Compare commits

..

No commits in common. "main" and "1.0.8-rc14" have entirely different histories.

168 changed files with 1362 additions and 26743 deletions

View file

@ -31,7 +31,6 @@ jobs:
steps: steps:
- name: Clone yavsc - name: Clone yavsc
run: | run: |
set -e
cd /src cd /src
git clone https://forgejo.pschneider.fr/notazof/yavsc.git _src git clone https://forgejo.pschneider.fr/notazof/yavsc.git _src
cd _src cd _src
@ -41,23 +40,12 @@ jobs:
fi fi
git submodule update --init --recursive git submodule update --init --recursive
echo "✅ Checked out at $(git rev-parse HEAD) on $(git branch --show-current 2>/dev/null || echo detached HEAD)" echo "✅ Checked out at $(git rev-parse HEAD) on $(git branch --show-current 2>/dev/null || echo detached HEAD)"
- name: Secret scan
run: |
echo "🔍 Scanning for secrets..."
cd /src/_src && dotnet tool restore && dotnet picket git --verbose --redact --exit-code 1 --log-opts -n10 \
- name: Build
run: |
echo "🏗️ Building the solution..."
cd /src/_src && dotnet build --verbosity normal
- name: Install SkiaSharp native dependencies
run: |
echo "📦 Installing libfontconfig/libfreetype for SkiaSharp (Avalonia.Headless)..."
apt-get update && apt-get install -y --no-install-recommends \
libfontconfig1 libfreetype6 libexpat1 zlib1g libbz2-1.0 libpng16-16 libbrotli1 \
&& rm -rf /var/lib/apt/lists/*
- name: Test - name: Test
run: | run: |
echo "🚀 Lancement des tests..." echo "🚀 Lancement des tests..."
cd /src/_src && dotnet test \ cd /src/_src && dotnet test \
--verbosity normal \ --verbosity normal \
--filter="Category!=Platform-Android" --filter="Category!=Platform-Android" \
--logger "xunit;LogFileName=test-results.xml" \
&& echo "✅ Success !" || echo "❌ Fail ($?)!"

View file

@ -175,12 +175,6 @@ jobs:
run: | run: |
cd /src/_src cd /src/_src
dotnet restore dotnet restore
- name: Test
run: |
cd /src/_src && dotnet test \
--verbosity normal \
--filter="Category!=Platform-Android" \
--logger "xunit;LogFileName=test-results.xml"
- name: Build de PostIt.Android ARM64 - name: Build de PostIt.Android ARM64
run: | run: |
@ -206,7 +200,6 @@ jobs:
RELEASE_BODY: ${{ env.RELEASE_BODY }} RELEASE_BODY: ${{ env.RELEASE_BODY }}
IS_PRERELEASE: ${{ env.IS_PRERELEASE }} IS_PRERELEASE: ${{ env.IS_PRERELEASE }}
run: | run: |
set -e
if [[ -z "$TAG" ]]; then if [[ -z "$TAG" ]]; then
echo "::error::No tag resolved for the API call." echo "::error::No tag resolved for the API call."
exit 1 exit 1

1
.gitignore vendored
View file

@ -35,7 +35,6 @@ appsettings-*.*.json
generated/ generated/
*.tmp *.tmp
tmp/
DataDir/ DataDir/
*.tests.trx *.tests.trx

View file

@ -1,45 +0,0 @@
# Exclure uniquement les dossiers de sortie de compilation
bin/
obj/
src/*/bin/
src/*/obj/
test/*/bin/
test/*/obj/
# Toolchain front (Node / esbuild)
node_modules/
build/
package-lock.json
# Exclure les caches lourds
.git/
.vs/
.env
.*.env
*.csproj.lscache
data/
appsettings.*.json
appsettings-*.*.json
# Exception: the Testing-environment override for Yavsc.Org is a tracked
# configuration source, not a secrets file. TestWebApplicationFactory
# (Yavsc.Org.Tests) flips ASPNETCORE_ENVIRONMENT to "Testing" so
# AddConfiguration("org") in Program.Main loads this file as the
# last in the chain (it is optional). It overrides the connection
# string and SMTP section for the in-memory test host and contains
# no production secrets.
!src/Yavsc.Org/appsettings-org.Testing.json
generated/
*.tmp
tmp/
DataDir/
*.tests.trx
*.tests.html
*.log

27
.vscode/launch.json vendored
View file

@ -4,22 +4,6 @@
// Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387 // Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{
"name": "PostIt Desktop",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj"
},
{
"name": "PostIt Desktop local",
"type": "coreclr",
"request": "launch",
"program": "${workspaceFolder}/src/PostIt/PostIt.Desktop/bin/Debug/net10.0/PostIt.Desktop.dll",
"env": {
"POSTIT_SETTINGS_JSON": "/home/paul/Workspace/yavsc/src/PostIt/PostIt/postit-settings.json"
},
"preLaunchTask": "dotnet: build-postit-desktop"
},
{ {
"name": "Android Debug", "name": "Android Debug",
"type": "mono", "type": "mono",
@ -36,10 +20,10 @@
"port": 55555 "port": 55555
}, },
{ {
"name": "Yavsc API", "name": "API",
"type": "dotnet", "type": "dotnet",
"request": "launch", "request": "launch",
"projectPath": "${workspaceFolder}/src/Yavsc.Api/Yavsc.Api.csproj" "projectPath": "${workspaceFolder}/src/Api/Api.csproj"
}, },
{ {
"name": "Yavsc Org", "name": "Yavsc Org",
@ -53,7 +37,12 @@
"request": "launch", "request": "launch",
"projectPath": "${workspaceFolder}/src/Yavsc.Blogs/Yavsc.Blogs.csproj" "projectPath": "${workspaceFolder}/src/Yavsc.Blogs/Yavsc.Blogs.csproj"
}, },
{
"name": "PostIt Desktop",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj",
},
{ {
"name": "Test PostIt.Android launch (Xamarin.UITest)", "name": "Test PostIt.Android launch (Xamarin.UITest)",
"type": "coreclr", "type": "coreclr",

42
.vscode/tasks.json vendored
View file

@ -47,10 +47,7 @@
"group": "build", "group": "build",
"isBuildCommand": true, "isBuildCommand": true,
"isTestCommand": false, "isTestCommand": false,
"isBackground": true, "isBackground": true
"options": {
"cwd": "${workspaceFolder}"
}
}, },
{ {
"label": "test blogs backend", "label": "test blogs backend",
@ -66,28 +63,6 @@
"isDefault": false "isDefault": false
} }
}, },
{
"label": "test api backend (npgsql)",
"type": "process",
"problemMatcher": "$msCompile",
"command": "dotnet",
"args": [
"test",
"Yavsc.Api.Test.csproj",
"-v",
"minimal"
],
"options": {
"cwd": "src/Yavsc.Api.Test",
"env": {
"YAVSC_API_TEST_DB_PROVIDER": "npgsql"
}
},
"group": {
"kind": "test",
"isDefault": false
}
},
{ {
"label": "build-webapi", "label": "build-webapi",
"type": "process", "type": "process",
@ -101,21 +76,6 @@
"kind": "build" "kind": "build"
}, },
"isBackground": true "isBackground": true
},
{
"label": "dotnet: build-postit-desktop",
"type": "process",
"isBuildCommand": true,
"isTestCommand": false,
"isBackground": true,
"command": "dotnet",
"args": ["build", "/property:GenerateFullPaths=true"],
"options": {
"cwd": "src/PostIt/PostIt.Desktop"
},
"group": {
"kind": "build"
}
} }
] ]
} }

View file

@ -48,4 +48,70 @@ docker-build:
docker-run: docker-run:
docker run -d -p 5000:5000 --name yavsc yavsc docker run -d -p 5000:5000 --name yavsc yavsc
.PHONY: test install docker-image docker-build docker-run # Crée une branche release/<V> depuis main, met à jour les
# `<Version>` des .csproj via dotnet-gitversion, et la
# pousse sur origin.
#
# Usage : make release V=1.0.7-rc1
#
# Pré-requis : être sur main, working tree clean. La cible
# vérifie les deux et refuse sinon — elle ne fait JAMAIS
# de checkout automatique, c'est à l'opérateur de s'être
# positionné sur la bonne branche au préalable (sinon le
# bump pourrait partir sur une branche tierce par accident).
#
# Notes :
# - Le nom de branche vient de l'argument V (ex: 1.0.7-rc1
# donne release/1.0.7-rc1). C'est une étiquette d'intention,
# pas la version assembly.
# - La version dans les .csproj vient de GitVersion qui la
# calcule depuis l'historique git (tag le plus proche +
# nombre de commits). C'est la version assembly réelle.
# - L'ordre (fetch → branche → bump → push) garantit qu'on
# part d'un main synchro et qu'on ne pollue pas main avec
# le bump (qui vit sur la branche release).
# - Fail-fast si la branche existe déjà en local ou sur origin.
release:
@if [ -z "$(V)" ]; then \
echo "Usage: make release V=<version>"; \
echo " V : version semver (ex. 1.0.7-rc1) — sert à nommer la branche."; \
exit 1; \
fi
@if [ -n "$$(git status --porcelain)" ]; then \
echo "Working tree sale, refus de créer une branche release."; \
git status --short; \
exit 1; \
fi
@BRANCH="release/$(V)"; \
if git show-ref --verify --quiet "refs/heads/$$BRANCH"; then \
echo "La branche $$BRANCH existe déjà en local."; \
echo " Pour la supprimer : git branch -D $$BRANCH"; \
exit 1; \
fi; \
if git ls-remote --exit-code --heads origin "$$BRANCH" >/dev/null 2>&1; then \
echo "La branche $$BRANCH existe déjà sur origin."; \
exit 1; \
fi; \
echo "==> Fetch + vérification synchro main"; \
git fetch origin main; \
if ! git merge-base --is-ancestor origin/main HEAD; then \
echo "main a avancé plus loin que HEAD. Fais :"; \
echo " git pull --ff-only origin main"; \
exit 1; \
fi; \
echo "==> Création de $$BRANCH depuis main"; \
git checkout -b "$$BRANCH"; \
echo "==> dotnet-gitversion /updateprojectfiles"; \
dotnet-gitversion /updateprojectfiles; \
echo "==> Commit du bump"; \
git add .; \
if git diff --cached --quiet; then \
echo "Pas de changements à committer (gitversion n'a produit aucune diff)."; \
else \
git commit -m "chore(release): bump version via gitversion for $(V)"; \
fi; \
echo "==> Push de $$BRANCH sur origin"; \
git push -u origin "$$BRANCH"; \
echo "==> Terminé. Branche $$BRANCH live sur origin."
.PHONY: test release

View file

@ -95,15 +95,6 @@ showConfig:
@echo CONFIGURATION: $(CONFIGURATION) @echo CONFIGURATION: $(CONFIGURATION)
@echo BASEAPPDIR: $(BASEAPPDIR) @echo BASEAPPDIR: $(BASEAPPDIR)
showApiLogs:
@sudo journalctl -u yavscApi.service -S "2 min ago" | tee yavscApi.log
showOrgLogs:
@sudo journalctl -u yavscOrg.service -S "2 min ago" | tee yavscOrg.log
showBlogsLogs:
@sudo journalctl -u yavscBlogs.service -S "2 min ago" | tee yavscBlogs.log
clean: clean:
@rm -rf generated @rm -rf generated

5
contrib/README.md Normal file
View file

@ -0,0 +1,5 @@
# Read me
## Note aux icones
㝉®🅬⛒⛑🩎🩺🞫🞮🞕🞖🞆🔴🔵🔲🖂🔧🔩🔐🔌💾💼💬💭👿👾🏷🎯🏹🌍🎎💩

View file

@ -1,13 +1,5 @@
{ {
"version": 1, "version": 1,
"isRoot": true, "isRoot": true,
"tools": { "tools": {}
"picket": {
"version": "0.2.12",
"commands": [
"picket"
],
"rollForward": false
}
}
} }

View file

@ -162,12 +162,6 @@ public class ActivitiesPageViewModelTests
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask; public ValueTask DisposeAsync() => ValueTask.CompletedTask;
} }
} }

View file

@ -352,12 +352,6 @@ public class BillingCommandPageViewModelTests
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask; public ValueTask DisposeAsync() => ValueTask.CompletedTask;
} }
} }

View file

@ -45,8 +45,10 @@ public class BillingQueriesPageViewModelTests
Assert.Equal(2, vm.Queries.Count); Assert.Equal(2, vm.Queries.Count);
Assert.All(vm.Queries, q => Assert.DoesNotContain("Rejected", q.StatusLabel, StringComparison.OrdinalIgnoreCase)); Assert.All(vm.Queries, q => Assert.DoesNotContain("Rejected", q.StatusLabel, StringComparison.OrdinalIgnoreCase));
Assert.Contains("lecture seule", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); Assert.Contains("lecture seule", vm.StatusMessage, StringComparison.OrdinalIgnoreCase);
Assert.False(vm.CanOpenDetails);
Assert.True(vm.Queries.Count > 0); vm.SelectedQuery = vm.Queries[0];
Assert.False(vm.OpenSelectedQueryCommand.CanExecute(null));
} }
private sealed class StubBillingApi : IYavscApiClient private sealed class StubBillingApi : IYavscApiClient
@ -127,12 +129,6 @@ public class BillingQueriesPageViewModelTests
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask; public ValueTask DisposeAsync() => ValueTask.CompletedTask;
} }
} }

View file

@ -1,270 +0,0 @@
using System.Net.Http;
using PostIt.ViewModels;
using Yavsc;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public class EstimateEditionPageViewModelTests
{
private static BillingQuerySummaryDto SampleQuery() => new()
{
Id = 42,
BillingCode = "Brush",
ActivityCode = "hair",
PerformerId = "perf-1",
ClientId = "cli-1",
Status = QueryStatus.InProgress,
Description = "Coupe simple",
EventDate = new DateTime(2026, 9, 12, 10, 0, 0, DateTimeKind.Utc),
};
private static EstimateEditionPageViewModel CreateViewModel(StubEstimateApi api, BillingQuerySummaryDto? query = null)
{
var client = new EstimateApiClient(api, "https://business.example/api/v1/");
return new EstimateEditionPageViewModel(query ?? SampleQuery(), client);
}
[Fact]
public void Constructor_prefills_description_and_adds_a_first_line()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
Assert.Equal("Coupe simple", vm.EstimateDescription);
Assert.Single(vm.Lines);
Assert.Same(vm.Lines[0], vm.SelectedLine);
Assert.Contains("#42", vm.ContextLabel);
Assert.Contains("cli-1", vm.ContextLabel);
}
[Fact]
public void AddLine_appends_and_selects_the_new_line()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.AddLineCommand.Execute(null);
Assert.Equal(2, vm.Lines.Count);
Assert.Same(vm.Lines[1], vm.SelectedLine);
}
[Fact]
public void RemoveLine_removes_the_selected_line()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
var first = vm.Lines[0];
vm.RemoveLineCommand.Execute(null);
Assert.Empty(vm.Lines);
Assert.Null(vm.SelectedLine);
Assert.False(vm.RemoveLineCommand.CanExecute(null));
Assert.DoesNotContain(first, vm.Lines);
}
[Fact]
public void Total_sums_line_totals_and_tracks_edits()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.Lines[0].Count = 2;
vm.Lines[0].UnitaryCost = 15.5m;
Assert.Equal(31m, vm.Total);
Assert.Equal($"{31m:0.00} EUR", vm.TotalLabel);
vm.AddLineCommand.Execute(null);
vm.Lines[1].Count = 1;
vm.Lines[1].UnitaryCost = 9m;
Assert.Equal(40m, vm.Total);
}
[Fact]
public async Task Send_without_title_warns_and_does_not_post()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].UnitaryCost = 25m;
await vm.SendCommand.ExecuteAsync(null);
Assert.Null(api.LastBody);
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
Assert.Contains("titre", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_without_any_line_warns_and_does_not_post()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines.Clear();
await vm.SendCommand.ExecuteAsync(null);
Assert.Null(api.LastBody);
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
Assert.Contains("ligne", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_with_a_blank_line_name_warns_and_does_not_post()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines[0].Description = "Oubli du nom";
await vm.SendCommand.ExecuteAsync(null);
Assert.Null(api.LastBody);
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
Assert.Contains("nom", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_posts_the_estimate_payload_to_the_estimate_route()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = " Devis coupe ";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].Count = 2.4m;
vm.Lines[0].UnitaryCost = 25m;
await vm.SendCommand.ExecuteAsync(null);
Assert.Equal("https://business.example/api/v1/estimate", api.LastPath);
Assert.Equal(HttpMethod.Post, api.LastMethod);
var payload = Assert.IsType<EstimateDto>(api.LastBody);
Assert.Equal(42, payload.CommandId);
Assert.Equal("cli-1", payload.ClientId);
Assert.Equal("Brush", payload.CommandType);
Assert.Equal("Devis coupe", payload.Title);
Assert.Equal("Coupe simple", payload.Description);
Assert.Empty(payload.AttachedFiles);
Assert.Empty(payload.AttachedGraphics);
var line = Assert.Single(payload.Bill);
Assert.Equal("Coupe", line.Name);
Assert.Equal(2, line.Count);
Assert.Equal(25m, line.UnitaryCost);
Assert.Equal("EUR", line.Currency);
}
[Fact]
public async Task Send_marks_the_page_as_sent_and_disables_resend()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].UnitaryCost = 25m;
await vm.SendCommand.ExecuteAsync(null);
Assert.True(vm.HasSent);
Assert.False(vm.SendCommand.CanExecute(null));
Assert.Equal("Devis envoyé", vm.SendLabel);
Assert.Equal(StatusSeverity.Info, vm.ActionStatus.Severity);
Assert.Contains("#7", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_surfaces_server_errors_as_error_status()
{
var api = new StubEstimateApi { Failure = new HttpRequestException("boom", null, System.Net.HttpStatusCode.InternalServerError) };
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
await vm.SendCommand.ExecuteAsync(null);
Assert.False(vm.HasSent);
Assert.Equal(StatusSeverity.Error, vm.ActionStatus.Severity);
Assert.True(vm.SendCommand.CanExecute(null));
}
[Fact]
public async Task Send_accepts_negative_amounts_for_discount_lines()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis avec remise";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].UnitaryCost = 25m;
vm.AddLineCommand.Execute(null);
vm.Lines[1].Name = "Remise fidélité";
vm.Lines[1].Description = "Remise client régulier";
vm.Lines[1].UnitaryCost = -5m;
Assert.Equal(20m, vm.Total);
await vm.SendCommand.ExecuteAsync(null);
var payload = Assert.IsType<EstimateDto>(api.LastBody);
Assert.Equal(2, payload.Bill.Count);
Assert.Equal(-5m, payload.Bill[1].UnitaryCost);
Assert.True(vm.HasSent);
}
private sealed class StubEstimateApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public string? LastPath { get; private set; }
public HttpMethod? LastMethod { get; private set; }
public object? LastBody { get; private set; }
public Exception? Failure { get; init; }
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
LastMethod = method;
LastPath = path;
LastBody = body;
if (Failure is not null)
{
throw Failure;
}
if (typeof(T) == typeof(EstimateCreatedDto))
{
var payload = (EstimateDto)body!;
var created = new EstimateCreatedDto { Id = 7, Bill = payload.Bill };
return Task.FromResult((T)(object)created);
}
return Task.FromResult(default(T)!);
}
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
LastMethod = method;
LastPath = path;
LastBody = body;
return Task.CompletedTask;
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -1,15 +0,0 @@
using PostIt.ViewModels;
namespace PostIt.Tests;
public class HomePageProviderFlowTests
{
[Fact]
public void HomePage_exposes_provider_requests_command()
{
var vm = new HomePageViewModel();
Assert.NotNull(vm.OpenProviderRequests);
Assert.True(vm.OpenProviderRequests.CanExecute(null));
}
}

View file

@ -8,8 +8,6 @@ using Yavsc.Blogspot;
using PostIt.Services; using PostIt.Services;
using PostIt.ViewModels; using PostIt.ViewModels;
using PostIt.Views; using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Helpers;
namespace PostIt.Tests; namespace PostIt.Tests;
@ -74,13 +72,13 @@ public class MainPageButtonsTests
{ } { }
} }
private static BlogsViewModel MakeViewModel(BlogPostDto? selectedPost = null) private static MainViewModel MakeViewModel(BlogPostDto? selectedPost = null)
{ {
var api = new ThrowingApi(); var api = new ThrowingApi();
var blog = new BlogApiClient(api, "http://localhost/"); var blog = new BlogApiClient(api, "http://localhost/");
var circle = new CircleApiClient(api, "http://localhost/"); var circle = new CircleApiClient(api, "http://localhost/");
var acl = new BlogAclApiClient(api, "http://localhost/"); var acl = new BlogAclApiClient(api, "http://localhost/");
// Minimal DI graph: only what BlogsViewModel resolves // Minimal DI graph: only what MainPageViewModel resolves
// when the user clicks a navigation button. Today that's // when the user clicks a navigation button. Today that's
// SignaturePageViewModel / CirclesPageViewModel / ACL // SignaturePageViewModel / CirclesPageViewModel / ACL
// dependencies. The graph intentionally stays local to this // dependencies. The graph intentionally stays local to this
@ -95,7 +93,7 @@ public class MainPageButtonsTests
services.AddTransient<SignaturePage>(); services.AddTransient<SignaturePage>();
services.AddTransient<CirclesPage>(); services.AddTransient<CirclesPage>();
services.AddTransient<PostAclDialog>(); services.AddTransient<PostAclDialog>();
var vm = new BlogsViewModel(blog, services: services.BuildServiceProvider()); var vm = new MainViewModel(blog, services: services.BuildServiceProvider());
if (selectedPost is not null) vm.SelectedPost = selectedPost; if (selectedPost is not null) vm.SelectedPost = selectedPost;
return vm; return vm;
} }
@ -103,7 +101,7 @@ public class MainPageButtonsTests
/// <summary> /// <summary>
/// Mount a real <see cref="MainView"/> (as /// Mount a real <see cref="MainView"/> (as
/// <c>SessionStatusBannerTests</c> does), push a /// <c>SessionStatusBannerTests</c> does), push a
/// <see cref="BlogsPage"/> with the given VM onto /// <see cref="MainPage"/> with the given VM onto
/// <c>NavRoot</c>. <c>PushAsync</c> is awaited (via /// <c>NavRoot</c>. <c>PushAsync</c> is awaited (via
/// <c>GetAwaiter().GetResult()</c>) so the page is on the /// <c>GetAwaiter().GetResult()</c>) so the page is on the
/// nav stack before the test tries to interact with its /// nav stack before the test tries to interact with its
@ -111,17 +109,13 @@ public class MainPageButtonsTests
/// realised and <c>KeyPressQwerty</c> has a real /// realised and <c>KeyPressQwerty</c> has a real
/// <see cref="TopLevel"/> to dispatch against. /// <see cref="TopLevel"/> to dispatch against.
/// </summary> /// </summary>
private static (MainView window, BlogsPage page) MountMainPage(BlogsViewModel vm) private static (MainView window, MainPage page) MountMainPage(MainViewModel vm)
{ {
var window = new MainView(); var window = new MainView();
var page = new BlogsPage { DataContext = vm }; var page = new MainPage { DataContext = vm };
var app = (PostIt.App)Application.Current!; var app = (PostIt.App)Application.Current!;
app.AttachMainWindow(window); app.AttachMainWindow(window);
window.NavRoot.PushAsync(page).GetAwaiter().GetResult(); window.NavRoot.PushAsync(page).GetAwaiter().GetResult();
var mainWindow = new Window { Content = window };
mainWindow.Show();
return (window, page); return (window, page);
} }
@ -151,7 +145,7 @@ public class MainPageButtonsTests
} }
[AvaloniaFact] [AvaloniaFact]
public async Task Acl_button_click_pushes_a_page_onto_nav_stack() public void Acl_button_click_pushes_a_page_onto_nav_stack()
{ {
// Arrange: a VM whose SelectedPost is non-null so // Arrange: a VM whose SelectedPost is non-null so
// CanManageAcl evaluates to true and the button is // CanManageAcl evaluates to true and the button is
@ -184,7 +178,7 @@ public class MainPageButtonsTests
} }
[AvaloniaFact] [AvaloniaFact]
public async Task Circles_button_click_pushes_a_page_onto_nav_stack() public void Circles_button_click_pushes_a_page_onto_nav_stack()
{ {
// Arrange: OpenCircles has no CanExecute guard today — // Arrange: OpenCircles has no CanExecute guard today —
// any click should fire it and push the page. // any click should fire it and push the page.
@ -209,7 +203,7 @@ public class MainPageButtonsTests
public void Signature_dev_button_click_pushes_a_page_onto_nav_stack() public void Signature_dev_button_click_pushes_a_page_onto_nav_stack()
{ {
// Arrange: the "[DEV] Signature" button is bound to the // Arrange: the "[DEV] Signature" button is bound to the
// BlogsViewModel.OpenSignatureDevCommand [RelayCommand]. // MainPageViewModel.OpenSignatureDevCommand [RelayCommand].
// The click must push SignaturePage on top of NavRoot. // The click must push SignaturePage on top of NavRoot.
// The ServiceCollection registered in MakeViewModel provides // The ServiceCollection registered in MakeViewModel provides
// SignaturePageViewModel so the command can resolve it via // SignaturePageViewModel so the command can resolve it via

View file

@ -5,11 +5,10 @@ using Yavsc.Blogspot;
using Yavsc.Api.Client; using Yavsc.Api.Client;
using PostIt.ViewModels; using PostIt.ViewModels;
using PostIt.Views; using PostIt.Views;
using PostIt.Views.Blogs;
namespace PostIt.Tests; namespace PostIt.Tests;
/// <summary> /// <summary>
/// Headless UI tests for the "Save" flow in <see cref="BlogsPage"/>. /// Headless UI tests for the "Save" flow in <see cref="MainPage"/>.
/// The pattern is the one <c>SessionStatusBannerTests</c> /// The pattern is the one <c>SessionStatusBannerTests</c>
/// established: <c>[AvaloniaFact]</c>, a <see cref="Window"/> /// established: <c>[AvaloniaFact]</c>, a <see cref="Window"/>
/// hosting the page (via a <see cref="Frame"/> because /// hosting the page (via a <see cref="Frame"/> because
@ -41,9 +40,9 @@ public class MainPageSaveTests
var recorder = new CallRecorder(); var recorder = new CallRecorder();
var api = new RecordingYavscApiClient(recorder); var api = new RecordingYavscApiClient(recorder);
var blog = new BlogApiClient(api, "http://localhost/"); var blog = new BlogApiClient(api, "http://localhost/");
var viewModel = new BlogsViewModel(blog); var viewModel = new MainViewModel(blog);
var page = new BlogsPage { DataContext = viewModel }; var page = new MainPage { DataContext = viewModel };
// MainPage is a ContentPage (a Page, not a Control), so it // MainPage is a ContentPage (a Page, not a Control), so it
// must be hosted in a navigation surface. The production // must be hosted in a navigation surface. The production
// MainWindow.axaml uses NavigationPage, and the API is the // MainWindow.axaml uses NavigationPage, and the API is the
@ -64,7 +63,9 @@ public class MainPageSaveTests
const string typed = "Mon premier billet"; const string typed = "Mon premier billet";
titleBox.Text = typed; titleBox.Text = typed;
var saveButton = page.SaveButton; var saveButton = window.GetVisualDescendants()
.OfType<Button>()
.Single(b => b.Content as string == "Save");
saveButton.Command!.Execute(null); saveButton.Command!.Execute(null);
// The Save command is async (RelayCommand over Task) but // The Save command is async (RelayCommand over Task) but

View file

@ -270,12 +270,6 @@ public class PostAclDialogTests
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask; public ValueTask DisposeAsync() => ValueTask.CompletedTask;
} }
} }

View file

@ -11,23 +11,25 @@ public class PostItViewModelTests
[Fact] [Fact]
public void SearchCommand_filters_posts_by_title_article_or_author() public void SearchCommand_filters_posts_by_title_article_or_author()
{ {
// BlogsViewModel no longer owns a BlogApiClient instance by // MainPageViewModel no longer owns a BlogApiClient instance by
// default; tests construct one with a fake YavscApiClient that // default; tests construct one with a fake YavscApiClient that
// throws on any call (we never call the API in this test). // throws on any call (we never call the API in this test).
var fakeApi = new ThrowingYavscApiClient(); var fakeApi = new ThrowingYavscApiClient();
var blog = new BlogApiClient(fakeApi, "http://localhost/"); var blog = new BlogApiClient(fakeApi, "http://localhost/");
var viewModel = new BlogsViewModel(blog); var viewModel = new MainViewModel(blog);
viewModel.Posts.Add(new BlogPostDto { Id = 1, Title = "First post", Article = "Hello world", AuthorId = "alice" }); viewModel.Posts.Add(new BlogPostDto { Id = 1, Title = "First post", Article = "Hello world", AuthorId = "alice" });
viewModel.Posts.Add(new BlogPostDto { Id = 2, Title = "Second post", Article = "Nothing here", AuthorId = "bob" }); viewModel.Posts.Add(new BlogPostDto { Id = 2, Title = "Second post", Article = "Nothing here", AuthorId = "bob" });
viewModel.Posts.Add(new BlogPostDto { Id = 3, Title = "Third post", Article = "Search me", AuthorId = "carol" }); viewModel.Posts.Add(new BlogPostDto { Id = 3, Title = "Third post", Article = "Search me", AuthorId = "carol" });
viewModel.SearchText = "search"; viewModel.SearchText = "search";
viewModel.SearchCommand.Execute(null);
Assert.Single(viewModel.FilteredPosts); Assert.Single(viewModel.FilteredPosts);
Assert.Equal(3, viewModel.FilteredPosts[0].Id); Assert.Equal(3, viewModel.FilteredPosts[0].Id);
viewModel.SearchText = "bob"; viewModel.SearchText = "bob";
viewModel.SearchCommand.Execute(null);
Assert.Single(viewModel.FilteredPosts); Assert.Single(viewModel.FilteredPosts);
Assert.Equal(2, viewModel.FilteredPosts[0].Id); Assert.Equal(2, viewModel.FilteredPosts[0].Id);
@ -58,7 +60,7 @@ public class PostItViewModelTests
{ {
var api = new RecordingPublishApi(); var api = new RecordingPublishApi();
var blog = new BlogApiClient(api, "http://localhost/"); var blog = new BlogApiClient(api, "http://localhost/");
var viewModel = new BlogsViewModel(blog); var viewModel = new MainViewModel(blog);
viewModel.SelectedPost = new BlogPostDto { Id = 42, IsPublished = false }; viewModel.SelectedPost = new BlogPostDto { Id = 42, IsPublished = false };
@ -144,12 +146,6 @@ public class PostItViewModelTests
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask; public ValueTask DisposeAsync() => ValueTask.CompletedTask;
} }
} }

View file

@ -1,238 +0,0 @@
using System.Net.Http;
using PostIt.ViewModels;
using Yavsc;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public class ProviderOngoingRequestsPageViewModelTests
{
[Fact]
public async Task RefreshAsync_calls_provider_endpoint_and_filters_out_unknown_billing_codes()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
Assert.Contains("https://business.example/api/v1/bill/provider/ongoing", api.Paths);
Assert.Equal(3, vm.Queries.Count);
Assert.Equal(12, vm.Queries[0].Id);
Assert.Equal(11, vm.Queries[1].Id);
Assert.Equal(10, vm.Queries[2].Id);
}
[Fact]
public async Task FilterText_filters_by_activity_code_and_status()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.FilterText = "mbrush";
Assert.Single(vm.Queries);
Assert.Equal("MBrush", vm.Queries[0].BillingCode);
vm.FilterText = "accepted";
Assert.Single(vm.Queries);
Assert.Equal(QueryStatus.Accepted, vm.Queries[0].Status);
}
[Fact]
public async Task OpenSelectedEditorCommand_can_execute_only_when_selection_exists()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
Assert.False(vm.OpenSelectedEditorCommand.CanExecute(null));
vm.SelectedQuery = vm.Queries[0];
Assert.True(vm.OpenSelectedEditorCommand.CanExecute(null));
}
[Fact]
public async Task SelectedSortOption_date_keeps_most_recent_first()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByDate;
Assert.Equal(new long[] { 12, 11, 10 }, vm.Queries.Select(q => q.Id).ToArray());
}
[Fact]
public async Task SelectedSortOption_date_ascending_keeps_oldest_first()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByDateAsc;
Assert.Equal(new long[] { 10, 11, 12 }, vm.Queries.Select(q => q.Id).ToArray());
}
[Fact]
public async Task SelectedSortOption_status_prioritizes_inprogress_then_accepted_then_inserted()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByStatus;
Assert.Equal(new long[] { 11, 12, 10 }, vm.Queries.Select(q => q.Id).ToArray());
}
[Fact]
public void Constructor_reads_saved_sort_option_from_settings()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var settings = new Settings
{
ProviderOngoingRequestsSortOption = ProviderOngoingRequestsPageViewModel.SortByStatus,
};
var vm = new ProviderOngoingRequestsPageViewModel(client, settings);
Assert.Equal(ProviderOngoingRequestsPageViewModel.SortByStatus, vm.SelectedSortOption);
}
[Fact]
public void Constructor_falls_back_to_default_when_saved_sort_is_invalid()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var settings = new Settings
{
ProviderOngoingRequestsSortOption = "invalide",
};
var vm = new ProviderOngoingRequestsPageViewModel(client, settings);
Assert.Equal(ProviderOngoingRequestsPageViewModel.SortByDate, vm.SelectedSortOption);
}
[Fact]
public async Task CreateEstimateForSelectedCommand_requires_a_selection()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var estimateClient = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client, estimateClient: estimateClient);
await vm.InitializeAsync();
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
vm.SelectedQuery = vm.Queries[0];
Assert.True(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
[Fact]
public async Task CreateEstimateForSelectedCommand_is_disabled_without_estimate_client()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedQuery = vm.Queries[0];
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
private sealed class StubProviderApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public List<string> Paths { get; } = new();
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
Paths.Add(path);
if (typeof(T) == typeof(List<BillingQuerySummaryDto>))
{
var data = new List<BillingQuerySummaryDto>
{
new()
{
Id = 10,
BillingCode = "Rdv",
ActivityCode = "dev",
PerformerId = "perf-1",
ClientId = "cli-1",
Status = QueryStatus.Inserted,
Description = "Rendez-vous",
EventDate = new DateTime(2026, 9, 10, 10, 0, 0, DateTimeKind.Utc),
},
new()
{
Id = 11,
BillingCode = "MBrush",
ActivityCode = "hair",
PerformerId = "perf-1",
ClientId = "cli-2",
Status = QueryStatus.InProgress,
Description = "Coupe multiple",
EventDate = new DateTime(2026, 9, 11, 10, 0, 0, DateTimeKind.Utc),
},
new()
{
Id = 12,
BillingCode = "Brush",
ActivityCode = "hair",
PerformerId = "perf-1",
ClientId = "cli-3",
Status = QueryStatus.Accepted,
Description = "Coupe simple",
EventDate = new DateTime(2026, 9, 12, 10, 0, 0, DateTimeKind.Utc),
},
new()
{
Id = 13,
BillingCode = "",
ActivityCode = "unknown",
PerformerId = "perf-1",
ClientId = "cli-4",
Status = QueryStatus.Accepted,
Description = "Doit être filtrée",
EventDate = new DateTime(2026, 9, 13, 10, 0, 0, DateTimeKind.Utc),
}
};
return Task.FromResult((T)(object)data);
}
return Task.FromResult(default(T)!);
}
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
Paths.Add(path);
return Task.CompletedTask;
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -74,12 +74,6 @@ public class RdvPageHeadlessTests
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
=> Task.CompletedTask; => Task.CompletedTask;
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask; public ValueTask DisposeAsync() => ValueTask.CompletedTask;
} }
} }

View file

@ -46,48 +46,35 @@ public partial class App : Application
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{ {
InitializeClassicDesktopLifetime(settings, desktop); var window = ServiceProvider.GetRequiredService<MainWindow>();
desktop.MainWindow = window;
View = window.MainView;
this.ConfigureRootView(window.MainView);
ApplyDarkMode(settings);
} }
else if (ApplicationLifetime is IActivityApplicationLifetime singleViewFactoryApplicationLifetime) else if (ApplicationLifetime is IActivityApplicationLifetime singleViewFactoryApplicationLifetime)
{ {
InitializeActivityLifetime(settings, singleViewFactoryApplicationLifetime); singleViewFactoryApplicationLifetime.MainViewFactory =
() =>
{
View = ServiceProvider.GetRequiredService<MainView>();
this.ConfigureRootView(View);
ApplyDarkMode(settings);
return View;
};
} }
else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform) else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
{ {
InitializeSingleViewLifetime(settings, singleViewPlatform); singleViewPlatform.MainView = View = ServiceProvider.GetRequiredService<MainView>();
ConfigureRootView(View);
ApplyDarkMode(settings);
} }
base.OnFrameworkInitializationCompleted(); base.OnFrameworkInitializationCompleted();
} }
public void InitializeSingleViewLifetime(Settings settings, ISingleViewApplicationLifetime singleViewPlatform) private void ConfigureRootView(MainView rootView)
{
singleViewPlatform.MainView = View = ServiceProvider!.GetRequiredService<MainView>();
ConfigureRootView(View);
ApplyDarkMode(settings);
}
public void InitializeActivityLifetime(Settings settings, IActivityApplicationLifetime singleViewFactoryApplicationLifetime)
{
singleViewFactoryApplicationLifetime.MainViewFactory =
() =>
{
this.ConfigureRootView(ServiceProvider!.GetRequiredService<MainView>());
ApplyDarkMode(settings);
return View!;
};
}
public void InitializeClassicDesktopLifetime(Settings settings, IClassicDesktopStyleApplicationLifetime desktop)
{
var window = ServiceProvider!.GetRequiredService<MainWindow>();
desktop.MainWindow = window;
this.ConfigureRootView(window.MainView);
ApplyDarkMode(settings);
}
public void ConfigureRootView(MainView rootView)
{ {
// Déclencher le Boot une seule fois lors du chargement du contrôle à l'écran. // Déclencher le Boot une seule fois lors du chargement du contrôle à l'écran.
rootView.AttachedToVisualTree += async (_, _) => await BootOnceAsync(); rootView.AttachedToVisualTree += async (_, _) => await BootOnceAsync();
@ -100,7 +87,6 @@ public partial class App : Application
}; };
rootView.SessionBanner.DataContext = sessionStatus; rootView.SessionBanner.DataContext = sessionStatus;
this.View = rootView;
} }
private async Task BootOnceAsync() private async Task BootOnceAsync()
@ -162,7 +148,7 @@ public partial class App : Application
public static async Task PushBlogsPageAsync() public static async Task PushBlogsPageAsync()
{ {
var app = (App)Current!; var app = (App)Current!;
var mainVm = app.ServiceProvider!.GetRequiredService<BlogsViewModel>(); var mainVm = app.ServiceProvider!.GetRequiredService<MainViewModel>();
await mainVm.InitializeAsync(); await mainVm.InitializeAsync();
await app.PushPageAsync(mainVm); await app.PushPageAsync(mainVm);
} }

View file

@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection;
using PostIt.Services; using PostIt.Services;
using PostIt.ViewModels; using PostIt.ViewModels;
using PostIt.Views; using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Views.Commands; using PostIt.Views.Commands;
using Yavsc.Api.Client; using Yavsc.Api.Client;
@ -30,13 +29,12 @@ public static class ServiceCollectionHelpers
() => settings.ApiUrl, () => settings.ApiUrl,
() => settings.Authentication?.Authority); () => settings.Authentication?.Authority);
var billingClient = new BillingApiClient(api, () => settings.ApiUrl); var billingClient = new BillingApiClient(api, () => settings.ApiUrl);
var estimateClient = new EstimateApiClient(api, () => settings.ApiUrl);
var userDirectory = new UserDirectory(userSearchClient); var userDirectory = new UserDirectory(userSearchClient);
var reverseGeocoding = new NominatimReverseGeocodingService(); var reverseGeocoding = new NominatimReverseGeocodingService();
// Vues // Vues
services.AddSingleton<MainView>(); services.AddSingleton<MainView>();
services.AddSingleton<BlogsPage>(); services.AddSingleton<MainPage>();
services.AddSingleton<MainWindow>(); services.AddSingleton<MainWindow>();
// SettingsPage is a singleton: there must be one and only one // SettingsPage is a singleton: there must be one and only one
@ -60,9 +58,6 @@ public static class ServiceCollectionHelpers
services.AddTransient<BrushPage>(); services.AddTransient<BrushPage>();
services.AddTransient<BillingQueriesPage>(); services.AddTransient<BillingQueriesPage>();
services.AddTransient<BillingQueryDetailsPage>(); services.AddTransient<BillingQueryDetailsPage>();
services.AddTransient<ProviderOngoingRequestsPage>();
services.AddTransient<EstimateEditionPage>();
// ViewModels // ViewModels
services.AddSingleton(settings); services.AddSingleton(settings);
services.AddSingleton<YavscApiClient>(api); services.AddSingleton<YavscApiClient>(api);
@ -72,7 +67,6 @@ public static class ServiceCollectionHelpers
services.AddSingleton(userSearchClient); services.AddSingleton(userSearchClient);
services.AddSingleton(activityClient); services.AddSingleton(activityClient);
services.AddSingleton(billingClient); services.AddSingleton(billingClient);
services.AddSingleton(estimateClient);
services.AddSingleton<IReverseGeocodingService>(reverseGeocoding); services.AddSingleton<IReverseGeocodingService>(reverseGeocoding);
services.AddSingleton<IUserDirectory>(userDirectory); services.AddSingleton<IUserDirectory>(userDirectory);
services.AddSingleton<HomePageViewModel>(); services.AddSingleton<HomePageViewModel>();
@ -95,7 +89,7 @@ public static class ServiceCollectionHelpers
sessionStatus.Refresh(); sessionStatus.Refresh();
services.AddSingleton(sessionStatus); services.AddSingleton(sessionStatus);
services.AddSingleton<SessionStatusBanner>(); services.AddSingleton<SessionStatusBanner>();
services.AddSingleton<BlogsViewModel>(); services.AddSingleton<MainViewModel>();
return services.BuildServiceProvider(); return services.BuildServiceProvider();
} }
} }

View file

@ -8,7 +8,7 @@ namespace PostIt.Helpers;
public static class ViewModelBaseHelpers public static class ViewModelBaseHelpers
{ {
public static async Task<Page> PushPageAsync(this App app, ViewModelBase vm) public static async Task PushPageAsync(this App app, ViewModelBase vm)
{ {
var window = app.View; var window = app.View;
if (window is null) if (window is null)
@ -43,11 +43,9 @@ public static class ViewModelBaseHelpers
var stack = window.NavRoot.NavigationStack; var stack = window.NavRoot.NavigationStack;
if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], page)) if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], page))
{ {
return page; return;
} }
await window.NavRoot.PushAsync(page); await window.NavRoot.PushAsync(page);
return page;
} }
} }

View file

@ -191,28 +191,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
object? body = null, object? body = null,
CancellationToken ct = default) CancellationToken ct = default)
{ {
using var response = await SendAsync(method, path, body is null ? null : () => JsonContent.Create(body), ct).ConfigureAwait(false); using var response = await SendAsync(method, path, body, ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
var dto = await JsonSerializer.DeserializeAsync<T>(stream,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }, ct).ConfigureAwait(false);
return dto!;
}
/// <summary>
/// Call a multipart endpoint, transparently refreshing the token if needed.
/// </summary>
public virtual async Task<T> CallAsync<T>(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default)
{
if (contentFactory is null)
throw new ArgumentNullException(nameof(contentFactory));
using var response = await SendAsync(method, path, contentFactory, ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false); await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
@ -238,23 +217,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
object? body = null, object? body = null,
CancellationToken ct = default) CancellationToken ct = default)
{ {
using var response = await SendAsync(method, path, body is null ? null : () => JsonContent.Create(body), ct).ConfigureAwait(false); using var response = await SendAsync(method, path, body, ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
}
/// <summary>
/// Call a multipart endpoint that returns no useful body (DELETE, etc.).
/// </summary>
public async Task CallAsync(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default)
{
if (contentFactory is null)
throw new ArgumentNullException(nameof(contentFactory));
using var response = await SendAsync(method, path, contentFactory, ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false); await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
} }
@ -269,7 +232,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
=> CallAsync(method, path, body: null, ct); => CallAsync(method, path, body: null, ct);
private async Task<HttpResponseMessage> SendAsync( private async Task<HttpResponseMessage> SendAsync(
HttpMethod method, string path, Func<HttpContent>? contentFactory, CancellationToken ct) HttpMethod method, string path, object? body, CancellationToken ct)
{ {
if (_tokens is null) if (_tokens is null)
throw new InvalidOperationException("Not logged in. Call LoginInteractiveAsync first."); throw new InvalidOperationException("Not logged in. Call LoginInteractiveAsync first.");
@ -277,8 +240,8 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
await EnsureFreshTokenAsync(ct).ConfigureAwait(false); await EnsureFreshTokenAsync(ct).ConfigureAwait(false);
using var req = new HttpRequestMessage(method, path); using var req = new HttpRequestMessage(method, path);
if (contentFactory is not null) if (body is not null)
req.Content = contentFactory(); req.Content = JsonContent.Create(body);
var response = await Http.SendAsync(req, ct).ConfigureAwait(false); var response = await Http.SendAsync(req, ct).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.Unauthorized) if (response.StatusCode == HttpStatusCode.Unauthorized)
@ -289,8 +252,8 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
await ForceRefreshAsync(ct).ConfigureAwait(false); await ForceRefreshAsync(ct).ConfigureAwait(false);
using var retry = new HttpRequestMessage(method, path); using var retry = new HttpRequestMessage(method, path);
if (contentFactory is not null) if (body is not null)
retry.Content = contentFactory(); retry.Content = JsonContent.Create(body);
response = await Http.SendAsync(retry, ct).ConfigureAwait(false); response = await Http.SendAsync(retry, ct).ConfigureAwait(false);
} }

View file

@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection;
using PostIt.ViewModels; using PostIt.ViewModels;
using PostIt.ViewModels.Commands; using PostIt.ViewModels.Commands;
using PostIt.Views; using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Views.Commands; using PostIt.Views.Commands;
namespace PostIt; namespace PostIt;
@ -39,7 +38,7 @@ public class ViewLocator : IDataTemplate
var services = app!.ServiceProvider!; var services = app!.ServiceProvider!;
return data switch return data switch
{ {
BlogsViewModel => services.GetRequiredService<BlogsPage>(), MainViewModel => services.GetRequiredService<MainPage>(),
Settings => services.GetRequiredService<SettingsPage>(), Settings => services.GetRequiredService<SettingsPage>(),
HomePageViewModel => services.GetRequiredService<HomePage>(), HomePageViewModel => services.GetRequiredService<HomePage>(),
ActivitiesPageViewModel => services.GetRequiredService<ActivitiesPage>(), ActivitiesPageViewModel => services.GetRequiredService<ActivitiesPage>(),
@ -52,8 +51,6 @@ public class ViewLocator : IDataTemplate
PostAclDialogViewModel => services.GetRequiredService<PostAclDialog>(), PostAclDialogViewModel => services.GetRequiredService<PostAclDialog>(),
BillingQueriesPageViewModel => services.GetRequiredService<BillingQueriesPage>(), BillingQueriesPageViewModel => services.GetRequiredService<BillingQueriesPage>(),
BillingQueryDetailsPageViewModel => services.GetRequiredService<BillingQueryDetailsPage>(), BillingQueryDetailsPageViewModel => services.GetRequiredService<BillingQueryDetailsPage>(),
ProviderOngoingRequestsPageViewModel => services.GetRequiredService<ProviderOngoingRequestsPage>(),
EstimateEditionPageViewModel => services.GetRequiredService<EstimateEditionPage>(),
null => new TextBlock { Text = "No view for <null>" }, null => new TextBlock { Text = "No view for <null>" },
_ => new TextBlock { Text = $"No view for {data.GetType().Name}" } _ => new TextBlock { Text = $"No view for {data.GetType().Name}" }
}; };

View file

@ -1,293 +0,0 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Avalonia;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PostIt.Helpers;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
/// <summary>
/// Edition d'un devis (<c>Estimate</c>) créé en réponse à une demande
/// client (<see cref="BillingQuerySummaryDto"/>) consultée depuis la
/// page « Mes demandes en cours ». L'envoi poste le devis sur
/// <c>api/v1/estimate</c>; côté serveur, la commande liée
/// (<see cref="BillingQuerySummaryDto.Id"/>) est alors marquée comme
/// validée par le prestataire.
/// </summary>
public partial class EstimateEditionPageViewModel : ViewModelBase, IActionStatusViewModel
{
private readonly EstimateApiClient _estimateClient;
private readonly BillingQuerySummaryDto _query;
public long QueryId => _query.Id;
public string ClientId => _query.ClientId;
public string BillingCode => _query.BillingCode;
public string Title => $"Devis — demande #{_query.Id}";
public string ContextLabel
=> $"Demande #{_query.Id} · {BillingCode} · client {ClientId}";
public string QueryDescription => string.IsNullOrWhiteSpace(_query.Description)
? "(sans description)"
: _query.Description;
[ObservableProperty]
public partial string EstimateTitle { get; set; } = string.Empty;
[ObservableProperty]
public partial string EstimateDescription { get; set; } = string.Empty;
[ObservableProperty]
public partial ObservableCollection<EstimateLineItemViewModel> Lines { get; set; } = new();
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(RemoveLineCommand))]
public partial EstimateLineItemViewModel? SelectedLine { get; set; }
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(SendCommand))]
public partial bool IsBusy { get; set; }
/// <summary>
/// True une fois le devis accepté par le serveur: l'envoi est
/// désactivé pour éviter les doublons, il ne reste que « Retour ».
/// </summary>
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(SendCommand))]
public partial bool HasSent { get; set; }
[ObservableProperty]
public partial string StatusMessage { get; set; } = "Prêt.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Prêt.");
public decimal Total => Lines.Sum(line => line.LineTotal);
public string TotalLabel => $"{Total:0.00} {Lines.FirstOrDefault()?.Currency ?? "EUR"}";
public string SendLabel => HasSent ? "Devis envoyé" : "Envoyer le devis";
public override bool CanNavigateNext
{
get => false;
protected set { _ = value; }
}
public override bool CanNavigatePrevious
{
get => true;
protected set { _ = value; }
}
public EstimateEditionPageViewModel(BillingQuerySummaryDto query, EstimateApiClient estimateClient)
{
_query = query ?? throw new ArgumentNullException(nameof(query));
_estimateClient = estimateClient ?? throw new ArgumentNullException(nameof(estimateClient));
EstimateDescription = query.Description ?? string.Empty;
Lines.CollectionChanged += OnLinesCollectionChanged;
AddLine();
this.SetInfoStatus("Complétez le devis puis envoyez-le. La demande associée sera validée.");
}
[RelayCommand]
private void AddLine()
{
var line = new EstimateLineItemViewModel();
Lines.Add(line);
SelectedLine = line;
}
private bool CanRemoveLine() => SelectedLine is not null && !IsBusy && !HasSent;
[RelayCommand(CanExecute = nameof(CanRemoveLine))]
private void RemoveLine()
{
if (SelectedLine is null)
{
return;
}
var index = Lines.IndexOf(SelectedLine);
Lines.Remove(SelectedLine);
SelectedLine = Lines.Count == 0
? null
: Lines[Math.Min(index, Lines.Count - 1)];
}
private bool CanSend() => !IsBusy && !HasSent;
[RelayCommand(CanExecute = nameof(CanSend))]
private async Task SendAsync()
{
if (!TryValidate(out var validationMessage))
{
this.SetWarningStatus(validationMessage);
return;
}
IsBusy = true;
try
{
var payload = BuildPayload();
var created = await _estimateClient.CreateAsync(payload).ConfigureAwait(true);
HasSent = true;
OnPropertyChanged(nameof(SendLabel));
this.SetInfoStatus(
$"Devis #{created.Id} envoyé ({created.Bill.Count} ligne(s)). La demande #{QueryId} est validée.");
}
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
this.SetWarningStatus("Accès refusé à l'API devis (scope 'api'). Déconnectez puis reconnectez-vous.");
}
catch (Exception ex)
{
this.SetErrorStatus($"Erreur lors de l'envoi du devis: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
[RelayCommand]
private async Task BackAsync()
{
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
await app.GoBackAsync().ConfigureAwait(true);
}
internal EstimateDto BuildPayload()
{
return new EstimateDto
{
CommandId = QueryId,
ClientId = ClientId,
CommandType = BillingCode,
Title = EstimateTitle.Trim(),
Description = EstimateDescription.Trim(),
Bill = Lines.Select(line => new EstimateLineDto
{
Id = line.Id,
Name = line.Name.Trim(),
Description = line.Description.Trim(),
Count = Math.Max(1, (int)Math.Round(line.Count)),
UnitaryCost = line.UnitaryCost,
Currency = string.IsNullOrWhiteSpace(line.Currency) ? "EUR" : line.Currency.Trim(),
}).ToList(),
};
}
private bool TryValidate(out string message)
{
if (string.IsNullOrWhiteSpace(EstimateTitle))
{
message = "Le titre du devis est requis.";
return false;
}
if (string.IsNullOrWhiteSpace(ClientId))
{
message = "La demande sélectionnée n'identifie pas de client.";
return false;
}
if (string.IsNullOrWhiteSpace(BillingCode))
{
message = "La demande sélectionnée n'a pas de code de facturation.";
return false;
}
if (Lines.Count == 0)
{
message = "Ajoutez au moins une ligne au devis.";
return false;
}
foreach (var line in Lines)
{
if (string.IsNullOrWhiteSpace(line.Name))
{
message = "Chaque ligne doit avoir un nom.";
return false;
}
if (line.Name.Trim().Length > 256)
{
message = $"Le nom de la ligne « {line.Name.Trim()[..20]}… » dépasse 256 caractères.";
return false;
}
if (string.IsNullOrWhiteSpace(line.Description))
{
message = $"La ligne « {line.Name.Trim()} » doit avoir une description.";
return false;
}
if (line.Description.Trim().Length > 512)
{
message = $"La description de la ligne « {line.Name.Trim()} » dépasse 512 caractères.";
return false;
}
if (line.Count < 1)
{
message = $"La quantité de la ligne « {line.Name.Trim()} » doit être d'au moins 1.";
return false;
}
}
message = string.Empty;
return true;
}
private void OnLinesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems is not null)
{
foreach (var item in e.OldItems.OfType<EstimateLineItemViewModel>())
{
item.PropertyChanged -= OnLinePropertyChanged;
}
}
if (e.NewItems is not null)
{
foreach (var item in e.NewItems.OfType<EstimateLineItemViewModel>())
{
item.PropertyChanged += OnLinePropertyChanged;
}
}
RaiseTotalsChanged();
}
private void OnLinePropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(EstimateLineItemViewModel.LineTotal)
or nameof(EstimateLineItemViewModel.Currency))
{
RaiseTotalsChanged();
}
}
private void RaiseTotalsChanged()
{
OnPropertyChanged(nameof(Total));
OnPropertyChanged(nameof(TotalLabel));
}
}

View file

@ -1,35 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace PostIt.ViewModels;
/// <summary>
/// Editable estimate line. <see cref="Count"/> is exposed as a
/// <see cref="decimal"/> so it binds directly to
/// <c>NumericUpDown.Value</c> (<c>decimal?</c>); it is rounded back
/// to an integer when the DTO is built.
/// </summary>
public partial class EstimateLineItemViewModel : ObservableObject
{
public long Id { get; set; }
[ObservableProperty]
public partial string Name { get; set; } = string.Empty;
[ObservableProperty]
public partial string Description { get; set; } = string.Empty;
[ObservableProperty, NotifyPropertyChangedFor(nameof(LineTotal))]
[NotifyPropertyChangedFor(nameof(LineTotalLabel))]
public partial decimal Count { get; set; } = 1m;
[ObservableProperty, NotifyPropertyChangedFor(nameof(LineTotal))]
[NotifyPropertyChangedFor(nameof(LineTotalLabel))]
public partial decimal UnitaryCost { get; set; }
[ObservableProperty]
public partial string Currency { get; set; } = "EUR";
public decimal LineTotal => Count * UnitaryCost;
public string LineTotalLabel => $"{LineTotal:0.00}";
}

View file

@ -1,390 +0,0 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Avalonia;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PostIt.Helpers;
using Yavsc;
using Yavsc.Abstract.Workflow;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActionStatusViewModel
{
public const string SortByDate = "Date (plus récent d'abord)";
public const string SortByDateAsc = "Date (plus ancien d'abord)";
public const string SortByStatus = "Statut (en cours d'abord)";
private readonly BillingApiClient _billingClient;
private readonly EstimateApiClient? _estimateClient;
private readonly Settings? _settings;
private List<BillingQuerySummaryDto> _allQueries = new();
[ObservableProperty]
public partial ObservableCollection<BillingQuerySummaryDto> Queries { get; set; } = new();
[ObservableProperty]
public partial string FilterText { get; set; } = string.Empty;
public IReadOnlyList<string> SortOptions { get; } = new[]
{
SortByDate,
SortByDateAsc,
SortByStatus,
};
[ObservableProperty]
public partial string SelectedSortOption { get; set; } = SortByDate;
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedQueryCommand))]
[NotifyCanExecuteChangedFor(nameof(OpenSelectedEditorCommand))]
[NotifyCanExecuteChangedFor(nameof(CreateEstimateForSelectedCommand))]
public partial BillingQuerySummaryDto? SelectedQuery { get; set; }
[ObservableProperty]
public partial bool IsBusy { get; set; }
[ObservableProperty]
public partial string StatusMessage { get; set; } = "Chargement des demandes fournisseur...";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Chargement des demandes fournisseur...");
public string Title => "Mes demandes en cours";
public override bool CanNavigateNext
{
get => false;
protected set { _ = value; }
}
public override bool CanNavigatePrevious
{
get => true;
protected set { _ = value; }
}
public ProviderOngoingRequestsPageViewModel(
BillingApiClient billingClient,
Settings? settings = null,
EstimateApiClient? estimateClient = null)
{
_billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient));
_estimateClient = estimateClient;
_settings = settings;
if (_settings is not null)
{
var preferredSort = NormalizeSortOption(_settings.ProviderOngoingRequestsSortOption);
if (!string.Equals(preferredSort, SelectedSortOption, StringComparison.Ordinal))
{
SelectedSortOption = preferredSort;
}
}
}
public Task InitializeAsync() => RefreshAsync();
[RelayCommand]
public async Task RefreshAsync()
{
IsBusy = true;
try
{
var items = await _billingClient.GetProviderOngoingQueriesAsync().ConfigureAwait(true) ?? new();
_allQueries = items
.Where(x => !string.IsNullOrWhiteSpace(x.BillingCode))
.OrderByDescending(x => x.EventDate ?? DateTime.MinValue)
.ThenByDescending(x => x.Id)
.ToList();
ApplyFilter();
this.SetInfoStatus(_allQueries.Count == 0
? "Aucune demande en cours pour votre profil fournisseur."
: $"{_allQueries.Count} demande(s) en cours chargée(s).");
}
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
_allQueries = new List<BillingQuerySummaryDto>();
Queries = new ObservableCollection<BillingQuerySummaryDto>();
this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous.");
}
catch (Exception ex)
{
_allQueries = new List<BillingQuerySummaryDto>();
Queries = new ObservableCollection<BillingQuerySummaryDto>();
this.SetErrorStatus($"Erreur: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
private bool CanOpenSelectedQuery() => SelectedQuery is not null;
private bool CanOpenSelectedEditor() => SelectedQuery is not null;
[RelayCommand(CanExecute = nameof(CanOpenSelectedQuery))]
public async Task OpenSelectedQueryAsync()
{
if (SelectedQuery is null)
{
this.SetWarningStatus("Sélectionnez une demande.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
IsBusy = true;
try
{
var details = await _billingClient
.GetQueryAsync(SelectedQuery.BillingCode, SelectedQuery.Id)
.ConfigureAwait(true);
var (activity, performer, form) = BuildNavigationContext(SelectedQuery);
var vm = new BillingQueryDetailsPageViewModel(
activity,
performer,
form,
_billingClient,
details,
isReadOnly: false);
await app.PushPageAsync(vm).ConfigureAwait(true);
}
catch (Exception ex)
{
this.SetErrorStatus($"Erreur lors de l'ouverture: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
[RelayCommand(CanExecute = nameof(CanOpenSelectedEditor))]
public async Task OpenSelectedEditorAsync()
{
if (SelectedQuery is null)
{
this.SetWarningStatus("Sélectionnez une demande.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
IsBusy = true;
try
{
var details = await _billingClient
.GetQueryAsync(SelectedQuery.BillingCode, SelectedQuery.Id)
.ConfigureAwait(true);
var (activity, performer, form) = BuildNavigationContext(SelectedQuery);
var vm = form.CreateCommandPageViewModel(activity, performer, _billingClient);
if (vm is null)
{
this.SetWarningStatus($"Le formulaire '{form.ActionName}' n'est pas pris en charge en édition.");
return;
}
await vm.InitializeAsync(details).ConfigureAwait(true);
await app.PushPageAsync(vm).ConfigureAwait(true);
}
catch (Exception ex)
{
this.SetErrorStatus($"Erreur lors de l'ouverture en édition: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
private bool CanCreateEstimateForSelected() => SelectedQuery is not null && _estimateClient is not null;
[RelayCommand(CanExecute = nameof(CanCreateEstimateForSelected))]
public async Task CreateEstimateForSelectedAsync()
{
if (SelectedQuery is null)
{
this.SetWarningStatus("Sélectionnez une demande.");
return;
}
if (_estimateClient is null)
{
this.SetWarningStatus("Le client devis n'est pas disponible.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
var vm = new EstimateEditionPageViewModel(SelectedQuery, _estimateClient);
await app.PushPageAsync(vm).ConfigureAwait(true);
}
partial void OnFilterTextChanged(string value)
{
ApplyFilter();
}
partial void OnSelectedSortOptionChanged(string value)
{
var normalized = NormalizeSortOption(value);
if (!string.Equals(normalized, value, StringComparison.Ordinal))
{
SelectedSortOption = normalized;
return;
}
PersistSortPreference(value);
ApplyFilter();
}
private void ApplyFilter()
{
var query = FilterText?.Trim();
var filtered = string.IsNullOrWhiteSpace(query)
? _allQueries
: _allQueries.Where(x =>
ContainsInsensitive(x.Description, query)
|| ContainsInsensitive(x.ActivityCode, query)
|| ContainsInsensitive(x.BillingCode, query)
|| ContainsInsensitive(x.ClientId, query)
|| ContainsInsensitive(x.Status.ToString(), query))
.ToList();
var sorted = ApplySort(filtered);
Queries = new ObservableCollection<BillingQuerySummaryDto>(sorted);
}
private List<BillingQuerySummaryDto> ApplySort(IEnumerable<BillingQuerySummaryDto> source)
{
if (string.Equals(SelectedSortOption, SortByStatus, StringComparison.Ordinal))
{
return source
.OrderBy(x => GetStatusRank(x.Status))
.ThenByDescending(x => x.EventDate ?? DateTime.MinValue)
.ThenByDescending(x => x.Id)
.ToList();
}
if (string.Equals(SelectedSortOption, SortByDateAsc, StringComparison.Ordinal))
{
return source
.OrderBy(x => x.EventDate ?? DateTime.MinValue)
.ThenBy(x => x.Id)
.ToList();
}
return source
.OrderByDescending(x => x.EventDate ?? DateTime.MinValue)
.ThenByDescending(x => x.Id)
.ToList();
}
private void PersistSortPreference(string selectedSort)
{
if (_settings is null)
{
return;
}
if (string.Equals(_settings.ProviderOngoingRequestsSortOption, selectedSort, StringComparison.Ordinal))
{
return;
}
_settings.ProviderOngoingRequestsSortOption = selectedSort;
try
{
_settings.Save();
}
catch
{
this.SetWarningStatus("Le tri a été appliqué, mais sa sauvegarde a échoué.");
}
}
private static string NormalizeSortOption(string? sortOption)
{
if (string.Equals(sortOption, SortByDate, StringComparison.Ordinal)
|| string.Equals(sortOption, SortByDateAsc, StringComparison.Ordinal)
|| string.Equals(sortOption, SortByStatus, StringComparison.Ordinal))
{
return sortOption!;
}
return SortByDate;
}
private static int GetStatusRank(QueryStatus status)
=> status switch
{
QueryStatus.InProgress => 0,
QueryStatus.Accepted => 1,
QueryStatus.Inserted => 2,
QueryStatus.Success => 3,
QueryStatus.Rejected => 4,
QueryStatus.Failed => 5,
_ => 99,
};
private static bool ContainsInsensitive(string? source, string query)
=> !string.IsNullOrWhiteSpace(source)
&& source.Contains(query, StringComparison.OrdinalIgnoreCase);
private static (ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form)
BuildNavigationContext(BillingQuerySummaryDto query)
{
var activity = new ActivityInfo
{
Code = query.ActivityCode,
Name = string.IsNullOrWhiteSpace(query.ActivityCode)
? "Activité"
: query.ActivityCode,
};
var performer = new ActivityUserDisplayItem
{
PerformerId = query.PerformerId,
UserName = "Mon profil fournisseur",
AvatarFallbackLabel = "M",
IsPerformerActive = true,
PerformerStatusBadgeLabel = "Actif",
PerformerStatusBadgeBackground = "#E6F7EC",
PerformerStatusBadgeBorder = "#2E7D32",
PerformerStatusBadgeForeground = "#1B5E20",
};
var form = new CommandFormSummary
{
ActionName = query.BillingCode,
Title = query.BillingCode,
};
return (activity, performer, form);
}
}

View file

@ -43,7 +43,7 @@ public partial class BillingQueriesPageViewModel : ViewModelBase, IActionStatusV
? $"Demandes en cours ({Form.Title})" ? $"Demandes en cours ({Form.Title})"
: $"Commandes {Form.Title}"; : $"Commandes {Form.Title}";
public string ContextLabel => $"{Performer.UserName} · {Activity.Name}"; public string ContextLabel => $"{Performer.UserName} · {Activity.Name}";
public bool CanOpenDetails => !IsReadOnly; public bool CanOpenDetails => true;
public override bool CanNavigateNext public override bool CanNavigateNext
{ {
@ -75,7 +75,7 @@ public partial class BillingQueriesPageViewModel : ViewModelBase, IActionStatusV
public Task InitializeAsync() => RefreshAsync(); public Task InitializeAsync() => RefreshAsync();
private bool CanOpenSelectedQuery() => CanOpenDetails && SelectedQuery is not null; private bool CanOpenSelectedQuery() => SelectedQuery is not null;
[RelayCommand] [RelayCommand]
public async Task RefreshAsync() public async Task RefreshAsync()

View file

@ -12,9 +12,6 @@ namespace PostIt.ViewModels.Commands;
public partial class RdvViewModel : BillingCommandPageViewModel public partial class RdvViewModel : BillingCommandPageViewModel
{ {
private long? _existingLocationId;
private bool _hydratingExistingQuery;
public override string SupportMessage => "Complétez les informations du rendez-vous puis postez la commande."; public override string SupportMessage => "Complétez les informations du rendez-vous puis postez la commande.";
[ObservableProperty] [ObservableProperty]
@ -59,7 +56,6 @@ public partial class RdvViewModel : BillingCommandPageViewModel
protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery) protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery)
{ {
_hydratingExistingQuery = true;
ExistingQueryId = existingQuery.Id; ExistingQueryId = existingQuery.Id;
CommandStatus = existingQuery.Status; CommandStatus = existingQuery.Status;
Consent = existingQuery.Consent; Consent = existingQuery.Consent;
@ -74,18 +70,11 @@ public partial class RdvViewModel : BillingCommandPageViewModel
if (existingQuery.Location is not null) if (existingQuery.Location is not null)
{ {
_existingLocationId = existingQuery.Location.Id;
Address = existingQuery.Location.Address ?? string.Empty; Address = existingQuery.Location.Address ?? string.Empty;
SuggestedAddress = string.Empty; SuggestedAddress = string.Empty;
Latitude = existingQuery.Location.Latitude; Latitude = existingQuery.Location.Latitude;
Longitude = existingQuery.Location.Longitude; Longitude = existingQuery.Location.Longitude;
} }
else
{
_existingLocationId = null;
}
_hydratingExistingQuery = false;
this.SetInfoStatus($"Commande #{existingQuery.Id} chargée."); this.SetInfoStatus($"Commande #{existingQuery.Id} chargée.");
} }
@ -128,22 +117,20 @@ public partial class RdvViewModel : BillingCommandPageViewModel
} }
} }
protected static BillingLocationDto BuildLocationPayload(string address, double? latitude, double? longitude, long? locationId = null) protected static object BuildLocationPayload(string address, double? latitude, double? longitude)
{ {
if (latitude.HasValue && longitude.HasValue) if (latitude.HasValue && longitude.HasValue)
{ {
return new BillingLocationDto return new
{ {
Id = locationId,
Address = address, Address = address,
Latitude = latitude.Value, Latitude = latitude.Value,
Longitude = longitude.Value, Longitude = longitude.Value,
}; };
} }
return new BillingLocationDto return new
{ {
Id = locationId,
Address = address, Address = address,
}; };
} }
@ -236,30 +223,6 @@ public partial class RdvViewModel : BillingCommandPageViewModel
OnPropertyChanged(nameof(EventDateSelection)); OnPropertyChanged(nameof(EventDateSelection));
} }
partial void OnAddressChanged(string value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
partial void OnLatitudeChanged(double? value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
partial void OnLongitudeChanged(double? value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
protected override async Task SubmitAsync() protected override async Task SubmitAsync()
{ {
@ -294,7 +257,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel
try try
{ {
var address = Address.Trim(); var address = Address.Trim();
var locationPayload = BuildLocationPayload(address, Latitude, Longitude, IsEditingExisting ? _existingLocationId : null); var locationPayload = BuildLocationPayload(address, Latitude, Longitude);
var payload = new BillingQueryDetailsDto var payload = new BillingQueryDetailsDto
{ {
@ -307,7 +270,12 @@ public partial class RdvViewModel : BillingCommandPageViewModel
Status = CommandStatus, Status = CommandStatus,
Reason = Reason.Trim(), Reason = Reason.Trim(),
AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? string.Empty : AdditionalInfo.Trim(), AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? string.Empty : AdditionalInfo.Trim(),
Location = locationPayload Location = new BillingLocationDto
{
Address = address,
Latitude = Latitude,
Longitude = Longitude,
}
}; };
if (IsEditingExisting) if (IsEditingExisting)

View file

@ -5,7 +5,6 @@ using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using PostIt.Helpers; using PostIt.Helpers;
using PostIt.Services; using PostIt.Services;
using Yavsc.Api.Client;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
public class HomePageViewModel : ViewModelBase public class HomePageViewModel : ViewModelBase
@ -31,12 +30,10 @@ public class HomePageViewModel : ViewModelBase
SessionStatus = sessionStatus; SessionStatus = sessionStatus;
OpenActivities = new AsyncRelayCommand(OpenActivitiesAsync); OpenActivities = new AsyncRelayCommand(OpenActivitiesAsync);
OpenProviderRequests = new AsyncRelayCommand(OpenProviderRequestsAsync);
OpenBlogs = new AsyncRelayCommand(App.PushBlogsPageAsync);
} }
public IAsyncRelayCommand OpenBlogs { get; } public IAsyncRelayCommand OpenBlogs { get; } = new AsyncRelayCommand(App.PushBlogsPageAsync);
public IAsyncRelayCommand OpenActivities { get; } public IAsyncRelayCommand OpenActivities { get; }
public IAsyncRelayCommand OpenProviderRequests { get; }
private async Task OpenActivitiesAsync() private async Task OpenActivitiesAsync()
{ {
@ -51,27 +48,6 @@ public class HomePageViewModel : ViewModelBase
await app.PushPageAsync(vm); await app.PushPageAsync(vm);
} }
private async Task OpenProviderRequestsAsync()
{
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
var billingClient = app.ServiceProvider?.GetRequiredService<BillingApiClient>();
if (billingClient is null)
{
throw new InvalidOperationException("Client billing indisponible.");
}
var estimateClient = app.ServiceProvider?.GetRequiredService<EstimateApiClient>();
var vm = new ProviderOngoingRequestsPageViewModel(billingClient, Settings, estimateClient);
await vm.InitializeAsync();
await app.PushPageAsync(vm);
}
/// <summary> /// <summary>
/// Avalonia designer constructor. Builds a self-contained VM /// Avalonia designer constructor. Builds a self-contained VM
/// with a freshly-constructed Settings so the XAML preview can /// with a freshly-constructed Settings so the XAML preview can

View file

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Avalonia; using Avalonia;
@ -9,12 +8,11 @@ using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Yavsc.Blogspot; using Yavsc.Blogspot;
using Yavsc.Api.Client; using Yavsc.Api.Client;
using Yavsc.Abstract.Files;
using PostIt.Helpers; using PostIt.Helpers;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
{ {
/// <summary>Window/tab title. Cosmetic — bound by /// <summary>Window/tab title. Cosmetic — bound by
/// <c>MainPage.axaml</c> if at all. Not the post title.</summary> /// <c>MainPage.axaml</c> if at all. Not the post title.</summary>
@ -68,9 +66,6 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
[ObservableProperty] [ObservableProperty]
public partial ObservableCollection<BlogPostDto> FilteredPosts { get; set; } public partial ObservableCollection<BlogPostDto> FilteredPosts { get; set; }
[ObservableProperty]
public partial ObservableCollection<BlogUploadFile> DraftAttachments { get; set; }
[ObservableProperty] [ObservableProperty]
public partial BlogPostDto? SelectedPost { get; set; } public partial BlogPostDto? SelectedPost { get; set; }
@ -96,6 +91,12 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
}); });
} }
[RelayCommand]
internal async Task SearchAsync() {
await RefreshAsync();
ApplyFilter();
}
[RelayCommand] [RelayCommand]
internal async Task SaveAsync() internal async Task SaveAsync()
{ {
@ -112,8 +113,6 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
await ExecuteAsync(async () => await ExecuteAsync(async () =>
{ {
var attachments = DraftAttachments.ToArray();
// Build a fresh BlogPostDto from the editor buffer on // Build a fresh BlogPostDto from the editor buffer on
// every Save — we no longer mutate SelectedPost in // every Save — we no longer mutate SelectedPost in
// place. The previous behaviour copied the buffer // place. The previous behaviour copied the buffer
@ -134,28 +133,11 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
DateModified = DateTime.UtcNow, DateModified = DateTime.UtcNow,
IsPublished = DraftIsPublished IsPublished = DraftIsPublished
}; };
var created = await BlogClient!.CreatePostAsync(draft, attachments); var created = await BlogClient!.CreatePostAsync(draft);
if (created is not null) if (created is not null)
{ {
SelectedPost = created; SelectedPost = created;
if (TryAppendAttachmentLinks(created, attachments))
{
var linkUpdate = new BlogPostDto
{
Id = created.Id,
AuthorId = created.AuthorId,
Photo = created.Photo,
Title = DraftTitle,
Article = DraftArticle ?? string.Empty,
DateCreated = created.DateCreated,
DateModified = DateTime.UtcNow,
};
await BlogClient.UpdatePostAsync(created.Id, linkUpdate);
}
this.SetInfoStatus($"Billet {created.Id} créé."); this.SetInfoStatus($"Billet {created.Id} créé.");
DraftAttachments.Clear();
} }
} }
else else
@ -170,26 +152,8 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
DateCreated = SelectedPost.DateCreated, DateCreated = SelectedPost.DateCreated,
DateModified = DateTime.UtcNow, DateModified = DateTime.UtcNow,
}; };
await BlogClient!.UpdatePostAsync(SelectedPost.Id, update);
await BlogClient!.UpdatePostAsync(SelectedPost.Id, update, attachments);
if (TryAppendAttachmentLinks(SelectedPost, attachments))
{
var linkUpdate = new BlogPostDto
{
Id = SelectedPost.Id,
AuthorId = SelectedPost.AuthorId,
Photo = SelectedPost.Photo,
Title = DraftTitle,
Article = DraftArticle ?? string.Empty,
DateCreated = SelectedPost.DateCreated,
DateModified = DateTime.UtcNow,
};
await BlogClient.UpdatePostAsync(SelectedPost.Id, linkUpdate);
}
this.SetInfoStatus($"Billet {SelectedPost.Id} enregistré."); this.SetInfoStatus($"Billet {SelectedPost.Id} enregistré.");
DraftAttachments.Clear();
} }
await RefreshPostsAsync(); await RefreshPostsAsync();
@ -372,7 +336,7 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
} }
public BlogsViewModel() public MainViewModel()
{ {
SettingsModel = new Settings(); SettingsModel = new Settings();
Init(SettingsModel); Init(SettingsModel);
@ -383,7 +347,6 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
{ {
Posts = new ObservableCollection<BlogPostDto>(); Posts = new ObservableCollection<BlogPostDto>();
FilteredPosts = new ObservableCollection<BlogPostDto>(); FilteredPosts = new ObservableCollection<BlogPostDto>();
DraftAttachments = new ObservableCollection<BlogUploadFile>();
SelectedPost = null; SelectedPost = null;
IsBusy = false; IsBusy = false;
this.SetInfoStatus("Prêt."); this.SetInfoStatus("Prêt.");
@ -433,7 +396,7 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
/// <see cref="BlogApiClient"/>. Production code uses the /// <see cref="BlogApiClient"/>. Production code uses the
/// (Settings, BlogApiClient) overload below. /// (Settings, BlogApiClient) overload below.
/// </summary> /// </summary>
public BlogsViewModel(BlogApiClient blogClient, Settings? settings = null, IServiceProvider? services = null) public MainViewModel(BlogApiClient blogClient, Settings? settings = null, IServiceProvider? services = null)
{ {
SettingsModel = new Settings(); SettingsModel = new Settings();
BlogClient = blogClient ?? throw new ArgumentNullException(nameof(blogClient)); ; BlogClient = blogClient ?? throw new ArgumentNullException(nameof(blogClient)); ;
@ -464,7 +427,6 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
// Mirror publication state too. Defaults to false on // Mirror publication state too. Defaults to false on
// null selection so a fresh draft starts unpublished. // null selection so a fresh draft starts unpublished.
DraftIsPublished = value?.IsPublished ?? false; DraftIsPublished = value?.IsPublished ?? false;
DraftAttachments.Clear();
UpdateCommandStates(); UpdateCommandStates();
} }
@ -546,55 +508,4 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
IsLoaded = true; IsLoaded = true;
} }
} }
private bool TryAppendAttachmentLinks(BlogPostDto post, IReadOnlyCollection<BlogUploadFile> attachments)
{
if (attachments.Count == 0)
return false;
var ownerSegment = post.Author?.UserName;
if (string.IsNullOrWhiteSpace(ownerSegment))
ownerSegment = post.AuthorId;
if (string.IsNullOrWhiteSpace(ownerSegment))
return false;
var article = DraftArticle ?? string.Empty;
var links = new List<string>();
foreach (var attachment in attachments)
{
var relativePath = $"{EscapePathSegment(ownerSegment)}/blogs/{post.Id}/{EscapePathSegment(attachment.FileName)}";
var fileUrl = ResolveUserFileUrl(relativePath);
var markdownLine = $"- [{attachment.FileName}]({fileUrl})";
if (!article.Contains(markdownLine, StringComparison.Ordinal))
links.Add(markdownLine);
}
if (links.Count == 0)
return false;
var prefix = article.Length == 0
? ""
: (article.EndsWith("\n", StringComparison.Ordinal) ? "\n" : "\n\n");
DraftArticle = article + prefix + string.Join("\n", links);
return true;
}
private string ResolveUserFileUrl(string relativePath)
{
var authority = Settings?.Authentication?.Authority;
if (!string.IsNullOrWhiteSpace(authority)
&& Uri.TryCreate(authority, UriKind.Absolute, out var baseUri))
{
return FileServerUrlHelpers.GetUserFilesUri(baseUri, relativePath).ToString();
}
return $"{Yavsc.Constants.UserFilesPath}/{relativePath}";
}
private static string EscapePathSegment(string segment)
=> Uri.EscapeDataString(segment);
} }

View file

@ -22,7 +22,7 @@ public partial class AuthenticationSettings : ObservableObject
public const string DefaultClientId = "postit"; public const string DefaultClientId = "postit";
public static readonly string[] DefaultScopes = { "blogs", "api" }; public static readonly string[] DefaultScopes = { "blogs" };
[ObservableProperty] [ObservableProperty]
public partial string Authority { get; set; } public partial string Authority { get; set; }

View file

@ -15,8 +15,7 @@ namespace PostIt.ViewModels;
public partial class Settings : ViewModelBase public partial class Settings : ViewModelBase
{ {
[JsonIgnore] const string SettingsFileName = "postit-settings.json";
public string? SettingsFileFullName { get; private set; }
[ObservableProperty] [ObservableProperty]
public partial AuthenticationSettings Authentication { get; set; } = new(); public partial AuthenticationSettings Authentication { get; set; } = new();
@ -33,67 +32,10 @@ public partial class Settings : ViewModelBase
[ObservableProperty] [ObservableProperty]
public partial string SearchText { get; set; } = string.Empty; public partial string SearchText { get; set; } = string.Empty;
[ObservableProperty]
public partial string ProviderOngoingRequestsSortOption { get; set; } = string.Empty;
[ObservableProperty] [ObservableProperty]
[JsonIgnore] [JsonIgnore]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
public bool Loaded { get; private set; } = false;
/// <summary>
/// True when the in-memory state has drifted from the last
/// <see cref="Load"/> or <see cref="Save"/> snapshot. The
/// Settings page binds the Sauver button's <c>IsEnabled</c> to
/// this flag, so it only enables when the user has actually
/// touched something since the last load / save. Cleared by
/// <see cref="Load"/> (and by <see cref="ApplyJson"/>), set by
/// every successful setter on the four top-level mutable
/// properties and on the sub-properties of
/// <see cref="Authentication"/>.
/// </summary>
[ObservableProperty]
public partial bool IsDirty { get; private set; } = false;
/// <summary>
/// Guards every mutation of the observable state. <c>[ObservableProperty]</c>
/// generates setters that call <c>SetProperty(...)</c> which fires
/// <c>PropertyChanged</c>. Avalonia bindings consume that event on
/// the UI thread, and a stray background-thread update is exactly
/// what crashed <c>DataValidationErrors.SetErrors</c> on
/// <c>postit://callback</c> re-launches. The lock makes mutations
/// atomic; <see cref="OnPropertyChanged(PropertyChangedEventArgs)"/>
/// then marshals the notification onto the UI thread so bindings
/// observe the change on the right thread.
/// </summary>
private readonly object _mutationGate = new();
/// <summary>
/// Scopes the PostIt client always requires from the OIDC provider,
/// regardless of what the user has in their settings file.
///
/// <para>PostIt calls into the Blog API (and any other Yavsc API
/// gated by an <c>[Authorize("…Scope")]</c> policy) and is silent
/// about the contract: a missing scope here surfaces as a 401
/// on the very first API call after login, with no obvious link
/// to the settings. The "feature" scopes the user must opt into
/// (e.g. <c>blogs</c>) are still their choice — we only force the
/// structural ones that OIDC itself needs.</para>
/// </summary>
private static readonly string[] BuiltInScopes = new[]
{
"openid", // OIDC: required for the id_token
"profile", // OIDC: standard profile claims
"offline_access", // OIDC: required to receive a refresh_token
"blogs",
"api"
};
private readonly string DEFAULT_SETTINGS_FILENAME = "postit-settings.json";
public void SetActionStatus(string message, StatusSeverity severity = StatusSeverity.Info) public void SetActionStatus(string message, StatusSeverity severity = StatusSeverity.Info)
{ {
ActionStatus = severity switch ActionStatus = severity switch
@ -120,7 +62,6 @@ public partial class Settings : ViewModelBase
partial void OnBlogsApiUrlChanged(string value) => MarkDirty(); partial void OnBlogsApiUrlChanged(string value) => MarkDirty();
partial void OnApiUrlChanged(string value) => MarkDirty(); partial void OnApiUrlChanged(string value) => MarkDirty();
partial void OnSearchTextChanged(string value) => MarkDirty(); partial void OnSearchTextChanged(string value) => MarkDirty();
partial void OnProviderOngoingRequestsSortOptionChanged(string value) => MarkDirty();
/// <summary> /// <summary>
/// Authentication can be reassigned wholesale by /// Authentication can be reassigned wholesale by
@ -141,6 +82,35 @@ public partial class Settings : ViewModelBase
MarkDirty(); MarkDirty();
} }
public bool Loaded { get; private set; } = false;
/// <summary>
/// True when the in-memory state has drifted from the last
/// <see cref="Load"/> or <see cref="Save"/> snapshot. The
/// Settings page binds the Sauver button's <c>IsEnabled</c> to
/// this flag, so it only enables when the user has actually
/// touched something since the last load / save. Cleared by
/// <see cref="Load"/> (and by <see cref="ApplyJson"/>), set by
/// every successful setter on the four top-level mutable
/// properties and on the sub-properties of
/// <see cref="Authentication"/>.
/// </summary>
[ObservableProperty]
public partial bool IsDirty { get; private set; } = false;
/// <summary>
/// Guards every mutation of the observable state. <c>[ObservableProperty]</c>
/// generates setters that call <c>SetProperty(...)</c> which fires
/// <c>PropertyChanged</c>. Avalonia bindings consume that event on
/// the UI thread, and a stray background-thread update is exactly
/// what crashed <c>DataValidationErrors.SetErrors</c> on
/// <c>postit://callback</c> re-launches. The lock makes mutations
/// atomic; <see cref="OnPropertyChanged(PropertyChangedEventArgs)"/>
/// then marshals the notification onto the UI thread so bindings
/// observe the change on the right thread.
/// </summary>
private readonly object _mutationGate = new();
/// <summary> /// <summary>
/// Build OidcClient options configured for Authorization Code + PKCE /// Build OidcClient options configured for Authorization Code + PKCE
/// (no client secret). The browser implementation should be supplied /// (no client secret). The browser implementation should be supplied
@ -204,6 +174,27 @@ public partial class Settings : ViewModelBase
Authentication.RefreshScopeListText(); Authentication.RefreshScopeListText();
} }
/// <summary>
/// Scopes the PostIt client always requires from the OIDC provider,
/// regardless of what the user has in their settings file.
///
/// <para>PostIt calls into the Blog API (and any other Yavsc API
/// gated by an <c>[Authorize("…Scope")]</c> policy) and is silent
/// about the contract: a missing scope here surfaces as a 401
/// on the very first API call after login, with no obvious link
/// to the settings. The "feature" scopes the user must opt into
/// (e.g. <c>blogs</c>) are still their choice — we only force the
/// structural ones that OIDC itself needs.</para>
/// </summary>
private static readonly string[] BuiltInScopes = new[]
{
"openid", // OIDC: required for the id_token
"profile", // OIDC: standard profile claims
"offline_access", // OIDC: required to receive a refresh_token
"blogs",
"api"
};
/// <summary> /// <summary>
/// Merge user-configured scopes with the built-in ones. User scopes /// Merge user-configured scopes with the built-in ones. User scopes
@ -256,42 +247,16 @@ public partial class Settings : ViewModelBase
return; return;
} }
} }
if (Environment.GetEnvironmentVariable("POSTIT_SETTINGS_JSON") is string envJson
&& !string.IsNullOrWhiteSpace(envJson))
{
Console.WriteLine("🔎 Loading settings from POSTIT_SETTINGS_JSON environment variable.");
FileInfo configByEnvFileInfo = new FileInfo(envJson);
if (!configByEnvFileInfo.Exists)
{
throw new Exception($"🩎 Settings file not found at {configByEnvFileInfo.FullName}");
}
string json = File.ReadAllText(configByEnvFileInfo.FullName);
ApplyJson(json, "POSTIT_SETTINGS_JSON");
SettingsFileFullName = configByEnvFileInfo.FullName;
Loaded = true;
return;
}
string configDir = Path.Combine( string configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt" "PostIt"
); );
Directory.CreateDirectory(configDir);
if (SettingsFileFullName is not null) string configPath = Path.Combine(configDir, SettingsFileName);
{
// Already set by a previous Load() or by the environment
// variable path above. Use it as-is.
}
else if (Environment.GetEnvironmentVariable("POSTIT_SETTINGS_JSON") is string envPath
&& !string.IsNullOrWhiteSpace(envPath))
{
SettingsFileFullName = envPath;
}
else
{
SettingsFileFullName = Path.Combine(configDir, "postit-settings.json");
}
FileInfo configFileInfo = new FileInfo(SettingsFileFullName); FileInfo configFileInfo = new FileInfo(configPath);
if (!configFileInfo.Exists) if (!configFileInfo.Exists)
{ {
@ -320,7 +285,6 @@ public partial class Settings : ViewModelBase
using var reader = new StreamReader(stream); using var reader = new StreamReader(stream);
var json = reader.ReadToEnd(); var json = reader.ReadToEnd();
ApplyJson(json, $"user file {configFileInfo.FullName}"); ApplyJson(json, $"user file {configFileInfo.FullName}");
SettingsFileFullName = configFileInfo.FullName;
Loaded = true; Loaded = true;
} }
catch (Exception ex) catch (Exception ex)
@ -372,7 +336,7 @@ public partial class Settings : ViewModelBase
// → our overridden dispatcher-safe marshaller below. // → our overridden dispatcher-safe marshaller below.
else lock (_mutationGate) else lock (_mutationGate)
{ {
var legacyApiUrl = TryReadApiUrl(json); var legacyApiUrl = TryReadLegacyApiUrl(json);
this.Authentication = settings.Authentication; this.Authentication = settings.Authentication;
this.DarkMode = settings.DarkMode; this.DarkMode = settings.DarkMode;
this.BlogsApiUrl = !string.IsNullOrWhiteSpace(settings.BlogsApiUrl) this.BlogsApiUrl = !string.IsNullOrWhiteSpace(settings.BlogsApiUrl)
@ -382,7 +346,6 @@ public partial class Settings : ViewModelBase
? settings.ApiUrl ? settings.ApiUrl
: this.ApiUrl; : this.ApiUrl;
this.SearchText = settings.SearchText ?? string.Empty; this.SearchText = settings.SearchText ?? string.Empty;
this.ProviderOngoingRequestsSortOption = settings.ProviderOngoingRequestsSortOption ?? string.Empty;
if (!(settings.Authentication is null)) if (!(settings.Authentication is null))
{ {
this.Authentication = new AuthenticationSettings(); this.Authentication = new AuthenticationSettings();
@ -428,7 +391,7 @@ public partial class Settings : ViewModelBase
} }
} }
private static string? TryReadApiUrl(string json) private static string? TryReadLegacyApiUrl(string json)
{ {
try try
{ {
@ -461,7 +424,6 @@ public partial class Settings : ViewModelBase
this.BlogsApiUrl = "https://blogs.pschneider.fr/api/v1/"; this.BlogsApiUrl = "https://blogs.pschneider.fr/api/v1/";
this.ApiUrl = "https://api.pschneider.fr/api/v1/"; this.ApiUrl = "https://api.pschneider.fr/api/v1/";
this.SearchText = string.Empty; this.SearchText = string.Empty;
this.ProviderOngoingRequestsSortOption = string.Empty;
} }
/// <summary> /// <summary>
@ -484,17 +446,11 @@ public partial class Settings : ViewModelBase
{ {
SetActionStatus("Enregistrement des parametres...", StatusSeverity.Info); SetActionStatus("Enregistrement des parametres...", StatusSeverity.Info);
if (SettingsFileFullName is null)
{
var configDir = Path.Combine( var configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt"); "PostIt");
Directory.CreateDirectory(configDir); Directory.CreateDirectory(configDir);
SettingsFileFullName = Path.Combine(configDir, DEFAULT_SETTINGS_FILENAME); var configPath = Path.Combine(configDir, SettingsFileName);
}
var configPath = SettingsFileFullName!;
Directory.CreateDirectory(Path.GetDirectoryName(configPath)!);
lock (_mutationGate) lock (_mutationGate)
{ {

View file

@ -23,8 +23,8 @@ public sealed class StatusNotice
(Glyph, Background, BorderBrush, Foreground) = severity switch (Glyph, Background, BorderBrush, Foreground) = severity switch
{ {
StatusSeverity.Error => ("!", "#7F1D1D", "#C62828", "#e1f0f6"), StatusSeverity.Error => ("!", "#FDECEA", "#C62828", "#7F1D1D"),
StatusSeverity.Warning => ("~", "#7C4A03", "#E6A700", "#eaeaea"), StatusSeverity.Warning => ("~", "#FFF8E1", "#E6A700", "#7C4A03"),
_ => ("i", "#E8F0FE", "#5B8DEF", "#1E3A8A"), _ => ("i", "#E8F0FE", "#5B8DEF", "#1E3A8A"),
}; };
} }

View file

@ -1,151 +0,0 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.EstimateEditionPage"
x:DataType="vm:EstimateEditionPageViewModel"
Header="Edition de devis">
<Grid RowDefinitions="Auto,Auto,*,Auto" Margin="12">
<StackPanel Grid.Row="0" Spacing="3">
<TextBlock Text="{Binding Title}"
FontSize="20"
FontWeight="Bold" />
<TextBlock Text="{Binding ContextLabel}" Opacity="0.75" />
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="Auto,8,*" Margin="0,10,0,8">
<Button Grid.Column="0"
Content="Retour"
Command="{Binding BackCommand}" />
</Grid>
<ScrollViewer Grid.Row="2">
<StackPanel Spacing="10">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10">
<Grid ColumnDefinitions="Auto,12,*" RowDefinitions="Auto,Auto,Auto" RowSpacing="8">
<TextBlock Grid.Row="0"
Grid.Column="0"
Text="Demande"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<TextBlock Grid.Row="0"
Grid.Column="2"
Text="{Binding QueryDescription}"
TextWrapping="Wrap"
Opacity="0.75" />
<TextBlock Grid.Row="1"
Grid.Column="0"
Text="Titre"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<TextBox Grid.Row="1"
Grid.Column="2"
Text="{Binding EstimateTitle}"
PlaceholderText="Titre du devis" />
<TextBlock Grid.Row="2"
Grid.Column="0"
Text="Description"
FontWeight="SemiBold"
VerticalAlignment="Top" />
<TextBox Grid.Row="2"
Grid.Column="2"
Text="{Binding EstimateDescription}"
PlaceholderText="Description détaillée du devis"
AcceptsReturn="True"
TextWrapping="Wrap"
MinHeight="70" />
</Grid>
</Border>
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto,8,Auto">
<TextBlock Grid.Column="0"
Text="Lignes du devis"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<Button Grid.Column="1"
Content="Ajouter une ligne"
Command="{Binding AddLineCommand}" />
<Button Grid.Column="3"
Content="Retirer la ligne"
Command="{Binding RemoveLineCommand}" />
</Grid>
<ListBox ItemsSource="{Binding Lines}"
SelectedItem="{Binding SelectedLine, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="vm:EstimateLineItemViewModel">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="6"
Padding="8"
Margin="0,0,0,8">
<Grid ColumnDefinitions="*,8,110,8,130,8,90"
RowDefinitions="Auto,Auto"
RowSpacing="6">
<TextBox Grid.Row="0"
Grid.Column="0"
Text="{Binding Name}"
PlaceholderText="Nom de la ligne" />
<NumericUpDown Grid.Row="0"
Grid.Column="2"
Value="{Binding Count}"
Minimum="1"
Increment="1"
FormatString="0" />
<NumericUpDown Grid.Row="0"
Grid.Column="4"
Value="{Binding UnitaryCost}"
Increment="0.5"
FormatString="0.00" />
<TextBlock Grid.Row="0"
Grid.Column="6"
Text="{Binding LineTotalLabel}"
VerticalAlignment="Center"
HorizontalAlignment="Right"
FontWeight="SemiBold" />
<TextBox Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="7"
Text="{Binding Description}"
PlaceholderText="Description de la ligne" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid ColumnDefinitions="*,Auto">
<TextBlock Grid.Column="1"
Text="{Binding TotalLabel, StringFormat='Total : {0}'}"
FontSize="16"
FontWeight="Bold"
HorizontalAlignment="Right" />
</Grid>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
<Grid Grid.Row="3" ColumnDefinitions="Auto,8,*,Auto" Margin="0,12,0,0">
<Button Grid.Column="0"
Content="{Binding SendLabel}"
Command="{Binding SendCommand}" />
<postitControls:StatusBar Grid.Column="2"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="3"
Width="120"
IsIndeterminate="True"
IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>
</ContentPage>

View file

@ -1,17 +0,0 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace PostIt.Views;
public partial class EstimateEditionPage : ContentPage
{
public EstimateEditionPage()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}

View file

@ -1,102 +0,0 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:dto="using:Yavsc.Api.Client"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.ProviderOngoingRequestsPage"
x:DataType="vm:ProviderOngoingRequestsPageViewModel"
Header="Mes demandes en cours">
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto" Margin="12">
<StackPanel Grid.Row="0" Spacing="3">
<TextBlock Text="{Binding Title}" FontSize="20" FontWeight="Bold" />
<TextBlock Text="Point de vue fournisseur" Opacity="0.75" />
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="Auto,8,Auto,8,*,8,Auto" Margin="0,10,0,8">
<Button Grid.Column="0" Content="Rafraîchir" Command="{Binding RefreshCommand}" />
<ComboBox Grid.Column="2"
Width="220"
ItemsSource="{Binding SortOptions}"
SelectedItem="{Binding SelectedSortOption, Mode=TwoWay}" />
<TextBox Grid.Column="4"
PlaceholderText="Filtrer: activité, code, client, statut..."
Text="{Binding FilterText, Mode=TwoWay}" />
<TextBlock Grid.Column="6"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Text="{Binding Queries.Count, StringFormat='Résultats : {0}'}"
Opacity="0.7" />
</Grid>
<TextBlock Grid.Row="2"
Text="Astuce: sélectionnez une ligne puis ouvrez le détail ou l'édition directe."
Opacity="0.65"
FontSize="11"
Margin="0,0,0,8" />
<Grid Grid.Row="3" RowDefinitions="*,Auto">
<ListBox Grid.Row="0"
ItemsSource="{Binding Queries}"
SelectedItem="{Binding SelectedQuery, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="dto:BillingQuerySummaryDto">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10"
Margin="0,0,0,8">
<Grid RowDefinitions="Auto,Auto" ColumnDefinitions="*,Auto">
<TextBlock Grid.Row="0"
Grid.Column="0"
Text="{Binding Description}"
FontWeight="Bold"
TextWrapping="Wrap" />
<TextBlock Grid.Row="0"
Grid.Column="1"
Text="{Binding Status}"
FontSize="11"
Opacity="0.75"
HorizontalAlignment="Right" />
<TextBlock Grid.Row="1"
Grid.Column="0"
Margin="0,6,0,0"
Text="{Binding ActivityCode, StringFormat='Activité : {0}'}"
FontSize="11"
Opacity="0.75" />
<TextBlock Grid.Row="1"
Grid.Column="1"
Margin="0,6,0,0"
Text="{Binding BillingCode, StringFormat='Code : {0}'}"
FontSize="11"
Opacity="0.65"
HorizontalAlignment="Right" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Row="1"
Orientation="Horizontal"
HorizontalAlignment="Right"
Margin="0,8,0,0"
Spacing="8">
<Button Content="Ouvrir le détail"
Command="{Binding OpenSelectedQueryCommand}" />
<Button Content="Ouvrir en édition"
Command="{Binding OpenSelectedEditorCommand}"
/>
<Button Content="Créer un devis"
Command="{Binding CreateEstimateForSelectedCommand}"
/>
</StackPanel>
</Grid>
<Grid Grid.Row="4" ColumnDefinitions="*,Auto" Margin="0,12,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>
</ContentPage>

View file

@ -1,17 +0,0 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace PostIt.Views;
public partial class ProviderOngoingRequestsPage : ContentPage
{
public ProviderOngoingRequestsPage()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}

View file

@ -1,151 +0,0 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:models="using:Yavsc.Blogspot"
xmlns:views="using:PostIt.Views.Blogs"
xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
mc:Ignorable="d"
x:Class="PostIt.Views.Blogs.BlogsPage"
x:DataType="vm:BlogsViewModel"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Design.DataContext>
<vm:BlogsViewModel />
</Design.DataContext>
<ScrollViewer
VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Disabled"
Padding="5"
Margin="5"
>
<StackPanel HorizontalAlignment="Stretch">
<StackPanel Orientation="Horizontal" Spacing="10" Margin="5">
<TextBlock Text="Blog Posts" FontSize="20" FontWeight="SemiBold" />
<TextBox HorizontalAlignment="Right"
Text="{Binding SearchText, Mode=TwoWay}" PlaceholderText="Filter by title or author..." />
</StackPanel>
<CommandBar IsDynamicOverflowEnabled="True"
HorizontalAlignment="Right" >
<CommandBar.PrimaryCommands>
<CommandBarButton Label="Refresh" Command="{Binding RefreshAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource RefreshIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton x:Name="SaveButton" Label="Save" Command="{Binding SaveAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource SaveIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton Label="Delete" Command="{Binding DeleteAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource DeleteIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton Label="Ajouter fichiers" Click="AddAttachment_Click"
x:Name="AddAttachmentButton">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource AddIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton x:Name="ManageAclButton"
Label="ACL"
Command="{Binding ManageAclAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource AclIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton x:Name="OpenCirclesButton"
Label="Mes cercles" Command="{Binding OpenCirclesAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource CircleIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarToggleButton Label="Publié"
IsChecked="{Binding DraftIsPublished, Mode=TwoWay}">
<CommandBarToggleButton.Icon>
<PathIcon Data="{StaticResource PublishedIcon}" />
</CommandBarToggleButton.Icon>
</CommandBarToggleButton>
<CommandBarButton x:Name="OpenSignatureDevButton"
Label="[DEV] Signature" Command="{Binding OpenSignatureDevAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource SignIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
</CommandBar.PrimaryCommands>
</CommandBar>
<Grid Margin="12" RowSpacing="12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0" ItemSpacing="10">
</WrapPanel>
<Border Grid.Row="1" BorderBrush="Gray" BorderThickness="1" Padding="8">
<ListBox ItemsSource="{Binding FilteredPosts}"
SelectedItem="{Binding SelectedPost, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="models:BlogPostDto">
<StackPanel Spacing="4">
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" />
<TextBlock Text="{Binding DateModified, StringFormat='Updated: {0:yyyy-MM-dd HH:mm}'}" FontSize="10" Foreground="Gray" />
<TextBlock Text="{Binding AuthorId}" FontSize="10" Foreground="DarkSlateGray" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<Border Grid.Row="2" BorderBrush="Gray" BorderThickness="1" Padding="8">
<Grid RowSpacing="10"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Text="Post detail" FontWeight="SemiBold" />
<TextBox x:Name="DraftTitleTextBox"
Grid.Row="1" Text="{Binding DraftTitle, Mode=TwoWay}" PlaceholderText="Title" />
<TextBox Grid.Row="2" PlaceholderText="Write something here !"
Text="{Binding DraftArticle, Mode=TwoWay}"
MinHeight="320"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
<Border Grid.Row="3" BorderBrush="LightGray" BorderThickness="1" Padding="8">
<StackPanel Spacing="4">
<TextBlock Text="Pièces jointes" FontWeight="SemiBold" />
<ItemsControl ItemsSource="{Binding DraftAttachments}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FileName}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<postitControls:StatusBar Grid.Row="4"
DataContext="{Binding ActionStatus}" />
</Grid>
</Border>
</Grid>
</StackPanel>
</ScrollViewer>
</ContentPage>

View file

@ -1,71 +0,0 @@
using System;
using System.IO;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using Avalonia.Controls.Primitives;
namespace PostIt.Views.Blogs;
public partial class BlogsPage : ContentPage
{
public BlogsPage()
{
InitializeComponent();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (DataContext is ViewModels.BlogsViewModel vm)
{
if (!vm.IsLoaded)
{
vm.RefreshAsync().Wait();
}
}
}
private async void AddAttachment_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel is null || DataContext is not ViewModels.BlogsViewModel vm)
return;
var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "Choisir des fichiers à joindre au billet",
AllowMultiple = true,
});
if (files.Count == 0)
return;
var uploads = new System.Collections.Generic.List<Yavsc.Api.Client.BlogUploadFile>(files.Count);
foreach (var file in files)
{
await using var stream = await file.OpenReadAsync();
using var memory = new MemoryStream();
await stream.CopyToAsync(memory);
uploads.Add(new Yavsc.Api.Client.BlogUploadFile(file.Name, memory.ToArray(), GetMimeType(file.Name)));
}
vm.DraftAttachments.Clear();
foreach (var upload in uploads)
vm.DraftAttachments.Add(upload);
}
private static string GetMimeType(string fileName)
{
var ext = Path.GetExtension(fileName)?.ToLowerInvariant();
return ext switch
{
".png" => "image/png",
".jpg" or ".jpeg" => "image/jpeg",
".webp" => "image/webp",
".gif" => "image/gif",
".pdf" => "application/pdf",
_ => "application/octet-stream"
};
}
}

View file

@ -34,13 +34,13 @@
<Grid Grid.Row="3" Margin="0,12,0,0" ColumnDefinitions="Auto,8,Auto,8,Auto,12,*"> <Grid Grid.Row="3" Margin="0,12,0,0" ColumnDefinitions="Auto,8,Auto,8,Auto,12,*">
<Button Grid.Column="0" <Button Grid.Column="0"
Content="Ouvrir le formulaire de demande" Content="Ouvrir le formulaire"
Command="{Binding OpenSelectedFormCommand}" /> Command="{Binding OpenSelectedFormCommand}" />
<Button Grid.Column="2" <Button Grid.Column="2"
Content="Voir les demandes non validées" Content="Voir les commandes"
Command="{Binding OpenQueriesCommand}" /> Command="{Binding OpenQueriesCommand}" />
<Button Grid.Column="4" <Button Grid.Column="4"
Content="Demandes en cours (validées, en lecture seule)" Content="Demandes en cours (lecture seule)"
Command="{Binding OpenOngoingQueriesCommand}" /> Command="{Binding OpenOngoingQueriesCommand}" />
<postitControls:StatusBar Grid.Column="6" <postitControls:StatusBar Grid.Column="6"
DataContext="{Binding ActionStatus}" /> DataContext="{Binding ActionStatus}" />

View file

@ -22,9 +22,5 @@
Command="{Binding OpenActivities}" Command="{Binding OpenActivities}"
HorizontalAlignment="Center" HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/> IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
<Button Content="Mes demandes en cours"
Command="{Binding OpenProviderRequests}"
HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
</StackPanel> </StackPanel>
</ContentPage> </ContentPage>

View file

@ -0,0 +1,114 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:models="using:Yavsc.Blogspot"
xmlns:views="using:PostIt.Views"
xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
mc:Ignorable="d"
x:Class="PostIt.Views.MainPage"
x:DataType="vm:MainViewModel"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Design.DataContext>
<vm:MainViewModel />
</Design.DataContext>
<Grid Margin="12" RowSpacing="12"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="0"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Padding="0">
<WrapPanel Orientation="Horizontal">
<Button Command="{Binding RefreshAsync}" Content="🗘 Refresh" />
<Button Command="{Binding SearchAsync}" Content="🔍 Filter" />
<Button Command="{Binding SaveAsync}" Content="Save" />
<Button Command="{Binding DeleteAsync}" Content="Delete" />
<Button x:Name="ManageAclButton"
Command="{Binding ManageAclAsync}"
Content="ACL" />
<Button x:Name="OpenCirclesButton"
Command="{Binding OpenCirclesAsync}"
Content="Mes cercles" />
<!-- Publication toggle: a CheckBox wired to
DraftIsPublished. Clicking it fires
TogglePublishCommand, which pushes the
new state to /api/blog/{id}/publish.
The CheckBox is the canonical
AvaloniaXaml 'toggle' surface; binding
IsChecked TwoWay keeps the visual state
and the buffer in sync. -->
<CheckBox Content="Publié"
IsChecked="{Binding DraftIsPublished, Mode=TwoWay}"
Command="{Binding TogglePublishAsync}"
VerticalAlignment="Center"/>
<!--
DEV ONLY: temporary shortcut to open the signature
capture page. Production entry point is a SignalR
push from Yavsc.Org ("devis received, sign here").
Remove this button and its Click handler in
MainPage.axaml.cs once the SignalR handler lands.
-->
<Button x:Name="OpenSignatureDevButton"
Command="{Binding OpenSignatureDevAsync}"
Content="[DEV] Signature"
ToolTip.Tip="DEV ONLY — to remove when SignalR handler lands" />
</WrapPanel>
</Border>
<Border Grid.Row="1" BorderBrush="Gray" BorderThickness="1" Padding="8">
<ListBox ItemsSource="{Binding FilteredPosts}" SelectedItem="{Binding SelectedPost, Mode=TwoWay}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinHeight="40">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="models:BlogPostDto">
<StackPanel Spacing="4">
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" />
<TextBlock Text="{Binding DateModified, StringFormat='Updated: {0:yyyy-MM-dd HH:mm}'}" FontSize="10" Foreground="Gray" />
<TextBlock Text="{Binding AuthorId}" FontSize="10" Foreground="DarkSlateGray" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<Border Grid.Row="2" BorderBrush="Gray" BorderThickness="1" Padding="8">
<Grid RowSpacing="10"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Text="Post detail" FontWeight="SemiBold" />
<TextBox Grid.Row="1" Text="{Binding DraftTitle, Mode=TwoWay}" PlaceholderText="Title" />
<TextBox Grid.Row="2" PlaceholderText="Write something here !"
Text="{Binding DraftArticle, Mode=TwoWay}"
MinHeight="320"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</TextBox>
<postitControls:StatusBar Grid.Row="3"
DataContext="{Binding ActionStatus}" />
</Grid>
</Border>
</Grid>
</ContentPage>

View file

@ -0,0 +1,25 @@
using System;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
namespace PostIt.Views;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (DataContext is ViewModels.MainViewModel vm)
{
if (!vm.IsLoaded)
{
vm.RefreshAsync().Wait();
}
}
}
}

View file

@ -6,11 +6,11 @@
xmlns:views="using:PostIt.Views" xmlns:views="using:PostIt.Views"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="PostIt.Views.MainView" x:Class="PostIt.Views.MainView"
x:DataType="vm:HomePageViewModel"> x:DataType="vm:MainViewModel">
<Design.DataContext> <Design.DataContext>
<!-- This only sets the DataContext for the previewer in an IDE, <!-- This only sets the DataContext for the previewer in an IDE,
to set the actual DataContext for runtime, set the DataContext property in code (look at App.axaml.cs) --> to set the actual DataContext for runtime, set the DataContext property in code (look at App.axaml.cs) -->
<vm:HomePageViewModel /> <vm:MainViewModel />
</Design.DataContext> </Design.DataContext>
<DockPanel LastChildFill="True"> <DockPanel LastChildFill="True">

View file

@ -13,7 +13,7 @@ public partial class MainView : UserControl
protected override void OnDataContextChanged(EventArgs e) protected override void OnDataContextChanged(EventArgs e)
{ {
base.OnDataContextChanged(e); base.OnDataContextChanged(e);
if (DataContext is ViewModels.BlogsViewModel vm) if (DataContext is ViewModels.MainViewModel vm)
{ {
if (!vm.IsLoaded) if (!vm.IsLoaded)
{ {

View file

@ -0,0 +1,15 @@
{
"Authentication": {
"ClientId": "postit",
"Authority": "https://yavsc.pschneider.fr"
},
"RedirectUri": "postit://callback",
"DarkMode": false,
"ApiUrl": "https://api.pschneider.fr/api/v1/",
"Scopes": [
"openid",
"profile",
"offline_access",
"blogs"
]
}

View file

@ -1,17 +0,0 @@
{
"Authentication": {
"ClientId": "postit",
"Authority": "https://yavsc.pschneider.fr",
"Scopes": [
"openid",
"profile",
"offline_access",
"blogs",
"api"
],
"RedirectUri": "postit://callback"
},
"DarkMode": false,
"ApiUrl": "https://api.pschneider.fr/api/v1/"
}

View file

@ -1,21 +1,15 @@
{ {
"Authentication": { "Authentication": {
"Authority": "https://localhost:5001",
"ClientId": "postit", "ClientId": "postit",
"Scopes": [ "Authority": "https://yavsc.pschneider.fr/"
"blogs",
"api"
],
"RedirectUri": "postit://callback"
}, },
"RedirectUri": "postit://callback",
"DarkMode": true, "DarkMode": true,
"BlogsApiUrl": "https://localhost:5003/api/v1/", "ApiUrl": "https://api.pschneider.fr/api/v1/",
"ApiUrl": "https://localhost:5005/api/v1/", "Scopes": [
"SearchText": "", "openid",
"ProviderOngoingRequestsSortOption": "", "profile",
"Loaded": true, "offline_access",
"IsDirty": true, "blogs"
"CanNavigateNext": false, ]
"CanNavigatePrevious": true,
"SaveCommand": {}
} }

View file

@ -1,67 +0,0 @@
namespace Yavsc.Abstract.Files;
/// <summary>
/// Helpers pour dériver les URL publiques des fichiers statiques à partir
/// d'une URL d'autorité OIDC ou d'un autre point d'entrée racine.
/// </summary>
public static class FileServerUrlHelpers
{
/// <summary>
/// Dérive la racine publique des fichiers utilisateur en alignant
/// le chemin sur <see cref="Yavsc.Constants.UserFilesPath"/>.
/// </summary>
/// <param name="authorityBaseUrl">
/// URL absolue de base, typiquement l'autorité OIDC de Yavsc.Org.
/// </param>
/// <returns>Une URL absolue pointant vers la racine des fichiers utilisateur.</returns>
public static Uri GetUserFilesBaseUri(Uri authorityBaseUrl)
{
ArgumentNullException.ThrowIfNull(authorityBaseUrl);
if (!authorityBaseUrl.IsAbsoluteUri)
{
throw new ArgumentException(
"The authority base URL must be absolute.",
nameof(authorityBaseUrl));
}
var baseString = authorityBaseUrl.GetLeftPart(UriPartial.Authority);
return new Uri(new Uri(baseString, UriKind.Absolute), EnsureTrailingSlash(Yavsc.Constants.UserFilesPath));
}
/// <summary>
/// Dérive la racine publique des fichiers utilisateur en alignant
/// le chemin sur <see cref="Yavsc.Constants.UserFilesPath"/>.
/// </summary>
/// <param name="authorityBaseUrl">
/// URL absolue de base, typiquement l'autorité OIDC de Yavsc.Org.
/// </param>
/// <returns>Une URL absolue pointant vers la racine des fichiers utilisateur.</returns>
public static Uri GetUserFilesBaseUri(string authorityBaseUrl)
=> GetUserFilesBaseUri(new Uri(authorityBaseUrl, UriKind.Absolute));
/// <summary>
/// Construit l'URL d'un fichier utilisateur à partir de la base d'autorité
/// et d'un chemin relatif sous la racine des fichiers.
/// </summary>
public static Uri GetUserFilesUri(Uri authorityBaseUrl, string relativePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
var baseUri = GetUserFilesBaseUri(authorityBaseUrl);
return new Uri(baseUri, NormalizeRelativePath(relativePath));
}
/// <summary>
/// Construit l'URL d'un fichier utilisateur à partir de la base d'autorité
/// et d'un chemin relatif sous la racine des fichiers.
/// </summary>
public static Uri GetUserFilesUri(string authorityBaseUrl, string relativePath)
=> GetUserFilesUri(new Uri(authorityBaseUrl, UriKind.Absolute), relativePath);
private static string EnsureTrailingSlash(string path)
=> path.EndsWith("/", StringComparison.Ordinal) ? path : path + "/";
private static string NormalizeRelativePath(string relativePath)
=> relativePath.TrimStart('/');
}

View file

@ -44,6 +44,7 @@ namespace Yavsc.Abstract.IT
public bool Validate() public bool Validate()
{ {
// this is a n*n task // this is a n*n task
throw new NotImplementedException(); throw new NotImplementedException();
} }

View file

@ -1,12 +0,0 @@
namespace Yavsc.Models.Access
{
using Yavsc.Abstract.Identity.Security;
public class FileAccessControlRulePayload : CircleAuthorization
{
public virtual string Path { get; set; }
}
}

View file

@ -77,14 +77,6 @@ public sealed class BillingApiClient
return items; return items;
} }
public Task<List<BillingQuerySummaryDto>> GetProviderOngoingQueriesAsync(CancellationToken ct = default)
{
return _api.CallAsync<List<BillingQuerySummaryDto>>(
HttpMethod.Get,
Absolute("bill/provider/ongoing"),
ct: ct);
}
public async Task<BillingQueryDetailsDto> GetQueryAsync(string billingCode, long queryId, CancellationToken ct = default) public async Task<BillingQueryDetailsDto> GetQueryAsync(string billingCode, long queryId, CancellationToken ct = default)
{ {
if (string.IsNullOrWhiteSpace(billingCode)) if (string.IsNullOrWhiteSpace(billingCode))
@ -164,7 +156,6 @@ public sealed class BillingApiClient
? null ? null
: new BillingLocationDto : new BillingLocationDto
{ {
Id = dto.Location.Id > 0 ? dto.Location.Id : null,
Address = dto.Location.Address ?? string.Empty, Address = dto.Location.Address ?? string.Empty,
Latitude = dto.Location.Latitude, Latitude = dto.Location.Latitude,
Longitude = dto.Location.Longitude, Longitude = dto.Location.Longitude,
@ -192,7 +183,6 @@ public sealed class BillingApiClient
? null ? null
: new BillingLocationDto : new BillingLocationDto
{ {
Id = dto.Location.Id > 0 ? dto.Location.Id : null,
Address = dto.Location.Address ?? string.Empty, Address = dto.Location.Address ?? string.Empty,
Latitude = dto.Location.Latitude, Latitude = dto.Location.Latitude,
Longitude = dto.Location.Longitude, Longitude = dto.Location.Longitude,
@ -222,7 +212,6 @@ public sealed class BillingApiClient
? null ? null
: new BillingLocationDto : new BillingLocationDto
{ {
Id = dto.Location.Id > 0 ? dto.Location.Id : null,
Address = dto.Location.Address ?? string.Empty, Address = dto.Location.Address ?? string.Empty,
Latitude = dto.Location.Latitude, Latitude = dto.Location.Latitude,
Longitude = dto.Location.Longitude, Longitude = dto.Location.Longitude,
@ -316,11 +305,6 @@ public sealed class BillingApiClient
["Address"] = location.Address, ["Address"] = location.Address,
}; };
if (location.Id.HasValue && location.Id.Value > 0)
{
payload["Id"] = location.Id.Value;
}
if (location.Latitude.HasValue) if (location.Latitude.HasValue)
{ {
payload["Latitude"] = location.Latitude.Value; payload["Latitude"] = location.Latitude.Value;
@ -336,7 +320,6 @@ public sealed class BillingApiClient
private sealed class BillingLocationResponse private sealed class BillingLocationResponse
{ {
public long Id { get; set; }
public string? Address { get; set; } public string? Address { get; set; }
public double Latitude { get; set; } public double Latitude { get; set; }
public double Longitude { get; set; } public double Longitude { get; set; }

View file

@ -1,5 +1,8 @@
using System.Net.Http.Headers; using System;
using System.Text.Json; using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Yavsc.Blogspot; using Yavsc.Blogspot;
namespace Yavsc.Api.Client; namespace Yavsc.Api.Client;
@ -59,18 +62,11 @@ public sealed class BlogApiClient
public Task<BlogPostDto?> GetPostAsync(long id, CancellationToken ct = default) public Task<BlogPostDto?> GetPostAsync(long id, CancellationToken ct = default)
=> _api.CallAsync<BlogPostDto?>(HttpMethod.Get, $"{_pathPrefix}/{id}", ct: ct); => _api.CallAsync<BlogPostDto?>(HttpMethod.Get, $"{_pathPrefix}/{id}", ct: ct);
public Task<BlogPostDto?> CreatePostAsync( public Task<BlogPostDto?> CreatePostAsync(BlogPostDto post, CancellationToken ct = default)
BlogPostDto post, => _api.CallAsync<BlogPostDto?>(HttpMethod.Post, _pathPrefix, body: post, ct: ct);
IReadOnlyCollection<BlogUploadFile>? files = null,
CancellationToken ct = default)
=> SendPostAsync(HttpMethod.Post, _pathPrefix, post, files, ct);
public Task UpdatePostAsync( public Task UpdatePostAsync(long id, BlogPostDto post, CancellationToken ct = default)
long id, => _api.CallAsync(HttpMethod.Put, $"{_pathPrefix}/{id}", body: post, ct: ct);
BlogPostDto post,
IReadOnlyCollection<BlogUploadFile>? files = null,
CancellationToken ct = default)
=> SendPostAsync(HttpMethod.Put, $"{_pathPrefix}/{id}", post, files, ct);
public Task DeletePostAsync(long id, CancellationToken ct = default) public Task DeletePostAsync(long id, CancellationToken ct = default)
=> _api.CallAsync(HttpMethod.Delete, $"{_pathPrefix}/{id}", ct: ct); => _api.CallAsync(HttpMethod.Delete, $"{_pathPrefix}/{id}", ct: ct);
@ -85,39 +81,4 @@ public sealed class BlogApiClient
public Task SetPublishAsync(long id, bool publish, CancellationToken ct = default) public Task SetPublishAsync(long id, bool publish, CancellationToken ct = default)
=> _api.CallAsync(HttpMethod.Put, $"{_pathPrefix}/{id}/publish", => _api.CallAsync(HttpMethod.Put, $"{_pathPrefix}/{id}/publish",
body: new { publish }, ct: ct); body: new { publish }, ct: ct);
private async Task<BlogPostDto?> SendPostAsync(
HttpMethod method,
string path,
BlogPostDto post,
IReadOnlyCollection<BlogUploadFile>? files,
CancellationToken ct)
{
if (files is null || files.Count == 0)
return await _api.CallAsync<BlogPostDto?>(method, path, body: post, ct: ct);
return await _api.CallAsync<BlogPostDto?>(method, path, () => CreateMultipartContent(post, files), ct: ct);
}
private static HttpContent CreateMultipartContent(BlogPostDto post, IReadOnlyCollection<BlogUploadFile> files)
{
var content = new MultipartFormDataContent();
var blogJson = JsonSerializer.Serialize(post, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
});
content.Add(new StringContent(blogJson), "blog");
foreach (var file in files)
{
var fileContent = new ByteArrayContent(file.Content);
fileContent.Headers.ContentType = new MediaTypeHeaderValue(
string.IsNullOrWhiteSpace(file.ContentType) ? "application/octet-stream" : file.ContentType);
content.Add(fileContent, "file", file.FileName);
}
return content;
}
} }

View file

@ -1,6 +0,0 @@
namespace Yavsc.Api.Client;
/// <summary>
/// Buffered file payload for multipart blog uploads.
/// </summary>
public sealed record BlogUploadFile(string FileName, byte[] Content, string? ContentType = null);

View file

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json.Serialization;
using Yavsc; using Yavsc;
namespace Yavsc.Api.Client; namespace Yavsc.Api.Client;
@ -30,14 +29,7 @@ public sealed class BillingQueryDetailsDto
public sealed class BillingLocationDto public sealed class BillingLocationDto
{ {
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public long? Id { get; set; }
public string Address { get; set; } = string.Empty; public string Address { get; set; } = string.Empty;
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public double? Latitude { get; set; } public double? Latitude { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public double? Longitude { get; set; } public double? Longitude { get; set; }
} }

View file

@ -1,52 +0,0 @@
using System;
using System.Collections.Generic;
namespace Yavsc.Api.Client;
/// <summary>
/// A single billable line of an estimate, mirroring the JSON shape of
/// the server-side <c>Yavsc.Models.Billing.CommandLine</c> entity.
/// </summary>
public sealed class EstimateLineDto
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public int Count { get; set; } = 1;
public decimal UnitaryCost { get; set; }
public long EstimateId { get; set; }
public string Currency { get; set; } = "EUR";
}
/// <summary>
/// Estimate payload exchanged with the <c>api/v1/estimate</c> routes
/// (<c>EstimateApiController</c>). <see cref="AttachedGraphics"/> and
/// <see cref="AttachedFiles"/> are always initialised: the server-side
/// entity reads them from non-nullable string properties and a null
/// list would break its serialisation.
/// </summary>
public sealed class EstimateDto
{
public long Id { get; set; }
public long? CommandId { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public List<EstimateLineDto> Bill { get; set; } = new();
public List<string> AttachedGraphics { get; set; } = new();
public List<string> AttachedFiles { get; set; } = new();
public string? OwnerId { get; set; }
public string ClientId { get; set; } = string.Empty;
public string CommandType { get; set; } = string.Empty;
public DateTime ProviderValidationDate { get; set; }
public DateTime ClientValidationDate { get; set; }
}
/// <summary>
/// Response of a successful estimate creation
/// (<c>Ok(new { estimate.Id, estimate.Bill })</c>).
/// </summary>
public sealed class EstimateCreatedDto
{
public long Id { get; set; }
public List<EstimateLineDto> Bill { get; set; } = new();
}

View file

@ -1,110 +0,0 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Yavsc.Api.Client;
/// <summary>
/// HTTP client for the estimate routes (<c>api/v1/estimate</c>,
/// served by <c>EstimateApiController</c>). Follows the same
/// DTO↔path mapper shape as <see cref="BillingApiClient"/>: all
/// transport concerns (base URL, JSON, Bearer auth, silent refresh
/// on 401) are delegated to <see cref="IYavscApiClient"/>.
/// </summary>
public sealed class EstimateApiClient
{
private const string PathPrefix = "estimate";
private readonly IYavscApiClient _api;
private readonly Func<string> _businessBaseAddress;
public EstimateApiClient(IYavscApiClient api, string businessBaseAddress)
: this(api, () => businessBaseAddress)
{
}
public EstimateApiClient(IYavscApiClient api, Func<string> businessBaseAddress)
{
_api = api ?? throw new ArgumentNullException(nameof(api));
_businessBaseAddress = businessBaseAddress ?? throw new ArgumentNullException(nameof(businessBaseAddress));
// Validate initial value early to fail fast on invalid setup.
_ = ResolveBusinessBaseAddress();
}
/// <summary>
/// Lists the estimates of the given owner; when <paramref name="ownerId"/>
/// is null, the server falls back to the current user.
/// </summary>
public Task<List<EstimateDto>> GetEstimatesAsync(string? ownerId = null, CancellationToken ct = default)
{
var path = string.IsNullOrWhiteSpace(ownerId)
? PathPrefix
: $"{PathPrefix}?ownerId={Uri.EscapeDataString(ownerId)}";
return _api.CallAsync<List<EstimateDto>>(HttpMethod.Get, Absolute(path), ct: ct);
}
public Task<EstimateDto> GetEstimateAsync(long id, CancellationToken ct = default)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id));
return _api.CallAsync<EstimateDto>(HttpMethod.Get, Absolute($"{PathPrefix}/{id}"), ct: ct);
}
/// <summary>
/// Creates an estimate. When <see cref="EstimateDto.CommandId"/> is set,
/// the server also stamps the linked command as validated.
/// </summary>
public async Task<EstimateCreatedDto> CreateAsync(EstimateDto estimate, CancellationToken ct = default)
{
if (estimate is null)
throw new ArgumentNullException(nameof(estimate));
var created = await _api.CallAsync<EstimateCreatedDto>(
HttpMethod.Post,
Absolute(PathPrefix),
body: estimate,
ct: ct).ConfigureAwait(false);
return created ?? new EstimateCreatedDto();
}
public Task UpdateAsync(long id, EstimateDto estimate, CancellationToken ct = default)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id));
if (estimate is null)
throw new ArgumentNullException(nameof(estimate));
estimate.Id = id;
return _api.CallAsync(
HttpMethod.Put,
Absolute($"{PathPrefix}/{id}"),
body: estimate,
ct: ct);
}
public Task DeleteAsync(long id, CancellationToken ct = default)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id));
return _api.CallAsync(HttpMethod.Delete, Absolute($"{PathPrefix}/{id}"), ct: ct);
}
private string Absolute(string relativePath) => new Uri(ResolveBusinessBaseAddress(), relativePath).ToString();
private Uri ResolveBusinessBaseAddress()
{
var raw = _businessBaseAddress();
if (string.IsNullOrWhiteSpace(raw))
throw new InvalidOperationException("Business base address is required.");
return new Uri(raw, UriKind.Absolute);
}
}

View file

@ -53,24 +53,10 @@ public interface IYavscApiClient : IAsyncDisposable
object? body = null, object? body = null,
CancellationToken ct = default); CancellationToken ct = default);
/// <summary>Call a multipart endpoint with a typed return value.</summary>
Task<T> CallAsync<T>(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default);
/// <summary>Call a JSON endpoint that returns no useful body (DELETE, 204, etc.).</summary> /// <summary>Call a JSON endpoint that returns no useful body (DELETE, 204, etc.).</summary>
Task CallAsync( Task CallAsync(
HttpMethod method, HttpMethod method,
string path, string path,
object? body = null, object? body = null,
CancellationToken ct = default); CancellationToken ct = default);
/// <summary>Call a multipart endpoint that returns no useful body.</summary>
Task CallAsync(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default);
} }

View file

@ -1,236 +0,0 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Api.Test.Fixtures;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Billing;
using Yavsc.Models.Haircut;
using Yavsc.Models.Workflow;
using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Collection("Yavsc Api")]
public sealed class BillingControllerTests : IClassFixture<ApiWebServerFixture>
{
private readonly ApiWebServerFixture _fixture;
public BillingControllerTests(ApiWebServerFixture fixture)
{
_fixture = fixture;
}
private HttpClient NewClient(string subject = "alice", string scope = "api")
{
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
var http = new HttpClient(handler)
{
BaseAddress = new Uri(_fixture.BaseAddress)
};
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", TestTokenIssuer.Issue(subject, scope));
return http;
}
[Fact]
public async Task GetProviderOngoingCommands_returns_current_provider_requests()
{
WorkflowHelpers.ConfigureBillingService();
_fixture.ResetAndSeedActivityGraph();
using (var scope = _fixture.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var location = db.Locations.Single();
db.RdvQueries.Add(new RdvQuery
{
ActivityCode = "dev",
ClientId = "bob",
PerformerId = "alice",
Consent = true,
UserCreated = "alice",
UserModified = "alice",
DateCreated = DateTime.UtcNow.AddMinutes(-10),
DateModified = DateTime.UtcNow.AddMinutes(-8),
EventDate = DateTime.UtcNow.AddDays(1),
Location = location,
Reason = "Rendez-vous fournisseur",
Status = QueryStatus.InProgress,
Description = "Commande fournisseur en cours",
});
db.RdvQueries.Add(new RdvQuery
{
ActivityCode = "dev",
ClientId = "alice",
PerformerId = "bob",
Consent = true,
UserCreated = "bob",
UserModified = "bob",
DateCreated = DateTime.UtcNow.AddMinutes(-20),
DateModified = DateTime.UtcNow.AddMinutes(-20),
EventDate = DateTime.UtcNow.AddDays(2),
Location = location,
Reason = "Commande d'un autre prestataire",
Status = QueryStatus.Accepted,
Description = "Autre prestataire",
});
db.SaveChanges();
}
using var http = NewClient();
var response = await http.GetAsync("/api/v1/bill/provider/ongoing", TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(response.StatusCode == HttpStatusCode.OK, $"Unexpected status {(int)response.StatusCode} ({response.StatusCode}): {body}");
var payload = await response.Content.ReadFromJsonAsync<List<ProviderOngoingCommandDto>>(TestContext.Current.CancellationToken);
Assert.NotNull(payload);
Assert.NotEmpty(payload!);
Assert.All(payload!, item => Assert.Equal("alice", item.PerformerId));
Assert.Contains(payload!, item => item.BillingCode == BillingCodes.Rdv);
}
[Fact]
public async Task GetProviderOngoingCommands_ignores_rows_with_invalid_discriminator()
{
WorkflowHelpers.ConfigureBillingService();
_fixture.ResetAndSeedActivityGraph();
using (var scope = _fixture.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Database.ExecuteSqlInterpolated($@"
INSERT INTO ""NominativeServiceCommands""
(""ActivityCode"", ""ClientId"", ""Consent"", ""DateCreated"", ""DateModified"", ""Description"", ""Discriminator"", ""PerformerId"", ""Status"", ""UserCreated"", ""UserModified"")
VALUES
({"dev"}, {"bob"}, {true}, {DateTime.UtcNow.AddMinutes(-5)}, {DateTime.UtcNow.AddMinutes(-4)}, {"Legacy malformed row"}, {""}, {"alice"}, {(int)QueryStatus.Accepted}, {"alice"}, {"alice"});
");
var location = db.Locations.Single();
db.RdvQueries.Add(new RdvQuery
{
ActivityCode = "dev",
ClientId = "bob",
PerformerId = "alice",
Consent = true,
UserCreated = "alice",
UserModified = "alice",
DateCreated = DateTime.UtcNow.AddMinutes(-3),
DateModified = DateTime.UtcNow.AddMinutes(-2),
EventDate = DateTime.UtcNow.AddDays(1),
Location = location,
Reason = "Commande valide",
Status = QueryStatus.InProgress,
Description = "Commande fournisseur valide",
});
db.SaveChanges();
}
using var http = NewClient();
var response = await http.GetAsync("/api/v1/bill/provider/ongoing", TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(response.StatusCode == HttpStatusCode.OK, $"Unexpected status {(int)response.StatusCode} ({response.StatusCode}): {body}");
var payload = await response.Content.ReadFromJsonAsync<List<ProviderOngoingCommandDto>>(TestContext.Current.CancellationToken);
Assert.NotNull(payload);
Assert.NotEmpty(payload!);
Assert.Contains(payload!, item => item.BillingCode == BillingCodes.Rdv && item.PerformerId == "alice");
Assert.DoesNotContain(payload!, item => string.IsNullOrWhiteSpace(item.BillingCode));
}
[Fact]
public async Task GetProviderOngoingCommands_returns_haircut_and_grouped_haircut_requests()
{
WorkflowHelpers.ConfigureBillingService();
_fixture.ResetAndSeedHaircutGraph();
using (var scope = _fixture.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.UserActivities.Add(new UserActivity
{
UserId = "alice",
DoesCode = "brush",
Weight = 50,
});
db.UserActivities.Add(new UserActivity
{
UserId = "alice",
DoesCode = "mbrush",
Weight = 50,
});
db.CommandForm.Add(new CommandForm
{
ActivityCode = "brush",
ActionName = BillingCodes.Brush,
Title = "Brush",
});
db.CommandForm.Add(new CommandForm
{
ActivityCode = "mbrush",
ActionName = BillingCodes.MBrush,
Title = "MBrush",
});
db.SaveChanges();
}
using var http = NewClient();
var response = await http.GetAsync("/api/v1/bill/provider/ongoing", TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(response.StatusCode == HttpStatusCode.OK, $"Unexpected status {(int)response.StatusCode} ({response.StatusCode}): {body}");
var payload = await response.Content.ReadFromJsonAsync<List<ProviderOngoingCommandDto>>(TestContext.Current.CancellationToken);
Assert.NotNull(payload);
Assert.Contains(payload!, item => item.BillingCode == BillingCodes.Brush && item.PerformerId == "alice");
Assert.Contains(payload!, item => item.BillingCode == BillingCodes.MBrush && item.PerformerId == "alice");
}
[Fact]
public async Task GetProviderOngoingCommands_excludes_requests_outside_performer_declared_activities()
{
WorkflowHelpers.ConfigureBillingService();
_fixture.ResetAndSeedHaircutGraph();
using var http = NewClient();
var response = await http.GetAsync("/api/v1/bill/provider/ongoing", TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(response.StatusCode == HttpStatusCode.OK, $"Unexpected status {(int)response.StatusCode} ({response.StatusCode}): {body}");
var payload = await response.Content.ReadFromJsonAsync<List<ProviderOngoingCommandDto>>(TestContext.Current.CancellationToken);
Assert.NotNull(payload);
Assert.DoesNotContain(payload!, item => item.BillingCode == BillingCodes.Brush);
Assert.DoesNotContain(payload!, item => item.BillingCode == BillingCodes.MBrush);
}
private sealed class ProviderOngoingCommandDto
{
public long Id { get; set; }
public string BillingCode { get; set; } = string.Empty;
public string ActivityCode { get; set; } = string.Empty;
public string PerformerId { get; set; } = string.Empty;
public string ClientId { get; set; } = string.Empty;
public QueryStatus Status { get; set; }
public string Description { get; set; } = string.Empty;
}
}

View file

@ -1,209 +0,0 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Api.Test.Fixtures;
using Yavsc.Models;
using Yavsc.Models.Billing;
using Yavsc.Models.Workflow;
using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Collection("Yavsc Api")]
public sealed class EstimateApiControllerTests : IClassFixture<ApiWebServerFixture>
{
private readonly ApiWebServerFixture _fixture;
public EstimateApiControllerTests(ApiWebServerFixture fixture)
{
_fixture = fixture;
}
private HttpClient NewClient(string subject = "alice", string scope = "api")
{
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
var http = new HttpClient(handler)
{
BaseAddress = new Uri(_fixture.BaseAddress)
};
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", TestTokenIssuer.Issue(subject, scope));
return http;
}
/// <summary>
/// Seed a provider (alice) and a client (bob) with a pending
/// <see cref="RdvQuery"/> from bob to alice, and return the
/// command id.
/// </summary>
private long SeedPendingCommand()
{
_fixture.ResetAndSeedActivityGraph();
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var location = db.Locations.Single();
var query = new RdvQuery
{
ActivityCode = "dev",
ClientId = "bob",
PerformerId = "alice",
Consent = true,
UserCreated = "bob",
UserModified = "bob",
DateCreated = DateTime.UtcNow.AddMinutes(-10),
DateModified = DateTime.UtcNow.AddMinutes(-10),
EventDate = DateTime.UtcNow.AddDays(1),
Location = location,
Reason = "Demande de devis",
Status = QueryStatus.InProgress,
Description = "Demande en attente de devis",
};
db.RdvQueries.Add(query);
db.SaveChanges();
return query.Id;
}
private static object NewEstimatePayload(long? commandId, string clientId, string? ownerId = null)
=> new
{
CommandId = commandId,
ClientId = clientId,
OwnerId = ownerId,
CommandType = BillingCodes.Rdv,
Title = "Devis prestation",
Description = "Devis détaillé",
AttachedFiles = Array.Empty<string>(),
AttachedGraphics = Array.Empty<string>(),
Bill = new[]
{
new { Name = "Prestation", Description = "Prestation de base", Count = 1, UnitaryCost = 120m, Currency = "EUR" },
new { Name = "Remise", Description = "Remise fidélité", Count = 1, UnitaryCost = -20m, Currency = "EUR" },
},
};
[Fact]
public async Task PostEstimate_creates_the_estimate_and_validates_the_linked_command()
{
var commandId = SeedPendingCommand();
using var http = NewClient("alice");
var response = await http.PostAsJsonAsync(
"/api/v1/estimate",
NewEstimatePayload(commandId, clientId: "bob"),
TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(response.StatusCode == HttpStatusCode.OK, $"Unexpected status {(int)response.StatusCode} ({response.StatusCode}): {body}");
using var doc = JsonDocument.Parse(body);
var estimateId = doc.RootElement.GetProperty("id").GetInt64();
Assert.True(estimateId > 0);
Assert.Equal(2, doc.RootElement.GetProperty("bill").GetArrayLength());
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var estimate = db.Estimates.Include(e => e.Bill).Single(e => e.Id == estimateId);
Assert.Equal("alice", estimate.OwnerId);
Assert.Equal("bob", estimate.ClientId);
Assert.Equal(commandId, estimate.CommandId);
Assert.Equal(BillingCodes.Rdv, estimate.CommandType);
Assert.Equal(2, estimate.Bill.Count);
Assert.Contains(estimate.Bill, line => line.UnitaryCost == -20m);
// PostEstimate stamps the linked command as validated.
var query = db.RdvQueries.Single(q => q.Id == commandId);
Assert.NotNull(query.ValidationDate);
}
[Fact]
public async Task PostEstimate_without_command_creates_a_standalone_estimate()
{
_fixture.ResetAndSeedActivityGraph();
using var http = NewClient("alice");
var response = await http.PostAsJsonAsync(
"/api/v1/estimate",
NewEstimatePayload(commandId: null, clientId: "bob"),
TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(response.StatusCode == HttpStatusCode.OK, $"Unexpected status {(int)response.StatusCode} ({response.StatusCode}): {body}");
using var doc = JsonDocument.Parse(body);
var estimateId = doc.RootElement.GetProperty("id").GetInt64();
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var estimate = db.Estimates.Single(e => e.Id == estimateId);
Assert.Null(estimate.CommandId);
Assert.Equal("alice", estimate.OwnerId);
}
[Fact]
public async Task PostEstimate_for_another_owner_is_rejected()
{
_fixture.ResetAndSeedActivityGraph();
using var http = NewClient("alice");
var response = await http.PostAsJsonAsync(
"/api/v1/estimate",
NewEstimatePayload(commandId: null, clientId: "bob", ownerId: "bob"),
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
Assert.Empty(db.Estimates);
}
[Fact]
public async Task PostEstimate_with_an_unknown_command_id_is_rejected()
{
_fixture.ResetAndSeedActivityGraph();
using var http = NewClient("alice");
var response = await http.PostAsJsonAsync(
"/api/v1/estimate",
NewEstimatePayload(commandId: 999999, clientId: "bob"),
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
Assert.Empty(db.Estimates);
}
[Fact]
public async Task PostEstimate_without_token_is_unauthorized()
{
_fixture.ResetAndSeedActivityGraph();
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
using var http = new HttpClient(handler) { BaseAddress = new Uri(_fixture.BaseAddress) };
var response = await http.PostAsJsonAsync(
"/api/v1/estimate",
NewEstimatePayload(commandId: null, clientId: "bob"),
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}

View file

@ -1,48 +1,26 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Npgsql;
using Yavsc.Controllers; using Yavsc.Controllers;
using Yavsc.Interfaces.Workflow;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Billing;
using Yavsc.Models.Google.Messaging;
using Yavsc.Models.Haircut; using Yavsc.Models.Haircut;
using Yavsc.Models.Messaging;
using Yavsc.Models.Relationship; using Yavsc.Models.Relationship;
using Yavsc.Models.Workflow; using Yavsc.Models.Workflow;
using Yavsc.Services;
using Yavsc.Tests.Shared; using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test.Fixtures; namespace Yavsc.Api.Test.Fixtures;
public sealed class ApiWebServerFixture : WebHostFixture public sealed class ApiWebServerFixture : WebHostFixture
{ {
private const string DbProviderEnvVar = "YAVSC_API_TEST_DB_PROVIDER";
private const string NpgsqlAdminConnectionEnvVar = "YAVSC_API_TEST_NPGSQL_ADMIN_CONNECTION";
private const string DedicatedNpgsqlDatabaseName = "yavscTestDb";
private const string DefaultDevelopmentConnectionString = "Server=localhost;Port=5432;Database=yavscdev;Username=yavscdev;Password=8*5idas;Include Error Detail=true";
protected override int HttpsPort => 5104; protected override int HttpsPort => 5104;
private static SqliteConnection? _sharedSqliteConnection; private static SqliteConnection? _sharedSqliteConnection;
private static readonly object _sqliteLock = new(); private static readonly object _sqliteLock = new();
private static readonly object _npgsqlLock = new();
private static string? _sharedNpgsqlConnectionString;
protected override WebApplication BuildApp(WebApplicationBuilder builder) protected override WebApplication BuildApp(WebApplicationBuilder builder)
{
if (UseNpgsqlProvider())
{
var npgsqlConnectionString = EnsureNpgsqlDatabaseCreated();
builder.Services.AddDbContext<ApplicationDbContext>(opt =>
opt.UseNpgsql(npgsqlConnectionString,
x => x.MigrationsAssembly("Yavsc.Org")));
}
else
{ {
SqliteConnection sharedConnection; SqliteConnection sharedConnection;
lock (_sqliteLock) lock (_sqliteLock)
@ -58,15 +36,10 @@ public sealed class ApiWebServerFixture : WebHostFixture
builder.Services.AddDbContext<ApplicationDbContext>(opt => builder.Services.AddDbContext<ApplicationDbContext>(opt =>
opt.UseSqlite(sharedConnection)); opt.UseSqlite(sharedConnection));
}
builder.Services.AddControllers() builder.Services.AddControllers()
.AddApplicationPart(typeof(ActivityApiController).Assembly); .AddApplicationPart(typeof(ActivityApiController).Assembly);
builder.Services.AddLocalization();
builder.Services.Configure<GoogleAuthSettings>(_ => { });
builder.Services.AddTransient<IBillingService, BillingService>();
builder.Services.AddTransient<IYavscMessageSender, NoopMessageSender>();
builder.Services.AddAuthorization(); builder.Services.AddAuthorization();
builder.Services.AddAuthentication("Bearer") builder.Services.AddAuthentication("Bearer")
@ -101,19 +74,8 @@ public sealed class ApiWebServerFixture : WebHostFixture
using (var scope = app.Services.CreateScope()) using (var scope = app.Services.CreateScope())
{ {
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (UseNpgsqlProvider())
{
// Apply the EF Core migrations (Yavsc.Org assembly) so the
// test database schema matches the production provider.
// EnsureCreated must not be used here: it would create the
// schema without the migrations history and break Migrate().
db.Database.Migrate();
}
else
{
db.Database.EnsureCreated(); db.Database.EnsureCreated();
} }
}
await Task.CompletedTask; await Task.CompletedTask;
return app; return app;
@ -121,97 +83,12 @@ public sealed class ApiWebServerFixture : WebHostFixture
public string BaseAddress => Addresses.First(a => a.StartsWith("https://", StringComparison.Ordinal)); public string BaseAddress => Addresses.First(a => a.StartsWith("https://", StringComparison.Ordinal));
public static bool UseNpgsqlProvider()
=> string.Equals(
Environment.GetEnvironmentVariable(DbProviderEnvVar),
"npgsql",
StringComparison.OrdinalIgnoreCase);
private static string EnsureNpgsqlDatabaseCreated()
{
lock (_npgsqlLock)
{
if (!string.IsNullOrWhiteSpace(_sharedNpgsqlConnectionString))
{
return _sharedNpgsqlConnectionString;
}
var adminConnectionString = BuildAdminConnectionString();
var databaseName = DedicatedNpgsqlDatabaseName;
using (var adminConnection = new NpgsqlConnection(adminConnectionString))
{
adminConnection.Open();
using var existsCommand = adminConnection.CreateCommand();
existsCommand.CommandText = "SELECT 1 FROM pg_database WHERE datname = @databaseName";
existsCommand.Parameters.AddWithValue("databaseName", databaseName);
if (existsCommand.ExecuteScalar() is null)
{
using var createCommand = adminConnection.CreateCommand();
createCommand.CommandText = $"CREATE DATABASE \"{databaseName}\"";
createCommand.ExecuteNonQuery();
}
}
var testConnectionBuilder = new NpgsqlConnectionStringBuilder(adminConnectionString)
{
Database = databaseName,
Pooling = false,
IncludeErrorDetail = true
};
_sharedNpgsqlConnectionString = testConnectionBuilder.ToString();
return _sharedNpgsqlConnectionString;
}
}
private static string BuildAdminConnectionString()
{
var configured = Environment.GetEnvironmentVariable(NpgsqlAdminConnectionEnvVar);
var source = string.IsNullOrWhiteSpace(configured)
? DefaultDevelopmentConnectionString
: configured;
var builder = new NpgsqlConnectionStringBuilder(source)
{
Pooling = false,
IncludeErrorDetail = true
};
if (string.IsNullOrWhiteSpace(configured))
{
builder.Database = "postgres";
}
else if (string.IsNullOrWhiteSpace(builder.Database))
{
builder.Database = "postgres";
}
return builder.ToString();
}
private sealed class NoopMessageSender : IYavscMessageSender
{
public Task<MessageWithPayloadResponse> NotifyBookQueryAsync(IEnumerable<string> connectionIds, RdvQueryEvent ev)
=> Task.FromResult(new MessageWithPayloadResponse());
public Task<MessageWithPayloadResponse> NotifyEstimateAsync(IEnumerable<string> connectionIds, EstimationEvent ev)
=> Task.FromResult(new MessageWithPayloadResponse());
public Task<MessageWithPayloadResponse> NotifyHairCutQueryAsync(IEnumerable<string> connectionIds, HairCutQueryEvent ev)
=> Task.FromResult(new MessageWithPayloadResponse());
public Task<MessageWithPayloadResponse> NotifyAsync(IEnumerable<string> connectionIds, IEvent yaev)
=> Task.FromResult(new MessageWithPayloadResponse());
}
public void ResetAndSeedActivityGraph() public void ResetAndSeedActivityGraph()
{ {
using var scope = Services.CreateScope(); using var scope = Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
ResetDatabase(db); db.Database.EnsureDeleted();
db.Database.EnsureCreated(); db.Database.EnsureCreated();
var user = new ApplicationUser var user = new ApplicationUser
@ -312,34 +189,6 @@ public sealed class ApiWebServerFixture : WebHostFixture
db.SaveChanges(); db.SaveChanges();
} }
private static void ResetDatabase(ApplicationDbContext db)
{
if (UseNpgsqlProvider())
{
// Purge only the tables of the test graph, children before
// parents, so no DELETE violates a foreign key. Estimate and
// CommandLine reference NominativeServiceCommand (CommandId) and
// must be deleted before the Rdv/HairCut/HairMultiCut queries.
db.Set<CommandLine>().RemoveRange(db.Set<CommandLine>());
db.Set<Estimate>().RemoveRange(db.Set<Estimate>());
db.Set<RdvQuery>().RemoveRange(db.Set<RdvQuery>());
db.Set<HairCutQuery>().RemoveRange(db.Set<HairCutQuery>());
db.Set<HairMultiCutQuery>().RemoveRange(db.Set<HairMultiCutQuery>());
db.Set<HairPrestationCollectionItem>().RemoveRange(db.Set<HairPrestationCollectionItem>());
db.Set<HairPrestation>().RemoveRange(db.Set<HairPrestation>());
db.Set<UserActivity>().RemoveRange(db.Set<UserActivity>());
db.Set<PerformerProfile>().RemoveRange(db.Set<PerformerProfile>());
db.Set<Activity>().RemoveRange(db.Set<Activity>());
db.Set<ApplicationUser>().RemoveRange(db.Set<ApplicationUser>());
db.Set<Location>().RemoveRange(db.Set<Location>());
db.SaveChanges();
return;
}
db.Database.EnsureDeleted();
}
public void ResetAndSeedRdvQueryGraph() public void ResetAndSeedRdvQueryGraph()
{ {
ResetAndSeedActivityGraph(); ResetAndSeedActivityGraph();
@ -486,9 +335,21 @@ public sealed class ApiWebServerFixture : WebHostFixture
public override void Dispose() public override void Dispose()
{ {
// Keep the shared in-memory SQLite connection alive for the try
// whole test process. Closing it from one fixture instance can {
// drop the schema while other tests are still running.
base.Dispose(); base.Dispose();
} }
finally
{
lock (_sqliteLock)
{
if (_sharedSqliteConnection is not null)
{
_sharedSqliteConnection.Close();
_sharedSqliteConnection.Dispose();
_sharedSqliteConnection = null;
}
}
}
}
} }

View file

@ -143,87 +143,4 @@ public sealed class RdvQueryApiControllerTests : IClassFixture<ApiWebServerFixtu
Assert.NotNull(created); Assert.NotNull(created);
Assert.Equal(DateTimeKind.Utc, created!.EventDate.Kind); Assert.Equal(DateTimeKind.Utc, created!.EventDate.Kind);
} }
[Fact]
public async Task PostQuery_with_unknown_location_id_creates_location_and_succeeds()
{
_fixture.ResetAndSeedRdvQueryGraph();
using var http = NewClient(subject: "alice");
var createPayload = new
{
ActivityCode = "dev",
PerformerId = "alice",
Consent = true,
EventDate = DateTime.UtcNow.AddDays(3),
Location = new
{
Id = 999999L,
Address = "4 rue du Test",
Latitude = 48.8569,
Longitude = 2.3525,
},
Reason = "Rendez-vous id location inconnu",
Status = QueryStatus.Inserted,
};
var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Rdv", createPayload, TestContext.Current.CancellationToken);
var body = await createResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(createResponse.StatusCode == HttpStatusCode.Created, $"Unexpected status {(int)createResponse.StatusCode} ({createResponse.StatusCode}): {body}");
var created = await createResponse.Content.ReadFromJsonAsync<RdvQuery>(TestContext.Current.CancellationToken);
Assert.NotNull(created);
Assert.NotNull(created!.Location);
Assert.True(created.Location.Id > 0);
Assert.NotEqual(999999L, created.Location.Id);
Assert.Equal("alice", created.ClientId);
}
[Fact]
public async Task PostQuery_without_location_returns_bad_request()
{
_fixture.ResetAndSeedRdvQueryGraph();
using var http = NewClient(subject: "alice");
var createPayload = new
{
ActivityCode = "dev",
PerformerId = "alice",
Consent = true,
EventDate = DateTime.UtcNow.AddDays(1),
Reason = "Rendez-vous sans location",
Status = QueryStatus.Inserted,
};
var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Rdv", createPayload, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, createResponse.StatusCode);
}
[Fact]
public async Task PostQuery_with_unknown_location_id_and_missing_address_returns_bad_request()
{
_fixture.ResetAndSeedRdvQueryGraph();
using var http = NewClient(subject: "alice");
var createPayload = new
{
ActivityCode = "dev",
PerformerId = "alice",
Consent = true,
EventDate = DateTime.UtcNow.AddDays(1),
Location = new
{
Id = 777777L,
Address = "",
Latitude = 0.0,
Longitude = 0.0,
},
Reason = "Rendez-vous location invalide",
Status = QueryStatus.Inserted,
};
var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Rdv", createPayload, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, createResponse.StatusCode);
}
} }

View file

@ -3,12 +3,9 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Security.Claims; using System.Security.Claims;
using Yavsc.Billing;
using Yavsc.Helpers; using Yavsc.Helpers;
using Yavsc.ViewModels; using Yavsc.ViewModels;
using Yavsc.Models.Billing; using Yavsc.Models.Billing;
using Yavsc.Models.Haircut;
using Yavsc.Models.Workflow;
using Yavsc.Server.Models.FileSystem; using Yavsc.Server.Models.FileSystem;
namespace Yavsc.ApiControllers namespace Yavsc.ApiControllers
@ -103,114 +100,6 @@ namespace Yavsc.ApiControllers
return ViewComponent("Bill",new object[] { billingCode, bill, OutputFormat.Pdf, true } ); return ViewComponent("Bill",new object[] { billingCode, bill, OutputFormat.Pdf, true } );
} }
/// <summary>
/// Lists ongoing service commands for the authenticated performer.
/// This endpoint is tailored for the PostIt provider homepage flow
/// ("Mes demandes en cours").
/// </summary>
[HttpGet("provider/ongoing")]
[Produces("application/json")]
public IActionResult GetProviderOngoingCommands()
{
var uid = User.GetUserId();
if (string.IsNullOrWhiteSpace(uid))
{
return Unauthorized();
}
if (billingService.BillingMap.Count == 0)
{
WorkflowHelpers.ConfigureBillingService();
}
var allowedActivityCodes = dbContext.UserActivities
.AsNoTracking()
.Where(a => a.UserId == uid)
.Select(a => a.DoesCode)
.Distinct()
.ToList();
if (allowedActivityCodes.Count == 0)
{
return Ok(Array.Empty<object>());
}
var allowedBillingCodes = dbContext.CommandForm
.AsNoTracking()
.Where(form => allowedActivityCodes.Contains(form.ActivityCode))
.Select(form => form.ActionName)
.Where(actionName => !string.IsNullOrWhiteSpace(actionName))
.Distinct()
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var fallbackToActivityFilteringOnly = allowedBillingCodes.Count == 0;
// Query only the command types allowed by the performer's declared
// activities; this avoids touching unrelated legacy slices.
var rdvCommands = fallbackToActivityFilteringOnly || allowedBillingCodes.Contains(BillingCodes.Rdv)
? dbContext.Set<RdvQuery>()
.AsNoTracking()
.Where(q => q.PerformerId == uid)
.Where(q => allowedActivityCodes.Contains(q.ActivityCode))
.Where(q => q.Status == QueryStatus.Inserted
|| q.Status == QueryStatus.Accepted
|| q.Status == QueryStatus.InProgress)
.Cast<NominativeServiceCommand>()
.ToList()
: new List<NominativeServiceCommand>();
var hairCommands = fallbackToActivityFilteringOnly || allowedBillingCodes.Contains(BillingCodes.Brush)
? dbContext.Set<HairCutQuery>()
.AsNoTracking()
.Where(q => q.PerformerId == uid)
.Where(q => allowedActivityCodes.Contains(q.ActivityCode))
.Where(q => q.Status == QueryStatus.Inserted
|| q.Status == QueryStatus.Accepted
|| q.Status == QueryStatus.InProgress)
.Cast<NominativeServiceCommand>()
.ToList()
: new List<NominativeServiceCommand>();
var hairMultiCommands = fallbackToActivityFilteringOnly || allowedBillingCodes.Contains(BillingCodes.MBrush)
? dbContext.Set<HairMultiCutQuery>()
.AsNoTracking()
.Where(q => q.PerformerId == uid)
.Where(q => allowedActivityCodes.Contains(q.ActivityCode))
.Where(q => q.Status == QueryStatus.Inserted
|| q.Status == QueryStatus.Accepted
|| q.Status == QueryStatus.InProgress)
.Cast<NominativeServiceCommand>()
.ToList()
: new List<NominativeServiceCommand>();
var commands = rdvCommands
.Concat(hairCommands)
.Concat(hairMultiCommands)
.OrderByDescending(q => q.DateModified)
.ThenByDescending(q => q.Id)
.ToList();
var payload = commands
.Select(q => new
{
Id = q.Id,
BillingCode = ResolveBillingCode(q),
ActivityCode = q.ActivityCode,
PerformerId = q.PerformerId,
ClientId = q.ClientId,
Status = q.Status,
Description = q.Description,
EventDate = ResolveEventDate(q),
Reason = q is Models.Workflow.RdvQuery rdv ? rdv.Reason : string.Empty,
AdditionalInfo = q is Models.Haircut.HairCutQuery hc ? hc.AdditionalInfo : string.Empty,
Provisional = q.Provisional,
})
.Where(x => !string.IsNullOrWhiteSpace(x.BillingCode))
.ToList();
return Ok(payload);
}
[HttpPost("prosign/{billingCode}/{id}")] [HttpPost("prosign/{billingCode}/{id}")]
public async Task<IActionResult> ProSign(string billingCode, long id) public async Task<IActionResult> ProSign(string billingCode, long id)
@ -244,23 +133,6 @@ namespace Yavsc.ApiControllers
return Ok (new { ProviderValidationDate = estimate.ProviderValidationDate, GCMSent = gcmSent }); return Ok (new { ProviderValidationDate = estimate.ProviderValidationDate, GCMSent = gcmSent });
} }
private string ResolveBillingCode(NominativeServiceCommand command)
{
var typeName = command.GetType().Name;
return billingService.BillingMap.TryGetValue(typeName, out var code)
? code
: string.Empty;
}
private static DateTime? ResolveEventDate(NominativeServiceCommand command)
=> command switch
{
Models.Workflow.RdvQuery rdv => rdv.EventDate,
Models.Haircut.HairCutQuery brush => brush.EventDate,
Models.Haircut.HairMultiCutQuery mbrush => mbrush.EventDate,
_ => null,
};
[HttpGet("prosign/{billingCode}/{id}")] [HttpGet("prosign/{billingCode}/{id}")]
public async Task<IActionResult> GetProSign(string billingCode, long id) public async Task<IActionResult> GetProSign(string billingCode, long id)
{ {
@ -282,28 +154,9 @@ namespace Yavsc.ApiControllers
public async Task<IActionResult> CliSign(string billingCode, long id) public async Task<IActionResult> CliSign(string billingCode, long id)
{ {
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var estimate = dbContext.Estimates var estimate = dbContext.Estimates.Include( e=>e.Query
.Include(e => e.Owner) ).Include(e=>e.Owner).Include(e=>e.Owner.Performer).Include(e=>e.Client)
.Include(e => e.Owner.Performer) .FirstOrDefault( e=> e.Id == id && e.Query.ClientId == uid );
.Include(e => e.Client)
.FirstOrDefault(e => e.Id == id);
if (estimate is null)
{
return NotFound();
}
if (estimate.CommandId is null)
{
return new ChallengeResult();
}
var command = dbContext.Set<NominativeServiceCommand>()
.FirstOrDefault(c => c.Id == estimate.CommandId.Value);
if (command is null || command.ClientId != uid)
{
return new ChallengeResult();
}
if (!(await authorizationService.AuthorizeAsync(User, estimate, new ReadPermission())).Succeeded) if (!(await authorizationService.AuthorizeAsync(User, estimate, new ReadPermission())).Succeeded)
{ {
return new ChallengeResult(); return new ChallengeResult();

Some files were not shown because too many files have changed in this diff Show more