From 3a1ce55c0fc02ce209f6bdbfe6bf348b1c756757 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 30 Aug 2026 17:03:59 +0100 Subject: [PATCH 01/31] code reorg --- .../{ => ViewModels}/Settings/AuthenticationSettings.cs | 6 +++--- src/PostIt/PostIt/ViewModels/{ => Settings}/Settings.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) rename src/PostIt/PostIt/{ => ViewModels}/Settings/AuthenticationSettings.cs (95%) rename src/PostIt/PostIt/ViewModels/{ => Settings}/Settings.cs (99%) diff --git a/src/PostIt/PostIt/Settings/AuthenticationSettings.cs b/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs similarity index 95% rename from src/PostIt/PostIt/Settings/AuthenticationSettings.cs rename to src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs index 9ebeaebd..8034820d 100644 --- a/src/PostIt/PostIt/Settings/AuthenticationSettings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs @@ -18,11 +18,11 @@ public partial class AuthenticationSettings : ObservableObject /// public const string AndroidRedirectUri = "android://postit-signin"; - public static string DefaultAuthority { get; internal set; } = "https://yavsc.pschneider.fr"; + public const string DefaultAuthority = "https://yavsc.pschneider.fr"; - public static string DefaultClientId { get; internal set; } = "postit"; + public const string DefaultClientId = "postit"; - public static string[] DefaultScopes { get; set; } = { "blogs"} ; + public static readonly string[] DefaultScopes = { "blogs" }; [ObservableProperty] public partial string Authority { get; set; } diff --git a/src/PostIt/PostIt/ViewModels/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs similarity index 99% rename from src/PostIt/PostIt/ViewModels/Settings.cs rename to src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 8586fa34..f942249b 100644 --- a/src/PostIt/PostIt/ViewModels/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -314,7 +314,7 @@ public partial class Settings : ViewModelBase settings.Authentication.Scopes = AuthenticationSettings.DefaultScopes; } else - this.Authentication.Scopes = settings.Authentication.Scopes; + this.Authentication.Scopes = settings.Authentication.Scopes; } } // A disk load (or an embedded-resource fallback) is the From 0241dd98f0830acbee8f5df7a19188bc58cc86fb Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 30 Aug 2026 19:37:55 +0100 Subject: [PATCH 02/31] load the ACL --- src/PostIt/Directory.Packages.props | 6 - .../PostIt.Tests/BlogPostAuthorDtoTests.cs | 47 ++++ src/PostIt/PostIt.Tests/PostAclDialogTests.cs | 59 ++++- src/PostIt/PostIt/ViewModels/MainViewModel.cs | 18 +- .../ViewModels/PostAclDialogViewModel.cs | 53 +++- src/Yavsc.Abstract/Blogspot/BlogPostDto.cs | 20 +- .../Blogspot/PostAccessControlRulePayload.cs | 3 +- .../Identity/Security/CircleAuthorization.cs | 2 +- .../Identity/Security/ICircleAuthorization.cs | 8 - .../Identity/Security/ICircleAuthorized.cs | 2 +- src/Yavsc.Blogs.Tests/BlogAclApiTests.cs | 85 ++++++- src/Yavsc.Org/Services/BlogSpotService.cs | 57 ++++- src/Yavsc.Server/Models/Blog/BlogPost.cs | 15 +- src/Yavsc.Server/Services/BlogSpotService.cs | 237 ++++++++---------- 14 files changed, 438 insertions(+), 174 deletions(-) delete mode 100644 src/Yavsc.Abstract/Identity/Security/ICircleAuthorization.cs diff --git a/src/PostIt/Directory.Packages.props b/src/PostIt/Directory.Packages.props index 0d5fa50c..4dd4b288 100644 --- a/src/PostIt/Directory.Packages.props +++ b/src/PostIt/Directory.Packages.props @@ -8,8 +8,6 @@ 12.1.1 - - @@ -21,16 +19,12 @@ - - - - diff --git a/src/PostIt/PostIt.Tests/BlogPostAuthorDtoTests.cs b/src/PostIt/PostIt.Tests/BlogPostAuthorDtoTests.cs index 895f220e..daabdf59 100644 --- a/src/PostIt/PostIt.Tests/BlogPostAuthorDtoTests.cs +++ b/src/PostIt/PostIt.Tests/BlogPostAuthorDtoTests.cs @@ -166,4 +166,51 @@ public class BlogPostAuthorDtoTests Assert.True(root.TryGetProperty("userName", out _)); Assert.True(root.TryGetProperty("avatar", out _)); } + + [Fact] + public void BlogPostDto_deserialises_acl_from_detail_payload() + { + // Detail payload shape emitted by BlogApiController.GetBlog: + // ACL entries are included under "acl"/"ACL". + var json = """ + { + "id": 99, + "title": "ACL test", + "authorId": "u-alice", + "acl": [ + { "circleId": 12, "blogPostId": 99 }, + { "circleId": 34, "blogPostId": 99 } + ] + } + """; + + var post = JsonSerializer.Deserialize(json, CaseInsensitiveJson); + + Assert.NotNull(post); + var acl = post!.GetACL(); + Assert.Equal(2, acl.Length); + Assert.Contains(acl, a => a.CircleId == 12); + Assert.Contains(acl, a => a.CircleId == 34); + } + + [Fact] + public void BlogPostDto_does_not_emit_acl_when_serialized_for_write() + { + var post = new BlogPostDto + { + Id = 77, + Title = "Write payload" + }; + post.AuthorizeCircle(11); + + // The client should not send ACL through POST/PUT blog payloads. + // ACL mutations have their own dedicated /blogacl endpoint. + var json = JsonSerializer.Serialize(post, + new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); + + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + Assert.False(root.TryGetProperty("acl", out _)); + Assert.False(root.TryGetProperty("wireAcl", out _)); + } } diff --git a/src/PostIt/PostIt.Tests/PostAclDialogTests.cs b/src/PostIt/PostIt.Tests/PostAclDialogTests.cs index ccb33ec7..dd277629 100644 --- a/src/PostIt/PostIt.Tests/PostAclDialogTests.cs +++ b/src/PostIt/PostIt.Tests/PostAclDialogTests.cs @@ -9,6 +9,7 @@ using PostIt.Services; using PostIt.ViewModels; using PostIt.Views; using Yavsc.Api.Client; +using Yavsc.Api.Client.Dtos; using Yavsc.Blogspot; namespace PostIt.Tests; @@ -190,9 +191,8 @@ public class PostAclDialogTests await Task.Delay(20); } - // Assert: exactly two GETs went out (one to /blogacl, - // one to /circle), both from the LoadAsync call. - Assert.Equal(2, handler.RequestCount); + // Assert: one GET went out (for /circle) from LoadAsync. + Assert.Equal(1, handler.RequestCount); // And the VM's idempotency gate has flipped. Assert.True(vm.Loaded); @@ -218,7 +218,58 @@ public class PostAclDialogTests await vm.LoadAsync(); // Assert: the second call short-circuited on _loaded. - Assert.Equal(2, handler.RequestCount); + Assert.Equal(1, handler.RequestCount); Assert.True(vm.Loaded); } + + [Fact] + public async Task LoadAsync_keeps_acl_from_blogpostdto_and_only_loads_circles() + { + var post = new BlogPostDto { Id = 42, Title = "ACL hydration" }; + post.AuthorizeCircle(12); + post.AuthorizeCircle(34); + + var api = new StubAclApiClient(); + var aclClient = new BlogAclApiClient(api, "http://localhost/"); + var circleClient = new CircleApiClient(api, "http://localhost/"); + var vm = new PostAclDialogViewModel(post, aclClient, circleClient); + + await vm.LoadAsync(); + + Assert.Equal(1, api.CallCount); + Assert.Equal(2, vm.AclEntries.Count); + Assert.Contains(vm.AclEntries, a => a.CircleId == 12); + Assert.Contains(vm.AclEntries, a => a.CircleId == 34); + } + + private sealed class StubAclApiClient : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public int CallCount { get; private set; } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + CallCount++; + + if (typeof(T) == typeof(List)) + { + var circles = new List + { + new() { Id = 12, Name = "A", OwnerId = "owner", Public = false }, + new() { Id = 34, Name = "B", OwnerId = "owner", Public = false }, + }; + return Task.FromResult((T)(object)circles); + } + + return Task.FromResult(default(T)!); + } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + CallCount++; + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } } diff --git a/src/PostIt/PostIt/ViewModels/MainViewModel.cs b/src/PostIt/PostIt/ViewModels/MainViewModel.cs index 84e10cfb..f56b666d 100644 --- a/src/PostIt/PostIt/ViewModels/MainViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/MainViewModel.cs @@ -250,7 +250,23 @@ public partial class MainViewModel : ViewModelBase StatusMessage = "Select an existing post before managing ACL."; return; } - await ((App)App.Current!).PushPageAsync(GetACLViewModel(SelectedPost)).ConfigureAwait(true); + + var postForAcl = SelectedPost; + try + { + var detailed = await BlogClient!.GetPostAsync(SelectedPost.Id).ConfigureAwait(true); + if (detailed is not null) + { + postForAcl = detailed; + SelectedPost = detailed; + } + } + catch + { + // Keep the dialog usable even if the detail refresh fails. + } + + await ((App)App.Current!).PushPageAsync(GetACLViewModel(postForAcl)).ConfigureAwait(true); } [RelayCommand] diff --git a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs index ae9e71d5..1c6b8864 100644 --- a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Linq; +using System.Net; using System.Threading.Tasks; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; @@ -8,6 +10,8 @@ using Yavsc.Blogspot; using Yavsc.Api.Client; using Yavsc.Api.Client.Dtos; using Yavsc.Abstract.BlogSpot; +using Yavsc.Abstract.Identity.Security; +using System.Net.Http; namespace PostIt.ViewModels; @@ -41,7 +45,7 @@ public partial class PostAclDialogViewModel : ViewModelBase MyCircles { get; set; } = new(); [ObservableProperty] - public partial ObservableCollection + public partial ObservableCollection AclEntries { get; set; } = new(); [ObservableProperty] @@ -77,6 +81,12 @@ public partial class PostAclDialogViewModel : ViewModelBase Post = post ?? throw new ArgumentNullException(nameof(post)); _aclClient = aclClient ?? throw new ArgumentNullException(nameof(aclClient)); _circleClient = circleClient ?? throw new ArgumentNullException(nameof(circleClient)); + + AclEntries = new ObservableCollection(post.GetACL().Select(a => new CircleAuthorization + { + CircleId = a.CircleId + })); + SelectedCircleToAdd = null; } public override bool CanNavigateNext { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } @@ -90,12 +100,10 @@ public partial class PostAclDialogViewModel : ViewModelBase IsBusy = true; try { - // Load circles and ACL entries in parallel — both are - // independent reads on the same host. The caller's uid - // is implicit in both endpoints. + // Load circles for the picker. ACL entries come from the + // BlogPostDto detail payload (source of truth for initial state). var circlesTask = _circleClient.GetMyCirclesAsync(); - var aclTask = _aclClient.GetMyAclAsync(); - await Task.WhenAll(circlesTask, aclTask); + await Task.WhenAll(circlesTask); var circles = circlesTask.Result ?? new List(); MyCircles = new ObservableCollection(circles); @@ -126,14 +134,20 @@ public partial class PostAclDialogViewModel : ViewModelBase IsBusy = true; try { - var created = await _aclClient.GrantAsync(new Yavsc.Abstract.BlogSpot.PostAccessControlRulePayload + if (AclEntries.Any(a => a.CircleId == SelectedCircleToAdd.Id)) + { + StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; + return; + } + + var created = await _aclClient.GrantAsync(new PostAccessControlRulePayload { CircleId = SelectedCircleToAdd.Id, BlogPostId = Post.Id }); if (created is not null) { - AclEntries.Add(created); + AclEntries.Add(new CircleAuthorization { CircleId = created.CircleId }); StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » autorisé"; } else @@ -141,6 +155,13 @@ public partial class PostAclDialogViewModel : ViewModelBase StatusMessage = "Autorisation refusée par le serveur"; } } + catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Conflict) + { + // Conflict means the link already exists in backend. Resync + // from the dedicated ACL API so the UI reflects server truth. + await ReloadAclEntriesFromServerAsync(); + StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; + } catch (Exception ex) { StatusMessage = $"Erreur: {ex.Message}"; @@ -159,7 +180,9 @@ public partial class PostAclDialogViewModel : ViewModelBase try { await _aclClient.RevokeAsync(acl.CircleId); - AclEntries.Remove(acl); + var existing = AclEntries.FirstOrDefault(e => e.CircleId == acl.CircleId); + if (existing is not null) + AclEntries.Remove(existing); StatusMessage = "Autorisation révoquée"; } catch (Exception ex) @@ -171,4 +194,16 @@ public partial class PostAclDialogViewModel : ViewModelBase IsBusy = false; } } + + private async Task ReloadAclEntriesFromServerAsync() + { + var allAcl = await _aclClient.GetMyAclAsync(); + var currentPostAcl = (allAcl ?? new List()) + .Where(a => a.BlogPostId == Post.Id) + .Select(a => new CircleAuthorization { CircleId = a.CircleId }) + .GroupBy(a => a.CircleId) + .Select(g => g.First()) + .ToList(); + AclEntries = new ObservableCollection(currentPostAcl); + } } diff --git a/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs b/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs index 0da052ae..9cb5b143 100644 --- a/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs +++ b/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs @@ -1,4 +1,5 @@ using Yavsc.Abstract.Identity.Security; +using System.Text.Json.Serialization; namespace Yavsc.Blogspot; @@ -35,11 +36,26 @@ public class BlogPostDto : IBlogPost return true; } - private List ACL { get; set; } = new List(); + public ICollection ACL = new List(); + + /// + /// Wire-only ACL bridge for System.Text.Json: accepts the + /// acl/ACL payload from GET detail responses, + /// but is never emitted on POST/PUT from the client. + /// + [JsonPropertyName("acl")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public List? WireAcl + { + get => null; + set => ACL = value ?? new List(); + } public string[] Tags { get; set; } + ICollection ICircleAuthorized.ACL => this.ACL; + public string[] GetTags() => Tags; - public ICircleAuthorization[] GetACL() => ACL.ToArray(); + public CircleAuthorization[] GetACL() => ACL.ToArray(); } diff --git a/src/Yavsc.Abstract/Blogspot/PostAccessControlRulePayload.cs b/src/Yavsc.Abstract/Blogspot/PostAccessControlRulePayload.cs index c58fca48..a42e5428 100644 --- a/src/Yavsc.Abstract/Blogspot/PostAccessControlRulePayload.cs +++ b/src/Yavsc.Abstract/Blogspot/PostAccessControlRulePayload.cs @@ -3,8 +3,7 @@ using Yavsc.Abstract.Identity.Security; namespace Yavsc.Abstract.BlogSpot; -public class PostAccessControlRulePayload : ICircleAuthorization +public class PostAccessControlRulePayload : CircleAuthorization { - public long CircleId { get; set; } public long BlogPostId { get; set; } } diff --git a/src/Yavsc.Abstract/Identity/Security/CircleAuthorization.cs b/src/Yavsc.Abstract/Identity/Security/CircleAuthorization.cs index d8b08c05..96392c7b 100644 --- a/src/Yavsc.Abstract/Identity/Security/CircleAuthorization.cs +++ b/src/Yavsc.Abstract/Identity/Security/CircleAuthorization.cs @@ -11,7 +11,7 @@ namespace Yavsc.Abstract.Identity.Security; /// UI already has the post, and the circles are looked up by id /// against the list returned by GET /api/circle. /// -public sealed class CircleAuthorization : ICircleAuthorization +public class CircleAuthorization { public long CircleId { get; set; } } diff --git a/src/Yavsc.Abstract/Identity/Security/ICircleAuthorization.cs b/src/Yavsc.Abstract/Identity/Security/ICircleAuthorization.cs deleted file mode 100644 index 9c16bd3b..00000000 --- a/src/Yavsc.Abstract/Identity/Security/ICircleAuthorization.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Yavsc.Abstract.Identity.Security -{ - - public interface ICircleAuthorization - { - long CircleId { get; set; } - } -} diff --git a/src/Yavsc.Abstract/Identity/Security/ICircleAuthorized.cs b/src/Yavsc.Abstract/Identity/Security/ICircleAuthorized.cs index 25c21961..6b593f3c 100644 --- a/src/Yavsc.Abstract/Identity/Security/ICircleAuthorized.cs +++ b/src/Yavsc.Abstract/Identity/Security/ICircleAuthorized.cs @@ -9,7 +9,7 @@ namespace Yavsc.Abstract.Identity.Security bool AuthorizeCircle(long circleId); - ICircleAuthorization [] GetACL(); + ICollection ACL { get; } //ICircleAuthorization [] GetACL(); } } diff --git a/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs b/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs index 4aef805f..ab5ebcc6 100644 --- a/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs +++ b/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs @@ -283,8 +283,8 @@ public sealed class BlogAclApiTests : IClassFixture TestContext.Current.CancellationToken )); Assert.Equal(JsonValueKind.Array, doc.RootElement.ValueKind); - Assert.Equal(2, doc.RootElement.GetArrayLength()); - Assert.Equal(created.Id, doc.RootElement[0].GetProperty("id").GetInt64()); + Assert.True(doc.RootElement.GetArrayLength() >= 1); + Assert.Contains(doc.RootElement.EnumerateArray(), p => p.GetProperty("id").GetInt64() == created.Id); // detail should return the same post, with ACL and tags. var detailResponse = await http.GetAsync( @@ -296,7 +296,86 @@ public sealed class BlogAclApiTests : IClassFixture )); Assert.Equal(JsonValueKind.Object, detailDoc.RootElement.ValueKind); Assert.Equal(created.Id, detailDoc.RootElement.GetProperty("id").GetInt64()); - Assert.Equal(1, detailDoc.RootElement.GetProperty("acl").GetArrayLength()); + Assert.True(detailDoc.RootElement.TryGetProperty("acl", out var acl)); + Assert.False(detailDoc.RootElement.TryGetProperty("ACL", out _)); + Assert.Equal(JsonValueKind.Array, acl.ValueKind); + Assert.Equal(1, acl.GetArrayLength()); + + var aclEntry = acl[0]; + Assert.Equal(JsonValueKind.Object, aclEntry.ValueKind); + Assert.True(aclEntry.TryGetProperty("circleId", out var circleId)); + Assert.Equal(_fixture.CircleId, circleId.GetInt64()); + } + + [Fact] + public async Task Non_owner_can_read_restricted_post_but_receives_empty_acl_in_list_and_detail() + { + CleanupAcl(); + _fixture.SeedUser(_fixture.DefaultUserLogin); + _fixture.SeedUser("tester"); + _fixture.SeedCircle(_fixture.DefaultUserLogin, "test", false, + new[] { _fixture.DefaultUserLogin, "tester" }); + + using var ownerHttp = NewClient(_fixture.DefaultUserLogin); + using var readerHttp = NewClient("tester"); + + var draft = new BlogPost + { + Id = 0, + Title = "ACL scrub test", + Article = "Visible to circle member", + DateCreated = DateTime.UtcNow, + DateModified = DateTime.UtcNow + }; + + var postResponse = await ownerHttp.PostAsJsonAsync( + BlogUrl(), + draft, + TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode); + + var created = await postResponse.Content.ReadFromJsonAsync( + TestContext.Current.CancellationToken); + Assert.NotNull(created); + Assert.NotEqual(0, created!.Id); + + var grantResponse = await ownerHttp.PostAsJsonAsync( + BlogAclUrl(), + new PostAccessControlRulePayload + { + CircleId = _fixture.CircleId, + BlogPostId = created.Id + }, + TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.Created, grantResponse.StatusCode); + + var listResponse = await readerHttp.GetAsync( + BlogUrl(), + TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, listResponse.StatusCode); + + using var listDoc = JsonDocument.Parse(await listResponse.Content.ReadAsStringAsync( + TestContext.Current.CancellationToken)); + Assert.Equal(JsonValueKind.Array, listDoc.RootElement.ValueKind); + foreach (var listed in listDoc.RootElement.EnumerateArray()) + { + var authorId = listed.GetProperty("authorId").GetString(); + if (string.Equals(authorId, "tester", StringComparison.Ordinal)) + continue; + + Assert.True(listed.TryGetProperty("acl", out var listedAcl)); + Assert.Equal(0, listedAcl.GetArrayLength()); + } + + var detailResponse = await readerHttp.GetAsync( + $"{BlogUrl()}/{created.Id}", + TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, detailResponse.StatusCode); + + using var detailDoc = JsonDocument.Parse(await detailResponse.Content.ReadAsStringAsync( + TestContext.Current.CancellationToken)); + Assert.True(detailDoc.RootElement.TryGetProperty("acl", out var detailAcl)); + Assert.Equal(0, detailAcl.GetArrayLength()); } } diff --git a/src/Yavsc.Org/Services/BlogSpotService.cs b/src/Yavsc.Org/Services/BlogSpotService.cs index 7eac07a1..39e9329f 100644 --- a/src/Yavsc.Org/Services/BlogSpotService.cs +++ b/src/Yavsc.Org/Services/BlogSpotService.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; using Yavsc.Blogspot; using Yavsc.Models; +using Yavsc.Models.Access; using Yavsc.Models.Blog; using Yavsc.Server.Exceptions; using Yavsc.Server.Helpers; @@ -97,6 +98,7 @@ public class OldBlogSpotService throw new AuthorizationFailureException(auth); } var pub = await _context.blogSpotPublications.AnyAsync(x => x.BlogpostId == blog.Id); + ScrubAclForViewer(blog, user); return new BlogPostEditViewModel(blog, pub); } @@ -118,6 +120,7 @@ public class OldBlogSpotService { throw new AuthorizationFailureException(auth); } + ScrubAclForViewer(blog, user); foreach (var c in blog.Comments) { c.Author = _context.Users.First(u => u.Id == c.AuthorId); @@ -189,13 +192,14 @@ public class OldBlogSpotService public async Task> Index(ClaimsPrincipal user, string id, int skip = 0, int take = 25) { + string? viewerId = user.Identity?.IsAuthenticated == true ? user.GetUserId() : null; IEnumerable posts; if (user.Identity.IsAuthenticated) { - string viewerId = user.GetUserId(); + string viewerIdNonNull = viewerId!; long[] userCircles = await _context.Circle.Include(c => c.Members). - Where(c => c.Members.Any(m => m.MemberId == viewerId)) + Where(c => c.Members.Any(m => m.MemberId == viewerIdNonNull)) .Select(c => c.Id).ToArrayAsync(); posts = _context.BlogSpot @@ -205,7 +209,7 @@ public class OldBlogSpotService .Include(p => p.Comments) .Where(p => p.ACL == null || p.ACL.Count == 0 - || (p.AuthorId == viewerId) + || (p.AuthorId == viewerIdNonNull) || (userCircles != null && p.ACL.Any(a => userCircles.Contains(a.CircleId))) ); @@ -223,7 +227,11 @@ public class OldBlogSpotService .Select(p => p.BlogPost).ToArray(); } - var data = posts.OrderByDescending(p => p.DateModified) + var materialised = posts.ToList(); + foreach (var post in materialised.OfType()) + ScrubAclForViewer(post, user); + + var data = materialised.OrderByDescending(p => p.DateModified) .Skip(skip) .Take(take); return data; @@ -246,7 +254,11 @@ public class OldBlogSpotService { string? posterId = (await _context.Users.SingleOrDefaultAsync(u => u.UserName == posterName))?.Id ?? null; if (posterId == null) return Array.Empty(); - return _context.UserPosts(posterId, readerId); + var posts = _context.UserPosts(posterId, readerId).ToList(); + var viewerId = string.Equals(readerId, posterId, StringComparison.Ordinal) ? readerId : null; + foreach (var post in posts) + ScrubAclForViewer(post, viewerId); + return posts; } public object? GetTitle(string title) @@ -266,4 +278,39 @@ public class OldBlogSpotService .SingleOrDefaultAsync(x => x.Id == value); } + private static void ScrubAclForViewer(Yavsc.Models.Blog.BlogPost post, ClaimsPrincipal? user) + { + if (!IsOwner(post, user)) + post.ACL = new List(); + } + + private static void ScrubAclForViewer(Yavsc.Models.Blog.BlogPost post, string? viewerId) + { + if (!string.Equals(post.AuthorId, viewerId, StringComparison.Ordinal) + && !string.Equals(post.Author?.Id, viewerId, StringComparison.Ordinal)) + post.ACL = new List(); + } + + private static bool IsOwner(Yavsc.Models.Blog.BlogPost post, ClaimsPrincipal? user) + { + if (user?.Identity?.IsAuthenticated != true) return false; + + var viewerId = user.GetUserId(); + var viewerName = user.GetUserName() ?? user.Identity?.Name; + + if (!string.IsNullOrWhiteSpace(viewerId)) + { + if (string.Equals(post.AuthorId, viewerId, StringComparison.Ordinal)) return true; + if (string.Equals(post.Author?.Id, viewerId, StringComparison.Ordinal)) return true; + } + + if (!string.IsNullOrWhiteSpace(viewerName)) + { + if (string.Equals(post.AuthorId, viewerName, StringComparison.OrdinalIgnoreCase)) return true; + if (string.Equals(post.Author?.UserName, viewerName, StringComparison.OrdinalIgnoreCase)) return true; + } + + return false; + } + } diff --git a/src/Yavsc.Server/Models/Blog/BlogPost.cs b/src/Yavsc.Server/Models/Blog/BlogPost.cs index e5fd615d..4c2f2ae5 100644 --- a/src/Yavsc.Server/Models/Blog/BlogPost.cs +++ b/src/Yavsc.Server/Models/Blog/BlogPost.cs @@ -66,9 +66,9 @@ namespace Yavsc.Models.Blog return ACL?.Any(i => i.CircleId == circleId) ?? true; } - public ICircleAuthorization[] GetACL() + public CircleAuthorization[] GetACL() { - return ACL?.ToArray() ?? Array.Empty(); + return ACL?.ToArray() ?? Array.Empty(); } public void Tag(Tag tag) @@ -134,5 +134,16 @@ namespace Yavsc.Models.Blog }; } } + + ICollection ICircleAuthorized.ACL + { + get + { + return ACL?.Select(a => new CircleAuthorization + { + CircleId = a.CircleId + }).ToList() ?? new List(); + } + } } } diff --git a/src/Yavsc.Server/Services/BlogSpotService.cs b/src/Yavsc.Server/Services/BlogSpotService.cs index 6b85a4c3..a0832630 100644 --- a/src/Yavsc.Server/Services/BlogSpotService.cs +++ b/src/Yavsc.Server/Services/BlogSpotService.cs @@ -1,15 +1,16 @@ using System.Diagnostics; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; +using Yavsc.Blogspot; using Yavsc.Models; +using Yavsc.Models.Access; using Yavsc.Models.Blog; using Yavsc.Server.Exceptions; using Yavsc.Server.Helpers; using Yavsc.Services; using Yavsc.ViewModels.Auth; -using Microsoft.AspNetCore.Http; -using Yavsc.Blogspot; public class BlogSpotService { @@ -17,24 +18,25 @@ public class BlogSpotService private readonly IAuthorizationService _authorizationService; private readonly IFileSystemAuthManager fileSystemAuthManager; - public BlogSpotService(ApplicationDbContext context, - IAuthorizationService authorizationService, - IFileSystemAuthManager fileSystemAuthManager) + public BlogSpotService( + ApplicationDbContext context, + IAuthorizationService authorizationService, + IFileSystemAuthManager fileSystemAuthManager) { _authorizationService = authorizationService; _context = context; this.fileSystemAuthManager = fileSystemAuthManager; } - public Yavsc.Models.Blog.BlogPost Create(string userId, Yavsc.Models.Blog.BlogPost post, IFormFileCollection files) + public BlogPost Create(string userId, BlogPost post, IFormFileCollection files) { // Sauvegarder le post d'abord pour obtenir son ID - // Le créateur vient de l'authentification, donc on ne le prend pas du post + // Le createur vient de l'authentification, donc on ne le prend pas du post post.AuthorId = userId; _context.BlogSpot.Add(post); _context.SaveChanges(userId); - // Traiter les fichiers attachés s'il y en a + // Traiter les fichiers attaches s'il y en a if (files != null && files.Count > 0) { var user = _context.Users.FirstOrDefault(u => u.Id == userId); @@ -42,23 +44,19 @@ public class BlogSpotService { try { - // Créer un répertoire pour les fichiers du blog string blogFilesSubdir = $"blogs/{post.Id}"; string destDir = Path.Combine( AbstractFileSystemHelpers.UserFilesDirName, user.UserName, - blogFilesSubdir - ); + blogFilesSubdir); var di = new DirectoryInfo(destDir); if (!di.Exists) di.Create(); - // Traiter chaque fichier foreach (var formFile in files) { var fileInfo = user.ReceiveUserFile(destDir, formFile); if (fileInfo != null && !fileInfo.QuotaOffense) { - // Créer une entrée UploadedFile si nécessaire var uploadedFile = new UploadedFile { Path = fileInfo.FileName, @@ -68,7 +66,6 @@ public class BlogSpotService _context.UploadedFiles.Add(uploadedFile); _context.SaveChanges(userId); - // Lier le fichier au post var attachment = new BlogAttachedFile { PostId = post.Id, @@ -81,52 +78,56 @@ public class BlogSpotService } catch (Exception ex) { - // Logger l'erreur mais ne pas échouer la création du post - System.Diagnostics.Debug.WriteLine($"Erreur lors du traitement des fichiers : {ex.Message}"); + Debug.WriteLine($"Erreur lors du traitement des fichiers : {ex.Message}"); } } } return post; } + public async Task GetPostForEdition(ClaimsPrincipal user, long blogPostId) { - var blog = await _context.BlogSpot.Include(x => x.Author).Include(x => x.ACL).SingleAsync(m => m.Id == blogPostId); - var auth = await _authorizationService.AuthorizeAsync(user, blog, new EditPermission()); + var blog = await _context.BlogSpot + .Include(x => x.Author) + .Include(x => x.ACL) + .SingleAsync(m => m.Id == blogPostId); + + var auth = await _authorizationService.AuthorizeAsync(user, blog, new EditPermission()); if (!auth.Succeeded) - { throw new AuthorizationFailureException(auth); - } + var pub = await _context.blogSpotPublications.AnyAsync(x => x.BlogpostId == blog.Id); + ScrubAclForViewer(blog, user); return new BlogPostEditViewModel(blog, pub); } - public async Task Details(ClaimsPrincipal user, long blogPostId) + public async Task Details(ClaimsPrincipal user, long blogPostId) { - Yavsc.Models.Blog.BlogPost blog = await _context.BlogSpot - .Include(p => p.Author) - .Include(p => p.Tags) - .Include(p => p.Comments) - .Include(p => p.ACL) - .SingleAsync(m => m.Id == blogPostId); + BlogPost blog = await _context.BlogSpot + .Include(p => p.Author) + .Include(p => p.Tags) + .Include(p => p.Comments) + .Include(p => p.ACL) + .SingleAsync(m => m.Id == blogPostId); + if (blog == null) - { return null; - } - // Hydrate the [NotMapped] IsPublished flag from the - // publication table so the wire JSON carries it. + + // Hydrate le flag [NotMapped] depuis la table de publication. blog.IsPublished = await _context.blogSpotPublications .AnyAsync(pub => pub.BlogpostId == blogPostId); + var auth = await _authorizationService.AuthorizeAsync(user, blog, new ReadPermission()); if (!auth.Succeeded) - { throw new AuthorizationFailureException(auth); - } + + ScrubAclForViewer(blog, user); + foreach (var c in blog.Comments) - { c.Author = _context.Users.First(u => u.Id == c.AuthorId); - } + return blog; } @@ -134,54 +135,45 @@ public class BlogSpotService { var blog = _context.BlogSpot.SingleOrDefault(b => b.Id == blogEdit.Id); Debug.Assert(blog != null); + var auth = await _authorizationService.AuthorizeAsync(user, blog, new EditPermission()); if (!auth.Succeeded) - { throw new AuthorizationFailureException(auth); - } + blog.Article = blogEdit.Article; blog.Title = blogEdit.Title; blog.Photo = blogEdit.Photo; blog.ACL = blogEdit.ACL; - // saves the change _context.Update(blog); - var publication = await _context.blogSpotPublications.SingleOrDefaultAsync - (p => p.BlogpostId == blogEdit.Id); + + var publication = await _context.blogSpotPublications + .SingleOrDefaultAsync(p => p.BlogpostId == blogEdit.Id); + if (publication != null) { if (!blogEdit.Publish) - { _context.blogSpotPublications.Remove(publication); - } } - else + else if (blogEdit.Publish) { - if (blogEdit.Publish) - { - _context.blogSpotPublications.Add( - new BlogSpotPublication - { - BlogpostId = blogEdit.Id - } - ); - } + _context.blogSpotPublications.Add(new BlogSpotPublication { BlogpostId = blogEdit.Id }); } + _context.SaveChanges(user.GetUserId()); } - public async Task Modify(ClaimsPrincipal user, Yavsc.Models.Blog.BlogPost blog) + public async Task Modify(ClaimsPrincipal user, BlogPost blog) { - var existing = await _context.BlogSpot.Include(b => b.ACL).SingleOrDefaultAsync(b => b.Id == blog.Id); + var existing = await _context.BlogSpot + .Include(b => b.ACL) + .SingleOrDefaultAsync(b => b.Id == blog.Id); + if (existing == null) - { throw new InvalidOperationException($"Blog post {blog.Id} not found."); - } var auth = await _authorizationService.AuthorizeAsync(user, existing, new EditPermission()); if (!auth.Succeeded) - { throw new AuthorizationFailureException(auth); - } existing.Title = blog.Title; existing.Article = blog.Article; @@ -199,9 +191,10 @@ public class BlogSpotService if (user.Identity.IsAuthenticated) { string viewerId = user.GetUserId(); - long[] userCircles = await _context.Circle.Include(c => c.Members). - Where(c => c.Members.Any(m => m.MemberId == viewerId)) - .Select(c => c.Id).ToArrayAsync(); + long[] userCircles = await _context.Circle.Include(c => c.Members) + .Where(c => c.Members.Any(m => m.MemberId == viewerId)) + .Select(c => c.Id) + .ToArrayAsync(); posts = _context.BlogSpot .Include(b => b.Author) @@ -209,34 +202,25 @@ public class BlogSpotService .Include(p => p.Tags) .Include(p => p.Comments) .Where(p => p.ACL == null - || p.ACL.Count == 0 - || (p.AuthorId == viewerId) - || (userCircles != null && - p.ACL.Any(a => userCircles.Contains(a.CircleId))) - ); + || p.ACL.Count == 0 + || p.AuthorId == viewerId + || (userCircles != null && p.ACL.Any(a => userCircles.Contains(a.CircleId)))); } else { posts = _context.blogSpotPublications - .Include(p => p.BlogPost) - .Include(b => b.BlogPost.Author) - .Include(p => p.BlogPost.ACL) - .Include(p => p.BlogPost.Tags) - .Include(p => p.BlogPost.Comments) - .Where(p => p.BlogPost.ACL == null - || p.BlogPost.ACL.Count == 0) - .Select(p => p.BlogPost).ToArray(); + .Include(p => p.BlogPost) + .Include(b => b.BlogPost.Author) + .Include(p => p.BlogPost.ACL) + .Include(p => p.BlogPost.Tags) + .Include(p => p.BlogPost.Comments) + .Where(p => p.BlogPost.ACL == null || p.BlogPost.ACL.Count == 0) + .Select(p => p.BlogPost) + .ToArray(); } - // Materialise before hydrating IsPublished: it's a - // computed [NotMapped] property that needs to be set - // on each BlogPost instance after the query runs. var materialised = posts.ToList(); - // Single bulk lookup for the IsPublished flag — avoid - // the N+1 of one AnyAsync per post. The published ids - // are loaded once and matched against the post list - // in memory. var postIds = materialised.Select(p => p.Id).ToList(); if (postIds.Count > 0) { @@ -244,11 +228,15 @@ public class BlogSpotService .Where(pub => postIds.Contains(pub.BlogpostId)) .Select(pub => pub.BlogpostId) .ToListAsync(); + var publishedSet = publishedIds.ToHashSet(); - foreach (var post in materialised.OfType()) + foreach (var post in materialised.OfType()) post.IsPublished = publishedSet.Contains(post.Id); } + foreach (var post in materialised.OfType()) + ScrubAclForViewer(post, user); + return materialised .OrderByDescending(p => p.DateModified) .Skip(skip) @@ -257,61 +245,45 @@ public class BlogSpotService public async Task Delete(ClaimsPrincipal user, long id) { - var uid = user.GetUserId(); - Yavsc.Models.Blog.BlogPost blog = _context.BlogSpot.Single(m => m.Id == id); - + BlogPost blog = _context.BlogSpot.Single(m => m.Id == id); _context.BlogSpot.Remove(blog); _context.SaveChanges(user.GetUserId()); } - public async Task> UserPosts( - string posterName, - string? readerId, - int pageLen = 10, - int pageNum = 0) + public async Task> UserPosts(string posterName, string? readerId, int pageLen = 10, int pageNum = 0) { - string? posterId = (await _context.Users.SingleOrDefaultAsync(u => u.UserName == posterName))?.Id ?? null; - if (posterId == null) return Array.Empty(); - return _context.UserPosts(posterId, readerId); + string? posterId = (await _context.Users.SingleOrDefaultAsync(u => u.UserName == posterName))?.Id; + if (posterId == null) return Array.Empty(); + + var posts = _context.UserPosts(posterId, readerId).ToList(); + var isOwnerReader = string.Equals(readerId, posterId, StringComparison.Ordinal); + + foreach (var post in posts) + { + if (!isOwnerReader) + post.ACL = new List(); + } + + return posts; } public object? GetTitle(string title) { - return _context.BlogSpot.Include( - b => b.Author - ).Where(x => x.Title == title).OrderByDescending( - x => x.DateCreated - ).ToList(); + return _context.BlogSpot + .Include(b => b.Author) + .Where(x => x.Title == title) + .OrderByDescending(x => x.DateCreated) + .ToList(); } - public async Task GetBlogPostAsync(long value) + public async Task GetBlogPostAsync(long value) { return await _context.BlogSpot - .Include(b => b.Author) - .Include(b => b.ACL) - .SingleOrDefaultAsync(x => x.Id == value); + .Include(b => b.Author) + .Include(b => b.ACL) + .SingleOrDefaultAsync(x => x.Id == value); } - /// - /// Toggle a post's publication state. - /// true adds a row to blogSpotPublications (the post - /// becomes visible to anonymous callers via - /// ); false removes - /// the row if present. - /// - /// The post must already exist (caller must be the - /// author — this is gated by the controller's EditPermission - /// check). Returns false when the post does not exist; true - /// on a successful toggle. - /// - /// This is the same toggle the - /// -flavoured - /// - /// overload performs inline; extracted here so the - /// /api/blog/{id}/publish endpoint can hit it without - /// forcing the caller to round-trip the full BlogPost in - /// the request body. - /// public async Task SetPublishAsync(ClaimsPrincipal user, long postId, bool publish) { var blog = await _context.BlogSpot.SingleOrDefaultAsync(b => b.Id == postId); @@ -319,28 +291,33 @@ public class BlogSpotService var auth = await _authorizationService.AuthorizeAsync(user, blog, new EditPermission()); if (!auth.Succeeded) - { throw new AuthorizationFailureException(auth); - } - var existing = await _context.blogSpotPublications.SingleOrDefaultAsync( - p => p.BlogpostId == postId); + var existing = await _context.blogSpotPublications.SingleOrDefaultAsync(p => p.BlogpostId == postId); if (publish) { if (existing == null) - { _context.blogSpotPublications.Add(new BlogSpotPublication { BlogpostId = postId }); - } } else { if (existing != null) - { _context.blogSpotPublications.Remove(existing); - } } + await _context.SaveChangesAsync(user.GetUserId()); return true; } + private static void ScrubAclForViewer(BlogPost post, ClaimsPrincipal? user) + { + if (!IsOwner(post, user)) + post.ACL = new List(); + } + + private static bool IsOwner(BlogPost post, ClaimsPrincipal? user) + { + if (user?.Identity?.IsAuthenticated != true) return false; + return string.Equals(user.GetUserId(), post.AuthorId, StringComparison.Ordinal); + } } From 34ea58182d9f902c3a9ac85f7850ad3e4e3a64f1 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 30 Aug 2026 19:44:25 +0100 Subject: [PATCH 03/31] display the circle names --- .../ViewModels/PostAclDialogViewModel.cs | 34 ++++++++++++++----- src/PostIt/PostIt/Views/PostAclDialog.axaml | 7 ++-- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs index 1c6b8864..60544606 100644 --- a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs @@ -15,6 +15,12 @@ using System.Net.Http; namespace PostIt.ViewModels; +public sealed class PostAclEntry +{ + public long CircleId { get; init; } + public string CircleName { get; init; } = string.Empty; +} + /// /// View model for the "Gérer l'ACL" modal of a single blog post. /// @@ -45,7 +51,7 @@ public partial class PostAclDialogViewModel : ViewModelBase MyCircles { get; set; } = new(); [ObservableProperty] - public partial ObservableCollection + public partial ObservableCollection AclEntries { get; set; } = new(); [ObservableProperty] @@ -82,10 +88,7 @@ public partial class PostAclDialogViewModel : ViewModelBase _aclClient = aclClient ?? throw new ArgumentNullException(nameof(aclClient)); _circleClient = circleClient ?? throw new ArgumentNullException(nameof(circleClient)); - AclEntries = new ObservableCollection(post.GetACL().Select(a => new CircleAuthorization - { - CircleId = a.CircleId - })); + AclEntries = new ObservableCollection(post.GetACL().Select(a => ToAclEntry(a.CircleId))); SelectedCircleToAdd = null; } @@ -108,6 +111,9 @@ public partial class PostAclDialogViewModel : ViewModelBase var circles = circlesTask.Result ?? new List(); MyCircles = new ObservableCollection(circles); + // Resolve labels now that circles are available. + AclEntries = new ObservableCollection(AclEntries.Select(a => ToAclEntry(a.CircleId))); + StatusMessage = $"{AclEntries.Count} autorisation(s)"; _loaded = true; @@ -147,7 +153,7 @@ public partial class PostAclDialogViewModel : ViewModelBase }); if (created is not null) { - AclEntries.Add(new CircleAuthorization { CircleId = created.CircleId }); + AclEntries.Add(ToAclEntry(created.CircleId)); StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » autorisé"; } else @@ -173,7 +179,7 @@ public partial class PostAclDialogViewModel : ViewModelBase } [RelayCommand] - public async Task RevokeAsync(PostAccessControlRulePayload? acl) + public async Task RevokeAsync(PostAclEntry? acl) { if (acl is null) return; IsBusy = true; @@ -200,10 +206,20 @@ public partial class PostAclDialogViewModel : ViewModelBase var allAcl = await _aclClient.GetMyAclAsync(); var currentPostAcl = (allAcl ?? new List()) .Where(a => a.BlogPostId == Post.Id) - .Select(a => new CircleAuthorization { CircleId = a.CircleId }) + .Select(a => ToAclEntry(a.CircleId)) .GroupBy(a => a.CircleId) .Select(g => g.First()) .ToList(); - AclEntries = new ObservableCollection(currentPostAcl); + AclEntries = new ObservableCollection(currentPostAcl); + } + + private PostAclEntry ToAclEntry(long circleId) + { + var circleName = MyCircles.FirstOrDefault(c => c.Id == circleId)?.Name; + return new PostAclEntry + { + CircleId = circleId, + CircleName = string.IsNullOrWhiteSpace(circleName) ? $"Cercle #{circleId}" : circleName + }; } } diff --git a/src/PostIt/PostIt/Views/PostAclDialog.axaml b/src/PostIt/PostIt/Views/PostAclDialog.axaml index da5320d3..8552988e 100644 --- a/src/PostIt/PostIt/Views/PostAclDialog.axaml +++ b/src/PostIt/PostIt/Views/PostAclDialog.axaml @@ -3,8 +3,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="PostIt.Views.PostAclDialog" xmlns:vm="using:PostIt.ViewModels" - xmlns:dtos="using:Yavsc.Api.Client.Dtos" - xmlns:yabst="using:Yavsc.Abstract.Identity.Security" + xmlns:dtos="using:Yavsc.Api.Client.Dtos" x:DataType="vm:PostAclDialogViewModel" > @@ -32,10 +31,10 @@ - + - public SignaturePadData Snapshot() => new(_strokes.ToArray()); + /// + /// Copy of the current in-progress stroke, without the length + /// prefix used for sealed strokes. The view can render this as a + /// live preview while the user is still drawing. + /// + internal IReadOnlyList PendingStroke + => _capturing && _pendingPoints > 0 + ? _strokes.GetRange(_strokes.Count - 2 * _pendingPoints, 2 * _pendingPoints) + : Array.Empty(); + // --- Test-only surface (visible to PostIt.Tests) ------------------- /// diff --git a/src/PostIt/PostIt/Views/SignaturePage.axaml.cs b/src/PostIt/PostIt/Views/SignaturePage.axaml.cs index da6b8b7b..b7af78bd 100644 --- a/src/PostIt/PostIt/Views/SignaturePage.axaml.cs +++ b/src/PostIt/PostIt/Views/SignaturePage.axaml.cs @@ -87,5 +87,28 @@ public partial class SignaturePage : ContentPage poly.Points = pts; InkLayer.Children.Add(poly); } + + var pending = _control.PendingStroke; + if (pending.Count > 0) + { + var poly = new Polyline + { + Stroke = StrokeBrush, + StrokeThickness = StrokeThickness, + StrokeLineCap = PenLineCap.Round, + StrokeJoin = PenLineJoin.Round, + }; + + var pts = new List(pending.Count / 2); + for (int p = 0; p < pending.Count; p += 2) + { + int nx = pending[p]; + int ny = pending[p + 1]; + pts.Add(new Point(nx / CoordinateMax * w, ny / CoordinateMax * h)); + } + + poly.Points = pts; + InkLayer.Children.Add(poly); + } } } From 6e2fec1620a292e821d5b886380da3ace15304c8 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 30 Aug 2026 23:55:09 +0100 Subject: [PATCH 06/31] An activity interface --- contrib/.env-sample | 24 ++ contrib/Makefile | 13 +- contrib/tmp/yavscBlogs.service | 37 +++ .../ActivitiesPageViewModelTests.cs | 113 +++++++++ .../PostIt.Tests/SignaturePadControlTests.cs | 20 ++ .../PostIt/Controls/SignaturePadControl.cs | 11 + .../Helpers/ServiceCollectionHelpers.cs | 4 + src/PostIt/PostIt/ViewLocator.cs | 1 + .../ViewModels/ActivitiesPageViewModel.cs | 219 ++++++++++++++++++ .../PostIt/ViewModels/HomePageViewModel.cs | 24 +- .../PostIt/ViewModels/Settings/Settings.cs | 36 ++- src/PostIt/PostIt/Views/ActivitiesPage.axaml | 79 +++++++ .../PostIt/Views/ActivitiesPage.axaml.cs | 17 ++ src/PostIt/PostIt/Views/HomePage.axaml | 4 + .../PostIt/Views/SignaturePage.axaml.cs | 10 +- .../Workflow/ActivityBrowseItemDto.cs | 17 ++ .../Workflow/ActivityPerformerDto.cs | 18 ++ .../Workflow/CommandFormSummaryDto.cs | 11 + src/Yavsc.Api.Client/ActivityApiClient.cs | 56 +++++ .../Business/ActivityApiController.cs | 128 ++++++++++ .../Controllers/Business/BillingController.cs | 1 + .../Business/BookQueryApiController.cs | 1 + .../Business/EstimateApiController.cs | 1 + .../EstimateTemplatesApiController.cs | 2 + .../Business/FrontOfficeApiController.cs | 2 + .../Business/PaymentApiController.cs | 2 + .../Business/PerformersApiController.cs | 1 + .../Business/ProductApiController.cs | 1 + src/Yavsc.Org/Contants.cs | 3 +- src/Yavsc.Org/Extensions/HostingExtensions.cs | 1 + 30 files changed, 847 insertions(+), 10 deletions(-) create mode 100644 contrib/.env-sample create mode 100644 contrib/tmp/yavscBlogs.service create mode 100644 src/PostIt/PostIt.Tests/ActivitiesPageViewModelTests.cs create mode 100644 src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs create mode 100644 src/PostIt/PostIt/Views/ActivitiesPage.axaml create mode 100644 src/PostIt/PostIt/Views/ActivitiesPage.axaml.cs create mode 100644 src/Yavsc.Abstract/Workflow/ActivityBrowseItemDto.cs create mode 100644 src/Yavsc.Abstract/Workflow/ActivityPerformerDto.cs create mode 100644 src/Yavsc.Abstract/Workflow/CommandFormSummaryDto.cs create mode 100644 src/Yavsc.Api.Client/ActivityApiClient.cs diff --git a/contrib/.env-sample b/contrib/.env-sample new file mode 100644 index 00000000..fb01ede4 --- /dev/null +++ b/contrib/.env-sample @@ -0,0 +1,24 @@ +# parametres de déploiement au Makefile + +POSTGRES_HOST=localhost +POSTGRES_PORT=5432 +POSTGRES_DB=yavsc +POSTGRES_USER=yavsc +POSTGRES_PASSWORD= + +HTTP_HOST=localhost + +Org_PORT=83 +Blogs_PORT=85 +Api_PORT=87 + +PostIt_CLIENT_ID=postit + +ASPNETCORE_Smtp__Host="mercure.pschneider.fr" +ASPNETCORE_Smtp__Port=465 +ASPNETCORE_Smtp__SenderName="Paul Schneider" +ASPNETCORE_Smtp__SenderEmail="paul@pschneider.fr" +ASPNETCORE_Smtp__UserName="paul" +ASPNETCORE_Smtp__Password="" + +DESTDIR=/srv/www/yavsc diff --git a/contrib/Makefile b/contrib/Makefile index 151045db..79145668 100644 --- a/contrib/Makefile +++ b/contrib/Makefile @@ -1,4 +1,4 @@ -APP_PROJECT_NAMES=Org Blogs +APP_PROJECT_NAMES=Org Blogs Api SLNDIR=.. include $(SLNDIR)/.env @@ -9,9 +9,11 @@ generated/: generated/yavscOrg.service: generated/yavscBlogs.service: +generated/yavscApi.service: generated/yavsc%.service: generated/ template.service $(SLNDIR)/.env @cat template.service | APP_NAME="$*" \ + DESTDIR="$(DESTDIR)" \ HTTP_HOST="$(HTTP_HOST)" \ HTTP_PORT="$*_$(HTTP_PORT)" \ BASEAPPDIR="$(BASEAPPDIR)" \ @@ -33,11 +35,12 @@ generated/yavsc%.service: generated/ template.service $(SLNDIR)/.env @echo Created service file: $@ -copy-services: copy-service-Org copy-service-Blogs +copy-services: copy-service-Org copy-service-Blogs copy-service-Api copy-service-Org: /etc/systemd/system/yavscOrg.service copy-service-Blogs: /etc/systemd/system/yavscBlogs.service +copy-service-Api: /etc/systemd/system/yavscApi.service -copy-binaries: build_publish_Org build_publish_Blogs stop-services +copy-binaries: build_publish_Org build_publish_Blogs build_publish_Api stop-services @for project in $(APP_PROJECT_NAMES); \ do LCAPI=$$(echo $${project}|tr [:upper:] [:lower:]) ; \ echo "$${project} -> $${LCAPI}" ; \ @@ -60,6 +63,8 @@ copy-binaries: build_publish_Org build_publish_Blogs stop-services build_publish_%: clean_publish_dir_% @ASPNETCORE_ENV=$(CONFIGURATION) dotnet publish $(SLNDIR)/src/Yavsc.$*/Yavsc.$*.csproj +build_publish: build_publish_Org build_publish_Blogs build_publish_Api + clean_publish_dir_%: @rm -rf $(SLNDIR)/src/Yavsc.$*/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish @@ -84,6 +89,7 @@ stop-services: $(SLNDIR)/src/Yavsc.Org/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish $(SLNDIR)/src/Yavsc.Blogs/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish +$(SLNDIR)/src/Yavsc.Api/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish showConfig: @echo CONFIGURATION: $(CONFIGURATION) @@ -92,4 +98,3 @@ showConfig: clean: @rm -rf generated -.PHONY: build_publish mep showConfig copy-service-Org copy-service-Blogs reinstall clean diff --git a/contrib/tmp/yavscBlogs.service b/contrib/tmp/yavscBlogs.service new file mode 100644 index 00000000..718534cd --- /dev/null +++ b/contrib/tmp/yavscBlogs.service @@ -0,0 +1,37 @@ +[Unit] +Description=yavsc-Blogs +After=syslog.target +After=network.target +Wants=postgresql.service +After=postgresql.service + +[Service] +RestartSec=5s +Type=simple +User=yavsc +Group=yavsc +WorkingDirectory=/srv/www/yavsc +ExecStart=/srv/www/yavsc/Yavsc.Blogs +Restart=always +Environment="HOME=" +Environment="ANTHROPIC_API_KEY=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" +Environment="ANTHROPIC_MAX_TOKENS=255" +Environment="ASPNETCORE_Environment=" +Environment="ASPNETCORE_Kestrel__Endpoints__Http=http://localhost:Blogs_" +Environment="ASPNETCORE_ConnectionStrings__YavscConnection=Server=localhost;Port=5432;Database=yavsc;Username=yavsc;Password=4T/X+fOnE;" + +Environment="ASPNETCORE_Smtp__Host=\"mercure.pschneider.f\"" +Environment="ASPNETCORE_Smtp__Port=465" +Environment="ASPNETCORE_Smtp__SenderName=\"Paul Schneider\"" +Environment="ASPNETCORE_Smtp__SenderEmail=\"paul@pschneider.fr\"" +Environment="ASPNETCORE_Smtp__UserName=\"paul\"" +Environment="ASPNETCORE_Smtp__Password=\"j\0Dsn5=t\"" + +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +AmbientCapabilities=CAP_NET_BIND_SERVICE +StandardOutput=syslog +StandardError=syslog +SyslogIdentifier=yavscBlogs + +[Install] +WantedBy=multi-user.target diff --git a/src/PostIt/PostIt.Tests/ActivitiesPageViewModelTests.cs b/src/PostIt/PostIt.Tests/ActivitiesPageViewModelTests.cs new file mode 100644 index 00000000..124777e0 --- /dev/null +++ b/src/PostIt/PostIt.Tests/ActivitiesPageViewModelTests.cs @@ -0,0 +1,113 @@ +using System.Net.Http; +using PostIt.ViewModels; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +public class ActivitiesPageViewModelTests +{ + [Fact] + public async Task ActivityApiClient_uses_business_absolute_paths() + { + var api = new StubActivityApi(); + var client = new ActivityApiClient(api, "https://business.example/api/v1/"); + + await client.GetCatalogAsync("brush", TestContext.Current.CancellationToken); + await client.GetPerformersAsync("brush-pro", TestContext.Current.CancellationToken); + + Assert.Equal("https://business.example/api/v1/activity/catalog?parentCode=brush", api.Paths[0]); + Assert.Equal("https://business.example/api/v1/activity/brush-pro/performers", api.Paths[1]); + } + + [Fact] + public async Task RefreshAsync_loads_first_activity_then_specialization_performers() + { + var api = new StubActivityApi(); + var client = new ActivityApiClient(api, "https://business.example/api/v1/"); + var vm = new ActivitiesPageViewModel(client); + + await vm.RefreshAsync(); + + Assert.Equal("brush", vm.SelectedActivity?.Code); + Assert.Single(vm.Specializations); + Assert.Equal("brush", vm.CurrentActivity?.Code); + Assert.Single(vm.Performers); + Assert.Equal("Alice", vm.Performers[0].UserName); + + await vm.ShowSpecializationAsync(vm.Specializations[0]); + + Assert.Equal("brush-pro", vm.CurrentActivity?.Code); + Assert.Single(vm.Performers); + Assert.Equal("Bob", vm.Performers[0].UserName); + Assert.Contains("brush pro", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); + + await vm.ShowSpecializationAsync(null); + + Assert.Equal("brush", vm.CurrentActivity?.Code); + Assert.Single(vm.Performers); + Assert.Equal("Alice", vm.Performers[0].UserName); + } + + private sealed class StubActivityApi : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public List Paths { get; } = new(); + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + Paths.Add(path); + + if (typeof(T) == typeof(List)) + { + var activities = new List + { + new() + { + Code = "brush", + Name = "Brush", + Description = "Coiffure à domicile", + PerformerCount = 1, + Children = new List + { + new() + { + Code = "brush-pro", + Name = "Brush Pro", + Description = "Spécialisation premium", + ParentCode = "brush", + PerformerCount = 1, + } + } + } + }; + return Task.FromResult((T)(object)activities); + } + + if (typeof(T) == typeof(List)) + { + var performers = path.EndsWith("brush-pro/performers", StringComparison.Ordinal) + ? new List + { + new() { PerformerId = "pro-2", UserName = "Bob", ActivityCode = "brush-pro", ActivityName = "Brush Pro" } + } + : new List + { + new() { PerformerId = "pro-1", UserName = "Alice", ActivityCode = "brush", ActivityName = "Brush" } + }; + + return Task.FromResult((T)(object)performers); + } + + 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 ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/src/PostIt/PostIt.Tests/SignaturePadControlTests.cs b/src/PostIt/PostIt.Tests/SignaturePadControlTests.cs index c03e6850..ff1233e9 100644 --- a/src/PostIt/PostIt.Tests/SignaturePadControlTests.cs +++ b/src/PostIt/PostIt.Tests/SignaturePadControlTests.cs @@ -94,6 +94,26 @@ public class SignaturePadControlTests Assert.NotEqual(first.Strokes, third.Strokes); } + [Fact] + public void PendingStroke_is_exposed_only_while_capturing() + { + var pad = new SignaturePadControl(); + + Assert.Empty(pad.PendingStroke); + + pad.BeginCaptureForTest(); + pad.AppendPointForTest(1_000, 2_000); + pad.AppendPointForTest(3_000, 4_000); + + Assert.Equal(new[] { 1_000, 2_000, 3_000, 4_000 }, pad.PendingStroke); + Assert.Equal(new[] { 1_000, 2_000, 3_000, 4_000 }, pad.Strokes); + + pad.SealStrokeForTest(); + + Assert.Empty(pad.PendingStroke); + Assert.Equal(new[] { 2, 1_000, 2_000, 3_000, 4_000 }, pad.Strokes); + } + [Fact] public void Clear_empties_buffer_and_raises_redraw() { diff --git a/src/PostIt/PostIt/Controls/SignaturePadControl.cs b/src/PostIt/PostIt/Controls/SignaturePadControl.cs index 3a552a05..dee8af36 100644 --- a/src/PostIt/PostIt/Controls/SignaturePadControl.cs +++ b/src/PostIt/PostIt/Controls/SignaturePadControl.cs @@ -212,6 +212,17 @@ public class SignaturePadControl : TemplatedControl _pendingPoints++; } + /// + /// Test hook: mark the control as actively capturing so tests + /// can exercise the live-preview path without synthetic pointer + /// events. + /// + internal void BeginCaptureForTest() + { + _capturing = true; + _pendingPoints = 0; + } + /// /// Test hook: seal the currently-pending stroke with a length /// prefix. Mirrors what does at diff --git a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs index 5f19292a..98b6efb3 100644 --- a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs +++ b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs @@ -23,6 +23,7 @@ public static class ServiceCollectionHelpers var circleClient = new CircleApiClient(api, settings.BlogsApiUrl); var blogAclClient = new BlogAclApiClient(api, settings.BlogsApiUrl); var userSearchClient = new UserSearchClient(api, settings.BlogsApiUrl); + var activityClient = new ActivityApiClient(api, settings.BusinessApiUrl); var userDirectory = new UserDirectory(userSearchClient); // Vues @@ -45,6 +46,7 @@ public static class ServiceCollectionHelpers services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); // ViewModels services.AddSingleton(settings); services.AddSingleton(api); @@ -52,10 +54,12 @@ public static class ServiceCollectionHelpers services.AddSingleton(circleClient); services.AddSingleton(blogAclClient); services.AddSingleton(userSearchClient); + services.AddSingleton(activityClient); services.AddSingleton(userDirectory); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); // Dialogs (modal-light pages): the ViewLocator resolves // them when a caller pushes a PostAclDialogViewModel or diff --git a/src/PostIt/PostIt/ViewLocator.cs b/src/PostIt/PostIt/ViewLocator.cs index 3543a9c9..a81bf6ce 100644 --- a/src/PostIt/PostIt/ViewLocator.cs +++ b/src/PostIt/PostIt/ViewLocator.cs @@ -39,6 +39,7 @@ public class ViewLocator : IDataTemplate MainViewModel => services.GetRequiredService(), Settings => services.GetRequiredService(), HomePageViewModel => services.GetRequiredService(), + ActivitiesPageViewModel => services.GetRequiredService(), SignaturePageViewModel => services.GetRequiredService(), AddCircleMemberDialogViewModel => services.GetRequiredService(), CirclesPageViewModel => services.GetRequiredService(), diff --git a/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs new file mode 100644 index 00000000..57e387c9 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.ViewModels; + +public partial class ActivitiesPageViewModel : ViewModelBase +{ + private readonly ActivityApiClient _client; + private bool _syncingSelection; + + [ObservableProperty] + public partial ObservableCollection Activities { get; set; } = new(); + + [ObservableProperty] + public partial ActivityBrowseItemDto? SelectedActivity { get; set; } + + [ObservableProperty] + public partial ObservableCollection Specializations { get; set; } = new(); + + [ObservableProperty] + public partial ActivityBrowseItemDto? SelectedSpecialization { get; set; } + + [ObservableProperty] + public partial ObservableCollection Performers { get; set; } = new(); + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } = "Choisissez une activité."; + + public ActivityBrowseItemDto? CurrentActivity => SelectedSpecialization ?? SelectedActivity; + public string SelectedActivityLabel => SelectedActivity?.Name ?? "(aucune activité)"; + public string CurrentActivityLabel => CurrentActivity?.Name ?? "(aucune)"; + + public override bool CanNavigateNext + { + get => false; + protected set { _ = value; } + } + + public override bool CanNavigatePrevious + { + get => true; + protected set { _ = value; } + } + + public ActivitiesPageViewModel(ActivityApiClient client) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + } + + partial void OnSelectedActivityChanged(ActivityBrowseItemDto? value) + { + if (_syncingSelection) return; + _ = ShowActivitySafeAsync(value); + } + + partial void OnSelectedSpecializationChanged(ActivityBrowseItemDto? value) + { + if (_syncingSelection) return; + _ = ShowSpecializationSafeAsync(value); + } + + private async Task ShowActivitySafeAsync(ActivityBrowseItemDto? value) + { + try + { + await ShowActivityAsync(value); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + } + + private async Task ShowSpecializationSafeAsync(ActivityBrowseItemDto? value) + { + try + { + await ShowSpecializationAsync(value); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + } + + [RelayCommand] + public async Task RefreshAsync() + { + IsBusy = true; + try + { + var list = await _client.GetCatalogAsync(); + Activities = new ObservableCollection(list ?? new()); + + var first = Activities.FirstOrDefault(); + await ShowActivityAsync(first); + if (first is null) + { + StatusMessage = "Aucune activité disponible."; + } + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + Activities = new ObservableCollection(); + Specializations = new ObservableCollection(); + Performers = new ObservableCollection(); + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + Activities = new ObservableCollection(); + Specializations = new ObservableCollection(); + Performers = new ObservableCollection(); + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + public async Task ShowActivityAsync(ActivityBrowseItemDto? activity) + { + _syncingSelection = true; + try + { + SelectedActivity = activity; + SelectedSpecialization = null; + } + finally + { + _syncingSelection = false; + } + + OnPropertyChanged(nameof(CurrentActivity)); + OnPropertyChanged(nameof(SelectedActivityLabel)); + OnPropertyChanged(nameof(CurrentActivityLabel)); + Specializations = new ObservableCollection(activity?.Children ?? new()); + + if (activity is null) + { + Performers = new ObservableCollection(); + return; + } + + await LoadPerformersAsync(activity); + } + + public async Task ShowSpecializationAsync(ActivityBrowseItemDto? specialization) + { + _syncingSelection = true; + try + { + SelectedSpecialization = specialization; + } + finally + { + _syncingSelection = false; + } + + OnPropertyChanged(nameof(CurrentActivity)); + OnPropertyChanged(nameof(CurrentActivityLabel)); + + if (specialization is null) + { + if (SelectedActivity is not null) + { + await LoadPerformersAsync(SelectedActivity); + } + return; + } + + await LoadPerformersAsync(specialization); + } + + private async Task LoadPerformersAsync(ActivityBrowseItemDto activity) + { + IsBusy = true; + try + { + var list = await _client.GetPerformersAsync(activity.Code); + Performers = new ObservableCollection(list ?? new()); + StatusMessage = $"{activity.Name} · {Performers.Count} prestataire(s)"; + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + Performers = new ObservableCollection(); + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + Performers = new ObservableCollection(); + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } +} diff --git a/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs b/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs index 5d727729..cfd30650 100644 --- a/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs @@ -1,4 +1,9 @@ +using System; +using System.Threading.Tasks; +using Avalonia; using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.DependencyInjection; +using PostIt.Helpers; using PostIt.Services; namespace PostIt.ViewModels; @@ -24,8 +29,25 @@ public class HomePageViewModel : ViewModelBase Settings = settings; SessionStatus = sessionStatus; + OpenActivities = new AsyncRelayCommand(OpenActivitiesAsync); + } - public RelayCommand OpenBlogs { get; set; } = new RelayCommand(() => App.PushMainPageAsync()); + public IAsyncRelayCommand OpenBlogs { get; } = new AsyncRelayCommand(App.PushMainPageAsync); + public IAsyncRelayCommand OpenActivities { get; } + + private async Task OpenActivitiesAsync() + { + var app = (App?)Application.Current; + var vm = app?.ServiceProvider?.GetRequiredService(); + if (app is null || vm is null) + { + throw new InvalidOperationException("Activities page is not available."); + } + + await vm.RefreshAsync(); + await app.PushPageAsync(vm); + } + /// /// Avalonia designer constructor. Builds a self-contained VM /// with a freshly-constructed Settings so the XAML preview can diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index f942249b..0c7a040b 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -26,7 +26,7 @@ public partial class Settings : ViewModelBase public partial string BlogsApiUrl { get; set; } = "https://blogs.pschneider.fr/api/v1/"; [ObservableProperty] - public partial string BusinessApiUrl { get; set; } = "https://business.pschneider.fr/api/v1/"; + public partial string BusinessApiUrl { get; set; } = "https://api.pschneider.fr/api/v1/"; [ObservableProperty] public partial string SearchText { get; set; } = string.Empty; @@ -154,7 +154,10 @@ public partial class Settings : ViewModelBase { "openid", // OIDC: required for the id_token "profile", // OIDC: standard profile claims - "offline_access" // OIDC: required to receive a refresh_token + "offline_access", // OIDC: required to receive a refresh_token + "blogs", + "api" + }; /// @@ -297,8 +300,15 @@ public partial class Settings : ViewModelBase // → our overridden dispatcher-safe marshaller below. else lock (_mutationGate) { + var legacyApiUrl = TryReadLegacyApiUrl(json); this.Authentication = settings.Authentication; this.DarkMode = settings.DarkMode; + this.BlogsApiUrl = !string.IsNullOrWhiteSpace(settings.BlogsApiUrl) + ? settings.BlogsApiUrl + : legacyApiUrl ?? this.BlogsApiUrl; + this.BusinessApiUrl = !string.IsNullOrWhiteSpace(settings.BusinessApiUrl) + ? settings.BusinessApiUrl + : this.BusinessApiUrl; this.SearchText = settings.SearchText ?? string.Empty; if (!(settings.Authentication is null)) { @@ -343,6 +353,26 @@ public partial class Settings : ViewModelBase } } + private static string? TryReadLegacyApiUrl(string json) + { + try + { + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.TryGetProperty("ApiUrl", out var apiUrl) + && apiUrl.ValueKind == JsonValueKind.String) + { + return apiUrl.GetString(); + } + } + catch + { + // Ignore legacy payload parse errors: normal deserialization + // already reports actionable diagnostics to the caller. + } + + return null; + } + private void UseDefaultSettings() { this.Authentication = new AuthenticationSettings @@ -353,6 +383,8 @@ public partial class Settings : ViewModelBase Scopes = AuthenticationSettings.DefaultScopes }; this.DarkMode = false; + this.BlogsApiUrl = "https://blogs.pschneider.fr/api/v1/"; + this.BusinessApiUrl = "https://api.pschneider.fr/api/v1/"; this.SearchText = string.Empty; } diff --git a/src/PostIt/PostIt/Views/ActivitiesPage.axaml b/src/PostIt/PostIt/Views/ActivitiesPage.axaml new file mode 100644 index 00000000..03248a0e --- /dev/null +++ b/src/PostIt/PostIt/Views/ActivitiesPage.axaml @@ -0,0 +1,79 @@ + + + + +public sealed class HairPrestationDto +{ + public long Id { get; set; } + public string Title { get; set; } = string.Empty; + public string Details { get; set; } = string.Empty; +} \ No newline at end of file diff --git a/src/Yavsc.Api.Client/BillingApiClient.cs b/src/Yavsc.Api.Client/BillingApiClient.cs index b65fa65c..ad9945df 100644 --- a/src/Yavsc.Api.Client/BillingApiClient.cs +++ b/src/Yavsc.Api.Client/BillingApiClient.cs @@ -1,7 +1,9 @@ using System; +using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Yavsc.Models.Haircut; namespace Yavsc.Api.Client; @@ -38,5 +40,34 @@ public sealed class BillingApiClient ct: ct); } + public Task> GetHairPrestationsAsync(string billingCode, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(billingCode)) + throw new ArgumentException("Billing code is required.", nameof(billingCode)); + + return _api.CallAsync>( + HttpMethod.Get, + Absolute($"{PathPrefix}/{Uri.EscapeDataString(billingCode)}/prestations"), + ct: ct); + } + + public async Task> GetQuerySummariesAsync(string billingCode, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(billingCode)) + throw new ArgumentException("Billing code is required.", nameof(billingCode)); + + var items = await _api.CallAsync>( + HttpMethod.Get, + Absolute($"{PathPrefix}/{Uri.EscapeDataString(billingCode)}"), + ct: ct) ?? new List(); + + foreach (var item in items) + { + item.BillingCode = billingCode; + } + + return items; + } + private string Absolute(string relativePath) => new Uri(_baseAddress, relativePath).ToString(); } \ No newline at end of file diff --git a/src/Yavsc.Api.Client/Dtos/BillingQuerySummaryDto.cs b/src/Yavsc.Api.Client/Dtos/BillingQuerySummaryDto.cs new file mode 100644 index 00000000..0102b691 --- /dev/null +++ b/src/Yavsc.Api.Client/Dtos/BillingQuerySummaryDto.cs @@ -0,0 +1,23 @@ +using System; +using Yavsc; + +namespace Yavsc.Api.Client; + +/// +/// Lightweight billing-query projection consumed by PostIt list views. +/// Extra JSON fields from concrete query types are ignored. +/// +public sealed class BillingQuerySummaryDto +{ + 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; + public DateTime? EventDate { get; set; } + public string Reason { get; set; } = string.Empty; + public string AdditionalInfo { get; set; } = string.Empty; + public decimal? Provisional { get; set; } +} \ No newline at end of file diff --git a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs index ef89f563..ca4ae70f 100644 --- a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs +++ b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using Yavsc.Controllers; using Yavsc.Models; +using Yavsc.Models.Haircut; using Yavsc.Models.Relationship; using Yavsc.Models.Workflow; using Yavsc.Tests.Shared; @@ -212,6 +213,114 @@ public sealed class ApiWebServerFixture : WebHostFixture db.SaveChanges(); } + public void ResetAndSeedHaircutGraph() + { + ResetAndSeedActivityGraph(); + + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var location = db.Locations.Single(l => l.Address == "1 rue du Test"); + + if (!db.Activities.Any(a => a.Code == "brush")) + { + db.Activities.Add(new Activity + { + Code = "brush", + Name = "Brush", + Hidden = false, + DateCreated = DateTime.UtcNow, + DateModified = DateTime.UtcNow, + }); + } + + if (!db.Activities.Any(a => a.Code == "mbrush")) + { + db.Activities.Add(new Activity + { + Code = "mbrush", + Name = "MBrush", + Hidden = false, + DateCreated = DateTime.UtcNow, + DateModified = DateTime.UtcNow, + }); + } + + if (!db.BrusherProfile.Any(p => p.UserId == "alice")) + { + db.BrusherProfile.Add(new BrusherProfile + { + UserId = "alice", + ActionDistance = 25, + WomenLongCutPrice = 50m, + WomenHalfCutPrice = 40m, + WomenShortCutPrice = 30m, + ManCutPrice = 20m, + KidCutPrice = 15m, + ShampooPrice = 5m, + }); + } + + var prestation1 = new HairPrestation + { + Gender = HairCutGenders.Women, + Length = HairLength.HalfLong, + Cut = true, + Shampoo = true, + Dressing = HairDressings.Brushing, + Tech = HairTechnos.NoTech, + Cares = false, + Taints = new List(), + }; + var prestation2 = new HairPrestation + { + Gender = HairCutGenders.Man, + Length = HairLength.Short, + Cut = true, + Shampoo = false, + Dressing = HairDressings.Brushing, + Tech = HairTechnos.NoTech, + Cares = false, + Taints = new List(), + }; + + db.HairPrestation.AddRange(prestation1, prestation2); + db.SaveChanges(); + + db.HairCutQueries.Add(new HairCutQuery + { + ActivityCode = "brush", + ClientId = "alice", + PerformerId = "alice", + Consent = true, + EventDate = DateTime.UtcNow.AddDays(3), + Location = location, + PrestationId = prestation1.Id, + Prestation = prestation1, + AdditionalInfo = "Coupe test", + Status = Yavsc.QueryStatus.Inserted, + Description = "Haircut seed", + }); + + db.HairMultiCutQueries.Add(new HairMultiCutQuery + { + ActivityCode = "mbrush", + ClientId = "alice", + PerformerId = "alice", + Consent = true, + EventDate = DateTime.UtcNow.AddDays(4), + Location = location, + Prestations = new List + { + new() { PrestationId = prestation1.Id, Prestation = prestation1 }, + new() { PrestationId = prestation2.Id, Prestation = prestation2 }, + }, + Status = Yavsc.QueryStatus.Inserted, + }); + + db.SaveChanges(); + } + public override void Dispose() { try diff --git a/src/Yavsc.Api.Test/HairCutQueryApiControllerTests.cs b/src/Yavsc.Api.Test/HairCutQueryApiControllerTests.cs new file mode 100644 index 00000000..b4b7e3e4 --- /dev/null +++ b/src/Yavsc.Api.Test/HairCutQueryApiControllerTests.cs @@ -0,0 +1,120 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.EntityFrameworkCore; +using Yavsc.Api.Test.Fixtures; +using Yavsc.Models; +using Yavsc.Models.Haircut; +using Yavsc.Models.Relationship; +using Yavsc.Tests.Shared; + +namespace Yavsc.Api.Test; + +[Collection("Yavsc Api")] +public sealed class HairCutQueryApiControllerTests : IClassFixture +{ + private readonly ApiWebServerFixture _fixture; + + public HairCutQueryApiControllerTests(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 Billing_brush_route_supports_crud() + { + _fixture.ResetAndSeedHaircutGraph(); + using var http = NewClient(); + + var prestationId = await GetPrestationIdAsync(); + + var createPayload = new HairCutQuery + { + ActivityCode = "brush", + PerformerId = "alice", + Consent = true, + EventDate = DateTime.UtcNow.AddDays(5), + Location = new Location + { + Address = "2 rue de la Coupe", + Latitude = 48.8570, + Longitude = 2.3525, + }, + PrestationId = prestationId, + AdditionalInfo = "Brushing test", + Status = QueryStatus.Inserted, + Description = "Haircut create", + }; + + var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Brush", createPayload, TestContext.Current.CancellationToken); + if (createResponse.StatusCode != HttpStatusCode.Created) + { + var body = await createResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + Assert.Fail($"Unexpected status {createResponse.StatusCode}: {body}"); + } + + var created = await createResponse.Content.ReadFromJsonAsync(TestContext.Current.CancellationToken); + Assert.NotNull(created); + Assert.NotEqual(0, created!.Id); + Assert.Equal("alice", created.ClientId); + + var getResponse = await http.GetAsync($"/api/v1/billing/Brush/{created.Id}", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); + + var fetched = await getResponse.Content.ReadFromJsonAsync(TestContext.Current.CancellationToken); + Assert.NotNull(fetched); + Assert.Equal(created.Id, fetched!.Id); + Assert.Equal("Brushing test", fetched.AdditionalInfo); + + fetched.AdditionalInfo = "Brushing modifié"; + var putResponse = await http.PutAsJsonAsync($"/api/v1/billing/Brush/{fetched.Id}", fetched, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.NoContent, putResponse.StatusCode); + + var deleteResponse = await http.DeleteAsync($"/api/v1/billing/Brush/{fetched.Id}", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode); + + var missingResponse = await http.GetAsync($"/api/v1/billing/Brush/{fetched.Id}", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + } + + [Fact] + public async Task Billing_brush_route_exposes_prestation_catalog() + { + _fixture.ResetAndSeedHaircutGraph(); + using var http = NewClient(); + + var response = await http.GetAsync("/api/v1/billing/Brush/prestations", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var catalog = await response.Content.ReadFromJsonAsync>(TestContext.Current.CancellationToken); + Assert.NotNull(catalog); + Assert.NotEmpty(catalog!); + Assert.All(catalog!, item => Assert.False(string.IsNullOrWhiteSpace(item.Title))); + Assert.Contains(catalog!, item => item.Title == "Femme · Cheveux mi-longs" + && item.Details == "Coupe · Brushing · Aucune technique spécifique · Shampoing · Sans soins"); + } + + private async Task GetPrestationIdAsync() + { + using var scope = _fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.HairPrestation.Select(p => p.Id).FirstAsync(TestContext.Current.CancellationToken); + } +} \ No newline at end of file diff --git a/src/Yavsc.Api.Test/HairMultiCutQueryApiControllerTests.cs b/src/Yavsc.Api.Test/HairMultiCutQueryApiControllerTests.cs new file mode 100644 index 00000000..8d940b8b --- /dev/null +++ b/src/Yavsc.Api.Test/HairMultiCutQueryApiControllerTests.cs @@ -0,0 +1,123 @@ +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.Models; +using Yavsc.Models.Haircut; +using Yavsc.Models.Relationship; +using Yavsc.Tests.Shared; + +namespace Yavsc.Api.Test; + +[Collection("Yavsc Api")] +public sealed class HairMultiCutQueryApiControllerTests : IClassFixture +{ + private readonly ApiWebServerFixture _fixture; + + public HairMultiCutQueryApiControllerTests(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 Billing_mbrush_route_supports_crud() + { + _fixture.ResetAndSeedHaircutGraph(); + using var http = NewClient(); + + var prestationIds = await GetPrestationIdsAsync(); + + var createPayload = new HairMultiCutQuery + { + ActivityCode = "mbrush", + PerformerId = "alice", + Consent = true, + EventDate = DateTime.UtcNow.AddDays(6), + Location = new Location + { + Address = "3 rue du Groupe", + Latitude = 48.8580, + Longitude = 2.3530, + }, + Prestations = prestationIds.Select(id => new HairPrestationCollectionItem { PrestationId = id }).ToList(), + Status = QueryStatus.Inserted, + }; + + var createResponse = await http.PostAsJsonAsync("/api/v1/billing/MBrush", createPayload, TestContext.Current.CancellationToken); + if (createResponse.StatusCode != HttpStatusCode.Created) + { + var body = await createResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + Assert.Fail($"Unexpected status {createResponse.StatusCode}: {body}"); + } + + var created = await createResponse.Content.ReadFromJsonAsync(TestContext.Current.CancellationToken); + Assert.NotNull(created); + Assert.NotEqual(0, created!.Id); + Assert.Equal("alice", created.ClientId); + Assert.Equal(2, created.Prestations.Count); + + var getResponse = await http.GetAsync($"/api/v1/billing/MBrush/{created.Id}", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); + + var fetched = await getResponse.Content.ReadFromJsonAsync(TestContext.Current.CancellationToken); + Assert.NotNull(fetched); + Assert.Equal(created.Id, fetched!.Id); + Assert.Equal(2, fetched.Prestations.Count); + + fetched.Status = QueryStatus.Accepted; + var putResponse = await http.PutAsJsonAsync($"/api/v1/billing/MBrush/{fetched.Id}", fetched, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.NoContent, putResponse.StatusCode); + + var deleteResponse = await http.DeleteAsync($"/api/v1/billing/MBrush/{fetched.Id}", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode); + + var missingResponse = await http.GetAsync($"/api/v1/billing/MBrush/{fetched.Id}", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + } + + [Fact] + public async Task Billing_mbrush_route_exposes_prestation_catalog() + { + _fixture.ResetAndSeedHaircutGraph(); + using var http = NewClient(); + + var response = await http.GetAsync("/api/v1/billing/MBrush/prestations", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var catalog = await response.Content.ReadFromJsonAsync>(TestContext.Current.CancellationToken); + Assert.NotNull(catalog); + Assert.NotEmpty(catalog!); + Assert.All(catalog!, item => Assert.False(string.IsNullOrWhiteSpace(item.Details))); + Assert.Contains(catalog!, item => item.Title == "Femme · Cheveux mi-longs" + && item.Details == "Coupe · Brushing · Aucune technique spécifique · Shampoing · Sans soins"); + } + + private async Task> GetPrestationIdsAsync() + { + using var scope = _fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.HairPrestation + .OrderBy(p => p.Id) + .Select(p => p.Id) + .Take(2) + .ToListAsync(TestContext.Current.CancellationToken); + } +} \ No newline at end of file diff --git a/src/Yavsc.Api/Controllers/Business/HairCutQueryApiController.cs b/src/Yavsc.Api/Controllers/Business/HairCutQueryApiController.cs new file mode 100644 index 00000000..6c7c1ba6 --- /dev/null +++ b/src/Yavsc.Api/Controllers/Business/HairCutQueryApiController.cs @@ -0,0 +1,234 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Yavsc.Models; +using Yavsc.Models.Billing; +using Yavsc.Models.Haircut; +using Yavsc.Models.Relationship; +using Yavsc.Server.Helpers; + +namespace Yavsc.Controllers; + +[Authorize] +[Produces("application/json")] +[Route(Constants.APIPrefix + "/billing/" + BillingCodes.Brush)] +public class HairCutQueryApiController : Controller +{ + private readonly ApplicationDbContext _context; + + public HairCutQueryApiController(ApplicationDbContext context) + { + _context = context; + } + + [HttpGet] + public async Task GetQueries(CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + + var queries = await _context.HairCutQueries + .AsNoTracking() + .Include(q => q.Prestation) + .Include(q => q.Location) + .Include(q => q.Client) + .Include(q => q.PerformerProfile) + .Where(q => q.ClientId == uid || q.PerformerId == uid) + .OrderByDescending(q => q.Id) + .ToListAsync(cancellationToken); + + return Ok(queries); + } + + [HttpGet("prestations")] + public async Task GetPrestations(CancellationToken cancellationToken) + { + var prestations = await _context.HairPrestation + .AsNoTracking() + .OrderBy(p => p.Gender) + .ThenBy(p => p.Length) + .ThenBy(p => p.Tech) + .Select(p => ToDto(p)) + .ToListAsync(cancellationToken); + + return Ok(prestations); + } + + [HttpGet("{id}", Name = "GetBillingHairCutQuery")] + public async Task GetQuery([FromRoute] long id, CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + + var query = await _context.HairCutQueries + .Include(q => q.Prestation) + .Include(q => q.Location) + .Include(q => q.Client) + .Include(q => q.PerformerProfile) + .SingleOrDefaultAsync(q => q.Id == id, cancellationToken); + + if (query is null) + { + return NotFound(); + } + + if (query.ClientId != uid && query.PerformerId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + return Forbid(); + } + + return Ok(query); + } + + [HttpPost] + public async Task PostQuery([FromBody] HairCutQuery query, CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + if (string.IsNullOrWhiteSpace(query.ClientId)) + { + query.ClientId = uid; + } + + ModelState.Remove("ClientId"); + ModelState.Remove("Prestation"); + + if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + ModelState.AddModelError("ClientId", "You can only create your own HairCutQuery"); + return BadRequest(ModelState); + } + + query.Prestation = await _context.HairPrestation + .SingleOrDefaultAsync(p => p.Id == query.PrestationId, cancellationToken); + if (query.Prestation is null) + { + ModelState.AddModelError("PrestationId", "Unknown hair prestation."); + return BadRequest(ModelState); + } + + if (!ModelState.IsValid) + { + return BadRequest(ModelState); + } + + query.Location = await ResolveLocationAsync(query.Location, cancellationToken); + + _context.HairCutQueries.Add(query); + + try + { + await _context.SaveChangesAsync(User.GetUserId(), cancellationToken); + } + catch (DbUpdateException) + { + if (QueryExists(query.Id)) + { + return Conflict(); + } + + throw; + } + + return CreatedAtRoute("GetBillingHairCutQuery", new { id = query.Id }, query); + } + + [HttpPut("{id}")] + public async Task PutQuery([FromRoute] long id, [FromBody] HairCutQuery query, CancellationToken cancellationToken) + { + var existing = await _context.HairCutQueries + .Include(q => q.Location) + .SingleOrDefaultAsync(q => q.Id == id, cancellationToken); + + if (existing is null) + { + return NotFound(); + } + + var uid = User.GetUserId(); + if (existing.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + return Forbid(); + } + + var prestation = await _context.HairPrestation + .SingleOrDefaultAsync(p => p.Id == query.PrestationId, cancellationToken); + if (prestation is null) + { + ModelState.AddModelError("PrestationId", "Unknown hair prestation."); + return BadRequest(ModelState); + } + + existing.ActivityCode = query.ActivityCode; + existing.PerformerId = query.PerformerId; + existing.Consent = query.Consent; + existing.EventDate = query.EventDate; + existing.AdditionalInfo = query.AdditionalInfo; + existing.Status = query.Status; + existing.Provisional = query.Provisional; + existing.PrestationId = prestation.Id; + existing.Prestation = prestation; + existing.Location = await ResolveLocationAsync(query.Location, cancellationToken); + + await _context.SaveChangesAsync(User.GetUserId(), cancellationToken); + return NoContent(); + } + + [HttpDelete("{id}")] + public async Task DeleteQuery([FromRoute] long id, CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + + var query = await _context.HairCutQueries + .SingleOrDefaultAsync(q => q.Id == id, cancellationToken); + + if (query is null) + { + return NotFound(); + } + + if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + return Forbid(); + } + + _context.HairCutQueries.Remove(query); + await _context.SaveChangesAsync(User.GetUserId(), cancellationToken); + + return Ok(query); + } + + private async Task ResolveLocationAsync(Location candidate, CancellationToken cancellationToken) + { + if (candidate is null) + { + return null; + } + + var existingLocation = await _context.Locations.FirstOrDefaultAsync( + x => x.Address == candidate.Address + && x.Longitude == candidate.Longitude + && x.Latitude == candidate.Latitude, + cancellationToken); + + if (existingLocation is not null) + { + return existingLocation; + } + + _context.Attach(candidate); + return candidate; + } + + private bool QueryExists(long id) + { + return _context.HairCutQueries.Any(e => e.Id == id); + } + + private static HairPrestationDto ToDto(HairPrestation prestation) + { + return new HairPrestationDto + { + Id = prestation.Id, + Title = prestation.GetDisplayTitle(), + Details = prestation.GetDisplayDetails(), + }; + } +} \ No newline at end of file diff --git a/src/Yavsc.Api/Controllers/Business/HairMultiCutQueryApiController.cs b/src/Yavsc.Api/Controllers/Business/HairMultiCutQueryApiController.cs new file mode 100644 index 00000000..f850b3f4 --- /dev/null +++ b/src/Yavsc.Api/Controllers/Business/HairMultiCutQueryApiController.cs @@ -0,0 +1,286 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Yavsc.Models; +using Yavsc.Models.Billing; +using Yavsc.Models.Haircut; +using Yavsc.Models.Relationship; +using Yavsc.Server.Helpers; + +namespace Yavsc.Controllers; + +[Authorize] +[Produces("application/json")] +[Route(Constants.APIPrefix + "/billing/" + BillingCodes.MBrush)] +public class HairMultiCutQueryApiController : Controller +{ + private readonly ApplicationDbContext _context; + + public HairMultiCutQueryApiController(ApplicationDbContext context) + { + _context = context; + } + + [HttpGet] + public async Task GetQueries(CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + + var queries = await _context.HairMultiCutQueries + .AsNoTracking() + .Include(q => q.Prestations) + .ThenInclude(p => p.Prestation) + .Include(q => q.Location) + .Include(q => q.Client) + .Include(q => q.PerformerProfile) + .Where(q => q.ClientId == uid || q.PerformerId == uid) + .OrderByDescending(q => q.Id) + .ToListAsync(cancellationToken); + + return Ok(queries.Select(SanitizeForResponse).ToList()); + } + + [HttpGet("prestations")] + public async Task GetPrestations(CancellationToken cancellationToken) + { + var prestations = await _context.HairPrestation + .AsNoTracking() + .OrderBy(p => p.Gender) + .ThenBy(p => p.Length) + .ThenBy(p => p.Tech) + .Select(p => new HairPrestationDto + { + Id = p.Id, + Title = p.GetDisplayTitle(), + Details = p.GetDisplayDetails() + }) + .ToListAsync(cancellationToken); + + return Ok(prestations); + } + + [HttpGet("{id}", Name = "GetBillingHairMultiCutQuery")] + public async Task GetQuery([FromRoute] long id, CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + + var query = await _context.HairMultiCutQueries + .Include(q => q.Prestations) + .ThenInclude(p => p.Prestation) + .Include(q => q.Location) + .Include(q => q.Client) + .Include(q => q.PerformerProfile) + .SingleOrDefaultAsync(q => q.Id == id, cancellationToken); + + if (query is null) + { + return NotFound(); + } + + if (query.ClientId != uid && query.PerformerId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + return Forbid(); + } + + return Ok(SanitizeForResponse(query)); + } + + [HttpPost] + public async Task PostQuery([FromBody] HairMultiCutQuery query, CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + if (string.IsNullOrWhiteSpace(query.ClientId)) + { + query.ClientId = uid; + } + + ModelState.Remove("ClientId"); + + if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + ModelState.AddModelError("ClientId", "You can only create your own HairMultiCutQuery"); + return BadRequest(ModelState); + } + + if (query.Prestations is null || query.Prestations.Count == 0) + { + ModelState.AddModelError("Prestations", "At least one hair prestation is required."); + return BadRequest(ModelState); + } + + var prestationItems = await ResolvePrestationsAsync(query.Prestations, cancellationToken); + if (prestationItems is null) + { + ModelState.AddModelError("Prestations", "One or more hair prestations are unknown."); + return BadRequest(ModelState); + } + + if (!ModelState.IsValid) + { + return BadRequest(ModelState); + } + + query.Prestations = prestationItems; + query.Location = await ResolveLocationAsync(query.Location, cancellationToken); + _context.HairMultiCutQueries.Add(query); + + try + { + await _context.SaveChangesAsync(User.GetUserId(), cancellationToken); + } + catch (DbUpdateException) + { + if (QueryExists(query.Id)) + { + return Conflict(); + } + + throw; + } + + return CreatedAtRoute("GetBillingHairMultiCutQuery", new { id = query.Id }, SanitizeForResponse(query)); + } + + [HttpPut("{id}")] + public async Task PutQuery([FromRoute] long id, [FromBody] HairMultiCutQuery query, CancellationToken cancellationToken) + { + var existing = await _context.HairMultiCutQueries + .Include(q => q.Prestations) + .SingleOrDefaultAsync(q => q.Id == id, cancellationToken); + + if (existing is null) + { + return NotFound(); + } + + var uid = User.GetUserId(); + if (existing.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + return Forbid(); + } + + if (query.Prestations is null || query.Prestations.Count == 0) + { + ModelState.AddModelError("Prestations", "At least one hair prestation is required."); + return BadRequest(ModelState); + } + + var prestationItems = await ResolvePrestationsAsync(query.Prestations, cancellationToken); + if (prestationItems is null) + { + ModelState.AddModelError("Prestations", "One or more hair prestations are unknown."); + return BadRequest(ModelState); + } + + _context.RemoveRange(existing.Prestations); + existing.ActivityCode = query.ActivityCode; + existing.PerformerId = query.PerformerId; + existing.Consent = query.Consent; + existing.EventDate = query.EventDate; + existing.Status = query.Status; + existing.Provisional = query.Provisional; + existing.Prestations = prestationItems; + existing.Location = await ResolveLocationAsync(query.Location, cancellationToken); + + await _context.SaveChangesAsync(User.GetUserId(), cancellationToken); + return NoContent(); + } + + [HttpDelete("{id}")] + public async Task DeleteQuery([FromRoute] long id, CancellationToken cancellationToken) + { + var uid = User.GetUserId(); + + var query = await _context.HairMultiCutQueries + .Include(q => q.Prestations) + .SingleOrDefaultAsync(q => q.Id == id, cancellationToken); + + if (query is null) + { + return NotFound(); + } + + if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) + { + return Forbid(); + } + + _context.RemoveRange(query.Prestations); + _context.HairMultiCutQueries.Remove(query); + await _context.SaveChangesAsync(User.GetUserId(), cancellationToken); + + return Ok(SanitizeForResponse(query)); + } + + private async Task> ResolvePrestationsAsync( + IEnumerable requestedItems, + CancellationToken cancellationToken) + { + var ids = requestedItems + .Select(x => x.PrestationId) + .Where(x => x > 0) + .ToArray(); + + if (ids.Length == 0) + { + return null; + } + + var prestations = await _context.HairPrestation + .Where(p => ids.Contains(p.Id)) + .ToDictionaryAsync(p => p.Id, cancellationToken); + + if (prestations.Count != ids.Distinct().Count()) + { + return null; + } + + return requestedItems + .Select(item => new HairPrestationCollectionItem + { + PrestationId = item.PrestationId, + Prestation = prestations[item.PrestationId], + }) + .ToList(); + } + + private async Task ResolveLocationAsync(Location candidate, CancellationToken cancellationToken) + { + if (candidate is null) + { + return null; + } + + var existingLocation = await _context.Locations.FirstOrDefaultAsync( + x => x.Address == candidate.Address + && x.Longitude == candidate.Longitude + && x.Latitude == candidate.Latitude, + cancellationToken); + + if (existingLocation is not null) + { + return existingLocation; + } + + _context.Attach(candidate); + return candidate; + } + + private bool QueryExists(long id) + { + return _context.HairMultiCutQueries.Any(e => e.Id == id); + } + + private static HairMultiCutQuery SanitizeForResponse(HairMultiCutQuery query) + { + if (query.Prestations is not null) + { + foreach (var item in query.Prestations) + { + item.Query = null; + } + } + + return query; + } +} \ No newline at end of file diff --git a/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs b/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs index 9414d31e..fcfac2b2 100644 --- a/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs +++ b/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs @@ -1,4 +1,3 @@ -using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -24,7 +23,7 @@ public class RdvQueryApiController : Controller [HttpGet] public async Task GetQueries(CancellationToken cancellationToken) { - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + var uid = User.GetUserId(); var queries = await _context.RdvQueries .AsNoTracking() @@ -41,7 +40,7 @@ public class RdvQueryApiController : Controller [HttpGet("{id}", Name = "GetRdvQuery")] public async Task GetQuery([FromRoute] long id, CancellationToken cancellationToken) { - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + var uid = User.GetUserId(); var query = await _context.RdvQueries .Include(q => q.Location) @@ -65,13 +64,13 @@ public class RdvQueryApiController : Controller [HttpPost] public async Task PostQuery([FromBody] RdvQuery query, CancellationToken cancellationToken) { - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + var uid = User.GetUserId(); if (string.IsNullOrWhiteSpace(query.ClientId)) { query.ClientId = uid; } - ModelState.MarkFieldSkipped("ClientId"); + ModelState.Remove("ClientId"); if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) { @@ -134,7 +133,7 @@ public class RdvQueryApiController : Controller return BadRequest(); } - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + var uid = User.GetUserId(); if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) { return Forbid(); @@ -162,7 +161,7 @@ public class RdvQueryApiController : Controller [HttpDelete("{id}")] public async Task DeleteQuery([FromRoute] long id, CancellationToken cancellationToken) { - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + var uid = User.GetUserId(); var query = await _context.RdvQueries .SingleOrDefaultAsync(q => q.Id == id, cancellationToken); diff --git a/src/Yavsc.Server/Models/HairCut/HairDressings.cs b/src/Yavsc.Server/Models/HairCut/HairDressings.cs index 02fa17ed..20fd2080 100644 --- a/src/Yavsc.Server/Models/HairCut/HairDressings.cs +++ b/src/Yavsc.Server/Models/HairCut/HairDressings.cs @@ -4,8 +4,10 @@ namespace Yavsc.Models.Haircut { public enum HairDressings { + [Display(Name="Coiffage")] Coiffage, + [Display(Name="Brushing")] Brushing, [Display(Name="Mise en plis")] diff --git a/src/Yavsc.Server/Models/HairCut/HairLength.cs b/src/Yavsc.Server/Models/HairCut/HairLength.cs index b763096f..725d3223 100644 --- a/src/Yavsc.Server/Models/HairCut/HairLength.cs +++ b/src/Yavsc.Server/Models/HairCut/HairLength.cs @@ -1,12 +1,17 @@ +using System.ComponentModel.DataAnnotations; namespace Yavsc.Models.Haircut { public enum HairLength : int { + [Display(Name="Cheveux mi-longs")] HalfLong=0, + + [Display(Name="Cheveux courts")] Short=1, + [Display(Name="Cheveux longs")] Long=2 } } diff --git a/src/Yavsc.Server/Models/HairCut/HairPrestation.cs b/src/Yavsc.Server/Models/HairCut/HairPrestation.cs index a14053b3..6153f648 100644 --- a/src/Yavsc.Server/Models/HairCut/HairPrestation.cs +++ b/src/Yavsc.Server/Models/HairCut/HairPrestation.cs @@ -1,5 +1,6 @@ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Reflection; using Newtonsoft.Json; namespace Yavsc.Models.Haircut @@ -40,6 +41,41 @@ namespace Yavsc.Models.Haircut [Display(Name="Soins")] public bool Cares { get; set; } + public string GetDisplayTitle() + { + return $"{GetEnumDisplayName(Gender)} · {GetEnumDisplayName(Length)}"; + } + + public string GetDisplayDetails() + { + return string.Join(" · ", new[] + { + FormatFlag(nameof(Cut), Cut), + GetEnumDisplayName(Dressing), + GetEnumDisplayName(Tech), + FormatFlag(nameof(Shampoo), Shampoo), + FormatFlag(nameof(Cares), Cares), + }); + } + + private static string FormatFlag(string propertyName, bool enabled) + { + var label = GetPropertyDisplayName(propertyName); + return enabled ? label : $"Sans {label.ToLowerInvariant()}"; + } + + private static string GetPropertyDisplayName(string propertyName) + { + var property = typeof(HairPrestation).GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); + return property?.GetCustomAttribute()?.GetName() ?? propertyName; + } + + private static string GetEnumDisplayName(TEnum value) where TEnum : struct, Enum + { + var member = typeof(TEnum).GetMember(value.ToString()).FirstOrDefault(); + return member?.GetCustomAttribute()?.GetName() ?? value.ToString(); + } + } public class HairTaintInstance { diff --git a/src/Yavsc.Server/Models/HairCut/HairTechnos.cs b/src/Yavsc.Server/Models/HairCut/HairTechnos.cs index 51a99818..52ef0c4a 100644 --- a/src/Yavsc.Server/Models/HairCut/HairTechnos.cs +++ b/src/Yavsc.Server/Models/HairCut/HairTechnos.cs @@ -11,12 +11,14 @@ namespace Yavsc.Models.Haircut [Display(Name="Couleur")] Color, - [Display(Name="Permantante")] + [Display(Name="Permanente")] Permanent, [Display(Name="Défrisage")] Defris, [Display(Name="Mêches")] Mech, + + [Display(Name="Balayage")] Balayage } } From f4271b4052016ae18f888f0945e72f527b65ab82 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Mon, 31 Aug 2026 04:27:39 +0100 Subject: [PATCH 12/31] display my queries --- CHANGELOG.md | 7 + .../BillingCommandPageViewModelTests.cs | 57 ++++ .../BillingQueriesPageViewModelTests.cs | 50 +++- .../ViewModels/BillingCommandPageViewModel.cs | 171 +++++++++-- .../ViewModels/BillingQueriesPageViewModel.cs | 89 +++++- .../ViewModels/CommandFormsPageViewModel.cs | 30 +- .../PostIt/Views/BillingCommandPage.axaml | 2 +- .../PostIt/Views/BillingQueriesPage.axaml | 5 +- .../PostIt/Views/CommandFormsPage.axaml | 7 +- src/Yavsc.Api.Client/BillingApiClient.cs | 281 ++++++++++++++++++ .../Dtos/BillingQueryDetailsDto.cs | 35 +++ 11 files changed, 691 insertions(+), 43 deletions(-) create mode 100644 src/Yavsc.Api.Client/Dtos/BillingQueryDetailsDto.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a2efb4a..e5f285ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,17 @@ ### Added +* [PostIt] Une page d'historique des commandes billing permet maintenant d'ouvrir une commande existante. +* [PostIt] Une vue "Demandes en cours" en lecture seule est disponible pour le performer, filtrée sur les statuts actifs (Inserted, Accepted, InProgress). + ### Changed +* [PostIt] La page détail billing se préremplit depuis une commande existante (Rdv, Brush, MBrush) et passe en mode mise à jour. + ### Fixed +* [PostIt] Le flux historique n'est plus limité à une simple liste: l'action d'ouverture charge la commande cible puis navigue vers la page détail. + ## [1.0.8-rc9] - unstable ### Added diff --git a/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs b/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs index 4aa69978..eef3fe21 100644 --- a/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs @@ -132,15 +132,71 @@ public class BillingCommandPageViewModelTests Assert.Equal(22, prestations[1].GetProperty("PrestationId").GetInt32()); } + [Fact] + public async Task InitializeAsync_with_existing_brush_query_prefills_and_submit_updates_query() + { + var api = new RecordingApi + { + HairPrestations = new List + { + new() { Id = 30, Title = "Femme · Cheveux longs", Details = "Coupe · Brushing" }, + new() { Id = 31, Title = "Homme · Cheveux courts", Details = "Coupe" }, + } + }; + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new BillingCommandPageViewModel( + new ActivityBrowseItemDto { Code = "brush", Name = "Brush" }, + new ActivityUserDisplayItem { PerformerId = "perf-2", UserName = "Bob" }, + new CommandFormSummaryDto { Id = 13, ActionName = "Brush", Title = "Coupe" }, + client); + + await vm.InitializeAsync(new BillingQueryDetailsDto + { + Id = 77, + BillingCode = "Brush", + ActivityCode = "brush", + PerformerId = "perf-2", + ClientId = "cli-1", + EventDate = new DateTime(2026, 9, 2, 14, 30, 0, DateTimeKind.Utc), + Consent = true, + Status = QueryStatus.Accepted, + PrestationId = 30, + AdditionalInfo = "Ancienne note", + Location = new BillingLocationDto + { + Address = "1 rue du Test", + Latitude = 48.8566, + Longitude = 2.3522, + } + }); + + vm.SelectedPrestation = vm.AvailablePrestations[1]; + vm.AdditionalInfo = "Note mise à jour"; + await vm.SubmitCommand.ExecuteAsync(null); + + Assert.Equal(HttpMethod.Put, api.LastMethod); + Assert.Equal("https://business.example/api/v1/billing/Brush/77", api.LastPath); + Assert.True(vm.IsEditingExisting); + Assert.Equal("Mettre à jour la commande", vm.SubmitLabel); + + using var json = JsonDocument.Parse(JsonSerializer.Serialize(api.LastBody)); + Assert.Equal(77, json.RootElement.GetProperty("Id").GetInt32()); + Assert.Equal(31, json.RootElement.GetProperty("PrestationId").GetInt32()); + Assert.Equal("Note mise à jour", json.RootElement.GetProperty("AdditionalInfo").GetString()); + Assert.Equal((int)QueryStatus.Accepted, json.RootElement.GetProperty("Status").GetInt32()); + } + private sealed class RecordingApi : IYavscApiClient { public HttpClient Http { get; } = new(); + public HttpMethod? LastMethod { get; private set; } public string? LastPath { get; private set; } public object? LastBody { get; private set; } public List? HairPrestations { get; init; } public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) { + LastMethod = method; LastPath = path; LastBody = body; if (typeof(T) == typeof(List)) @@ -152,6 +208,7 @@ public class BillingCommandPageViewModelTests public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) { + LastMethod = method; LastPath = path; LastBody = body; return Task.CompletedTask; diff --git a/src/PostIt/PostIt.Tests/BillingQueriesPageViewModelTests.cs b/src/PostIt/PostIt.Tests/BillingQueriesPageViewModelTests.cs index f8a3348b..a5d37532 100644 --- a/src/PostIt/PostIt.Tests/BillingQueriesPageViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/BillingQueriesPageViewModelTests.cs @@ -22,9 +22,33 @@ public class BillingQueriesPageViewModelTests await vm.InitializeAsync(); Assert.Equal("https://business.example/api/v1/billing/Rdv", api.Paths.Single()); - Assert.Equal(1, vm.Queries.Count); - Assert.Equal("Rendez-vous #1", vm.Queries[0].Description); - Assert.Contains("1 commande", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); + Assert.Equal(3, vm.Queries.Count); + Assert.Contains(vm.Queries, q => q.Description == "Rendez-vous #1"); + Assert.Contains("3 commande", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task RefreshAsync_in_readonly_ongoing_mode_keeps_only_ongoing_statuses_and_disables_open() + { + var api = new StubBillingApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new BillingQueriesPageViewModel( + new ActivityBrowseItemDto { Code = "dev", Name = "Développement" }, + new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" }, + new CommandFormSummaryDto { Id = 1, ActionName = "Rdv", Title = "Rendez-vous" }, + client, + isReadOnly: true, + ongoingOnly: true); + + await vm.InitializeAsync(); + + Assert.Equal(2, vm.Queries.Count); + Assert.All(vm.Queries, q => Assert.DoesNotContain("Rejected", q.StatusLabel, StringComparison.OrdinalIgnoreCase)); + Assert.Contains("lecture seule", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); + Assert.False(vm.CanOpenDetails); + + vm.SelectedQuery = vm.Queries[0]; + Assert.False(vm.OpenSelectedQueryCommand.CanExecute(null)); } private sealed class StubBillingApi : IYavscApiClient @@ -70,6 +94,26 @@ public class BillingQueriesPageViewModelTests Status = QueryStatus.Accepted, Description = "Autre performer", EventDate = new DateTime(2026, 9, 3, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 14, + ActivityCode = "dev", + PerformerId = "perf-1", + ClientId = "cli-1", + Status = QueryStatus.InProgress, + Description = "En cours", + EventDate = new DateTime(2026, 9, 4, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 15, + ActivityCode = "dev", + PerformerId = "perf-1", + ClientId = "cli-1", + Status = QueryStatus.Rejected, + Description = "Rejetée", + EventDate = new DateTime(2026, 9, 5, 10, 0, 0, DateTimeKind.Utc), } }; diff --git a/src/PostIt/PostIt/ViewModels/BillingCommandPageViewModel.cs b/src/PostIt/PostIt/ViewModels/BillingCommandPageViewModel.cs index 68516ea9..c9050cbf 100644 --- a/src/PostIt/PostIt/ViewModels/BillingCommandPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/BillingCommandPageViewModel.cs @@ -61,6 +61,12 @@ public partial class BillingCommandPageViewModel : ViewModelBase [ObservableProperty] public partial string AdditionalInfo { get; set; } = string.Empty; + [ObservableProperty] + public partial long? ExistingQueryId { get; set; } + + [ObservableProperty] + public partial QueryStatus CommandStatus { get; set; } = QueryStatus.Inserted; + public string Title => Form.Title; public string PerformerLabel => Performer.UserName; public string ActivityLabel => Activity.Name; @@ -73,6 +79,8 @@ public partial class BillingCommandPageViewModel : ViewModelBase public bool ShowsSinglePrestation => IsBrush; public bool ShowsMultiplePrestations => IsMultiBrush; public string BillingRoute => $"/billing/{Form.ActionName}"; + public bool IsEditingExisting => ExistingQueryId.HasValue; + public string SubmitLabel => IsEditingExisting ? "Mettre à jour la commande" : "Poster la commande"; public string SupportMessage => IsSupported ? IsRdv ? "Complétez les informations du rendez-vous puis postez la commande." @@ -108,10 +116,21 @@ public partial class BillingCommandPageViewModel : ViewModelBase StatusMessage = SupportMessage; } - public async Task InitializeAsync() + partial void OnExistingQueryIdChanged(long? value) + { + OnPropertyChanged(nameof(IsEditingExisting)); + OnPropertyChanged(nameof(SubmitLabel)); + } + + public async Task InitializeAsync(BillingQueryDetailsDto? existingQuery = null) { if (!IsBrush && !IsMultiBrush) { + if (existingQuery is not null) + { + ApplyExistingQuery(existingQuery); + } + return; } @@ -139,6 +158,11 @@ public partial class BillingCommandPageViewModel : ViewModelBase { IsBusy = false; } + + if (existingQuery is not null) + { + ApplyExistingQuery(existingQuery); + } } [RelayCommand] @@ -196,18 +220,44 @@ public partial class BillingCommandPageViewModel : ViewModelBase Longitude = longitude, }; + var payload = new BillingQueryDetailsDto + { + Id = ExistingQueryId ?? 0, + BillingCode = Form.ActionName, + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent = Consent, + EventDate = eventDate, + Status = CommandStatus, + Reason = Reason.Trim(), + AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? string.Empty : AdditionalInfo.Trim(), + Location = new BillingLocationDto + { + Address = location.Address, + Latitude = location.Latitude, + Longitude = location.Longitude, + } + }; + if (IsRdv) { - await _billingClient.CreateAsync(Form.ActionName, new + if (IsEditingExisting) { - ActivityCode = Activity.Code, - PerformerId = Performer.PerformerId, - Consent, - EventDate = eventDate, - Location = location, - Reason = Reason.Trim(), - Status = QueryStatus.Inserted, - }).ConfigureAwait(true); + await _billingClient.UpdateAsync(Form.ActionName, ExistingQueryId!.Value, payload).ConfigureAwait(true); + } + else + { + await _billingClient.CreateAsync(Form.ActionName, new + { + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent, + EventDate = eventDate, + Location = location, + Reason = payload.Reason, + Status = payload.Status, + }).ConfigureAwait(true); + } } else if (IsBrush) { @@ -217,17 +267,26 @@ public partial class BillingCommandPageViewModel : ViewModelBase return; } - await _billingClient.CreateAsync(Form.ActionName, new + payload.PrestationId = SelectedPrestation.Id; + + if (IsEditingExisting) { - ActivityCode = Activity.Code, - PerformerId = Performer.PerformerId, - Consent, - EventDate = (DateTime?)eventDate, - Location = location, - PrestationId = SelectedPrestation.Id, - AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? null : AdditionalInfo.Trim(), - Status = QueryStatus.Inserted, - }).ConfigureAwait(true); + await _billingClient.UpdateAsync(Form.ActionName, ExistingQueryId!.Value, payload).ConfigureAwait(true); + } + else + { + await _billingClient.CreateAsync(Form.ActionName, new + { + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent, + EventDate = (DateTime?)eventDate, + Location = location, + PrestationId = SelectedPrestation.Id, + AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? null : AdditionalInfo.Trim(), + Status = payload.Status, + }).ConfigureAwait(true); + } } else if (IsMultiBrush) { @@ -238,19 +297,30 @@ public partial class BillingCommandPageViewModel : ViewModelBase return; } - await _billingClient.CreateAsync(Form.ActionName, new + payload.PrestationIds = selectedPrestations.Select(x => x.Id).ToList(); + + if (IsEditingExisting) { - ActivityCode = Activity.Code, - PerformerId = Performer.PerformerId, - Consent, - EventDate = eventDate, - Location = location, - Prestations = selectedPrestations.Select(x => new { PrestationId = x.Id }).ToList(), - Status = QueryStatus.Inserted, - }).ConfigureAwait(true); + await _billingClient.UpdateAsync(Form.ActionName, ExistingQueryId!.Value, payload).ConfigureAwait(true); + } + else + { + await _billingClient.CreateAsync(Form.ActionName, new + { + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent, + EventDate = eventDate, + Location = location, + Prestations = selectedPrestations.Select(x => new { PrestationId = x.Id }).ToList(), + Status = payload.Status, + }).ConfigureAwait(true); + } } - StatusMessage = $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; + StatusMessage = IsEditingExisting + ? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}." + : $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; } catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) { @@ -266,6 +336,47 @@ public partial class BillingCommandPageViewModel : ViewModelBase } } + private void ApplyExistingQuery(BillingQueryDetailsDto existingQuery) + { + ExistingQueryId = existingQuery.Id; + CommandStatus = existingQuery.Status; + Consent = existingQuery.Consent; + Reason = existingQuery.Reason ?? string.Empty; + AdditionalInfo = existingQuery.AdditionalInfo ?? string.Empty; + + if (existingQuery.EventDate is not null) + { + EventDateText = existingQuery.EventDate.Value + .ToLocalTime() + .ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture); + } + + if (existingQuery.Location is not null) + { + Address = existingQuery.Location.Address ?? string.Empty; + LatitudeText = existingQuery.Location.Latitude.ToString(CultureInfo.InvariantCulture); + LongitudeText = existingQuery.Location.Longitude.ToString(CultureInfo.InvariantCulture); + } + + if (IsBrush && existingQuery.PrestationId is not null) + { + SelectedPrestation = AvailablePrestations.FirstOrDefault(x => x.Id == existingQuery.PrestationId.Value); + } + + if (IsMultiBrush) + { + var selectedIds = existingQuery.PrestationIds is null + ? new HashSet() + : new HashSet(existingQuery.PrestationIds); + foreach (var item in MultiPrestations) + { + item.IsSelected = selectedIds.Contains(item.Id); + } + } + + StatusMessage = $"Commande #{existingQuery.Id} chargée."; + } + private bool TryParseEventDate(out DateTime eventDate) { return DateTime.TryParse( diff --git a/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs index 7629ac42..d680ba74 100644 --- a/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs @@ -4,8 +4,11 @@ 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.Api.Client; using Yavsc.Abstract.Workflow; @@ -18,18 +21,26 @@ public partial class BillingQueriesPageViewModel : ViewModelBase public ActivityBrowseItemDto Activity { get; } public ActivityUserDisplayItem Performer { get; } public CommandFormSummaryDto Form { get; } + public bool IsReadOnly { get; } + public bool OngoingOnly { get; } [ObservableProperty] public partial ObservableCollection Queries { get; set; } = new(); + [ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedQueryCommand))] + public partial BillingQueryDisplayItem? SelectedQuery { get; set; } + [ObservableProperty] public partial bool IsBusy { get; set; } [ObservableProperty] public partial string StatusMessage { get; set; } = "Chargement des commandes..."; - public string Title => $"Commandes {Form.Title}"; + public string Title => IsReadOnly + ? $"Demandes en cours ({Form.Title})" + : $"Commandes {Form.Title}"; public string ContextLabel => $"{Performer.UserName} · {Activity.Name}"; + public bool CanOpenDetails => !IsReadOnly; public override bool CanNavigateNext { @@ -47,16 +58,22 @@ public partial class BillingQueriesPageViewModel : ViewModelBase ActivityBrowseItemDto activity, ActivityUserDisplayItem performer, CommandFormSummaryDto form, - BillingApiClient billingClient) + BillingApiClient billingClient, + bool isReadOnly = false, + bool ongoingOnly = false) { Activity = activity ?? throw new ArgumentNullException(nameof(activity)); Performer = performer ?? throw new ArgumentNullException(nameof(performer)); Form = form ?? throw new ArgumentNullException(nameof(form)); _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); + IsReadOnly = isReadOnly; + OngoingOnly = ongoingOnly; } public Task InitializeAsync() => RefreshAsync(); + private bool CanOpenSelectedQuery() => !IsReadOnly && SelectedQuery is not null; + [RelayCommand] public async Task RefreshAsync() { @@ -66,15 +83,14 @@ public partial class BillingQueriesPageViewModel : ViewModelBase var list = await _billingClient.GetQuerySummariesAsync(Form.ActionName).ConfigureAwait(true); var filtered = (list ?? new()) .Where(q => q.ActivityCode == Activity.Code && q.PerformerId == Performer.PerformerId) + .Where(q => !OngoingOnly || IsOngoingStatus(q.Status)) .OrderByDescending(q => q.EventDate ?? DateTime.MinValue) .ThenByDescending(q => q.Id) .Select(BillingQueryDisplayItem.FromDto) .ToList(); Queries = new ObservableCollection(filtered); - StatusMessage = filtered.Count == 0 - ? "Aucune commande trouvée pour ce formulaire." - : $"{filtered.Count} commande(s) chargée(s)."; + StatusMessage = BuildLoadedStatusMessage(filtered.Count); } catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) { @@ -91,4 +107,67 @@ public partial class BillingQueriesPageViewModel : ViewModelBase IsBusy = false; } } + + [RelayCommand(CanExecute = nameof(CanOpenSelectedQuery))] + public async Task OpenSelectedQueryAsync() + { + if (IsReadOnly) + { + StatusMessage = "Mode lecture seule: l'ouverture en modification est désactivée."; + return; + } + + if (SelectedQuery is null) + { + StatusMessage = "Sélectionnez une commande."; + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + IsBusy = true; + try + { + var details = await _billingClient.GetQueryAsync(Form.ActionName, SelectedQuery.Id).ConfigureAwait(true); + var vm = new BillingCommandPageViewModel(Activity, Performer, Form, _billingClient); + await vm.InitializeAsync(details).ConfigureAwait(true); + await app.PushPageAsync(vm).ConfigureAwait(true); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur lors de l'ouverture: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + private string BuildLoadedStatusMessage(int count) + { + if (count == 0) + { + return OngoingOnly + ? "Aucune demande en cours pour ce formulaire." + : "Aucune commande trouvée pour ce formulaire."; + } + + if (OngoingOnly) + { + return $"{count} demande(s) en cours chargée(s) (lecture seule)."; + } + + return $"{count} commande(s) chargée(s)."; + } + + private static bool IsOngoingStatus(QueryStatus status) + => status is QueryStatus.Inserted or QueryStatus.Accepted or QueryStatus.InProgress; } \ No newline at end of file diff --git a/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs index 426533a7..e1453c11 100644 --- a/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs @@ -21,7 +21,7 @@ public partial class CommandFormsPageViewModel : ViewModelBase [ObservableProperty] public partial ObservableCollection Forms { get; set; } - [ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedFormCommand)), NotifyCanExecuteChangedFor(nameof(OpenQueriesCommand))] + [ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedFormCommand)), NotifyCanExecuteChangedFor(nameof(OpenQueriesCommand)), NotifyCanExecuteChangedFor(nameof(OpenOngoingQueriesCommand))] public partial CommandFormSummaryDto? SelectedForm { get; set; } [ObservableProperty] @@ -64,6 +64,8 @@ public partial class CommandFormsPageViewModel : ViewModelBase private bool CanOpenQueries() => SelectedForm is not null; + private bool CanOpenOngoingQueries() => SelectedForm is not null; + [RelayCommand(CanExecute = nameof(CanOpenSelectedForm))] private async Task OpenSelectedFormAsync() { @@ -103,4 +105,30 @@ public partial class CommandFormsPageViewModel : ViewModelBase await vm.InitializeAsync(); await app.PushPageAsync(vm); } + + [RelayCommand(CanExecute = nameof(CanOpenOngoingQueries))] + private async Task OpenOngoingQueriesAsync() + { + if (SelectedForm is null) + { + StatusMessage = "Sélectionnez un formulaire."; + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + var vm = new BillingQueriesPageViewModel( + Activity, + Performer, + SelectedForm, + _billingClient, + isReadOnly: true, + ongoingOnly: true); + await vm.InitializeAsync(); + await app.PushPageAsync(vm); + } } \ No newline at end of file diff --git a/src/PostIt/PostIt/Views/BillingCommandPage.axaml b/src/PostIt/PostIt/Views/BillingCommandPage.axaml index 251376e1..2dba7336 100644 --- a/src/PostIt/PostIt/Views/BillingCommandPage.axaml +++ b/src/PostIt/PostIt/Views/BillingCommandPage.axaml @@ -108,7 +108,7 @@