From eef8c95d98e8d4a6257f7cbe64bd4ddf781caebd Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 30 Aug 2026 09:49:17 +0200 Subject: [PATCH] =?UTF-8?q?feat(sites):=20suppression=20de=20site=20en=20c?= =?UTF-8?q?ascade=20=E2=80=94=20agents=20et=20cam=C3=A9ras=20(#177)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Commands/DeleteSite/DeleteSiteHandler.cs | 28 +++++++++++- .../DeleteSite/GetSiteCascadeInfoQuery.cs | 12 ++++++ .../GetSiteCascadeInfoHandler.cs | 33 ++++++++++++++ .../Components/Pages/SitesPage.razor | 43 ++++++++++++++++++- .../Controllers/SitesController.cs | 14 ++++++ .../Services/HeimdallApiClient.cs | 9 ++++ .../Handlers/Sites/DeleteSiteHandlerTests.cs | 42 +++++++++++++++++- 7 files changed, 177 insertions(+), 4 deletions(-) create mode 100644 src/Heimdall.Application/Sites/Commands/DeleteSite/GetSiteCascadeInfoQuery.cs create mode 100644 src/Heimdall.Application/Sites/Queries/GetSiteCascadeInfo/GetSiteCascadeInfoHandler.cs diff --git a/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs b/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs index 85d766f..083c80d 100644 --- a/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs +++ b/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs @@ -1,6 +1,7 @@ using Heimdall.Application.Common; using Heimdall.Domain.Entities; using MediatR; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Sites.Commands.DeleteSite; @@ -8,15 +9,40 @@ public class DeleteSiteHandler : IRequestHandler _context = context; + public async Task Handle(DeleteSiteCommand request, CancellationToken cancellationToken) { var site = await _context.Sites.FindAsync([request.Id], cancellationToken).ConfigureAwait(false); if (site is null) return ServiceResult.NotFound("Site not found"); + // ── Cascade soft-delete: agents + cameras in the same transaction ── + var cameras = await _context.Cameras + .Where(c => c.SiteId == request.Id && !c.IsDeleted) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + + var agents = await _context.Agents + .Where(a => a.SiteId == request.Id && !a.IsDeleted) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + + foreach (var camera in cameras) + camera.SoftDelete(); + + foreach (var agent in agents) + agent.SoftDelete(); + + // Soft-delete the site itself site.SoftDelete(); - _context.AuditLogs.Add(new AuditLog(null, "Site.Deleted", "Site", request.Id.ToString())); + // Audit log with cascade info + _context.AuditLogs.Add(new AuditLog( + null, + "Site.Deleted", + "Site", + request.Id.ToString(), + newValue: $"Cascade: {agents.Count} agent(s), {cameras.Count} camera(s) soft-deleted")); await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false); return ServiceResult.Success(); diff --git a/src/Heimdall.Application/Sites/Commands/DeleteSite/GetSiteCascadeInfoQuery.cs b/src/Heimdall.Application/Sites/Commands/DeleteSite/GetSiteCascadeInfoQuery.cs new file mode 100644 index 0000000..1abb8a0 --- /dev/null +++ b/src/Heimdall.Application/Sites/Commands/DeleteSite/GetSiteCascadeInfoQuery.cs @@ -0,0 +1,12 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Sites.Commands.DeleteSite; + +/// +/// Returns the number of agents and cameras that would be cascade-deleted with a site. +/// Used by the UI to display the scope before confirmation. +/// +public record GetSiteCascadeInfoQuery(Guid SiteId) : IRequest>; + +public record SiteCascadeInfoResponse(int AgentCount, int CameraCount); diff --git a/src/Heimdall.Application/Sites/Queries/GetSiteCascadeInfo/GetSiteCascadeInfoHandler.cs b/src/Heimdall.Application/Sites/Queries/GetSiteCascadeInfo/GetSiteCascadeInfoHandler.cs new file mode 100644 index 0000000..d8e2a16 --- /dev/null +++ b/src/Heimdall.Application/Sites/Queries/GetSiteCascadeInfo/GetSiteCascadeInfoHandler.cs @@ -0,0 +1,33 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Sites.Commands.DeleteSite; +using Microsoft.EntityFrameworkCore; +using MediatR; + +namespace Heimdall.Application.Sites.Queries.GetSiteCascadeInfo; + +public class GetSiteCascadeInfoHandler : IRequestHandler> +{ + private readonly IApplicationDbContext _context; + + public GetSiteCascadeInfoHandler(IApplicationDbContext context) => _context = context; + + public async Task> Handle(GetSiteCascadeInfoQuery request, CancellationToken cancellationToken) + { + var site = await _context.Sites.FindAsync([request.SiteId], cancellationToken).ConfigureAwait(false); + if (site is null) + return ServiceResult.NotFound("Site not found"); + + var agentCount = await _context.Agents + .Where(a => a.SiteId == request.SiteId && !a.IsDeleted) + .CountAsync(cancellationToken) + .ConfigureAwait(false); + + var cameraCount = await _context.Cameras + .Where(c => c.SiteId == request.SiteId && !c.IsDeleted) + .CountAsync(cancellationToken) + .ConfigureAwait(false); + + return ServiceResult.Success( + new SiteCascadeInfoResponse(agentCount, cameraCount)); + } +} diff --git a/src/Heimdall.Web/Components/Pages/SitesPage.razor b/src/Heimdall.Web/Components/Pages/SitesPage.razor index ca254d3..b2ab644 100644 --- a/src/Heimdall.Web/Components/Pages/SitesPage.razor +++ b/src/Heimdall.Web/Components/Pages/SitesPage.razor @@ -115,10 +115,30 @@ else Confirmer la suppression Supprimer le site "@_confirmDeleteName" ? Cette action est irréversible. + @if (_cascadeInfoLoading) + { + + Chargement du périmètre... + } + else if (_cascadeInfo is not null) + { + + + Cette action supprimera également : + + + • @(_cascadeInfo.AgentCount) agent(s) + + + • @(_cascadeInfo.CameraCount) caméra(s) + + + } Annuler - Supprimer + Supprimer @@ -293,12 +313,31 @@ else private bool _confirmDeleteShow; private Guid _confirmDeleteId; private string _confirmDeleteName = ""; + private SiteCascadeInfo? _cascadeInfo; + private bool _cascadeInfoLoading; - private void ConfirmDeleteSite(Guid id, string name) + private async Task ConfirmDeleteSite(Guid id, string name) { _confirmDeleteId = id; _confirmDeleteName = name; + _cascadeInfo = null; + _cascadeInfoLoading = true; _confirmDeleteShow = true; + StateHasChanged(); + + try + { + _cascadeInfo = await Api.GetSiteCascadeInfoAsync(id); + } + catch + { + // If we can't load cascade info, still allow deletion + _cascadeInfo = null; + } + finally + { + _cascadeInfoLoading = false; + } } private async Task ExecuteDelete() diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index 4a8068d..7d72916 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -10,6 +10,7 @@ using Heimdall.Application.Sites.Commands.DeleteSite; using Heimdall.Application.Sites.Commands.GenerateSiteToken; using Heimdall.Application.Sites.Queries.GetSites; using Heimdall.Application.Sites.Queries.GetSite; +using Heimdall.Application.Sites.Queries.GetSiteCascadeInfo; using Heimdall.Infrastructure.Security; using MediatR; using Microsoft.AspNetCore.Authorization; @@ -94,6 +95,19 @@ public class SitesController : ControllerBase : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } + /// Get cascade info (agent/camera counts) before deleting a site. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)] + [HttpGet("{id:guid}/cascade-info")] + [ProducesResponseType(typeof(SiteCascadeInfoResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetCascadeInfo(Guid id, CancellationToken ct) + { + var result = await _mediator.Send(new GetSiteCascadeInfoQuery(id), ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + /// Delete a site (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)] [HttpDelete("{id:guid}")] diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 3d3b790..b03d1b5 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -369,6 +369,14 @@ public class HeimdallApiClient return response.IsSuccessStatusCode; } + public async Task GetSiteCascadeInfoAsync(Guid siteId) + { + var client = CreateClient(); + var response = await client.GetAsync($"api/sites/{siteId}/cascade-info"); + if (!response.IsSuccessStatusCode) return null; + return await response.Content.ReadFromJsonAsync(Json); + } + public async Task DeleteSiteAsync(Guid id) { var client = CreateClient(); @@ -1104,3 +1112,4 @@ public record CreateApiKeyResult( public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; } public class PlatformAssetInfo { [JsonPropertyName("url")] public string Url { get; set; } = ""; [JsonPropertyName("sha256")] public string? Sha256 { get; set; } [JsonPropertyName("size")] public long Size { get; set; } } +public record SiteCascadeInfo([property: JsonPropertyName("agentCount")] int AgentCount, [property: JsonPropertyName("cameraCount")] int CameraCount); diff --git a/tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs index b9e0315..9cdc1a1 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs @@ -15,6 +15,8 @@ public class DeleteSiteHandlerTests { var context = Substitute.For(); context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + context.Cameras.Returns(MockDbSetHelper.CreateFor()); var handler = new DeleteSiteHandler(context); var command = new DeleteSiteCommand(_existingSite.Id); @@ -28,6 +30,8 @@ public class DeleteSiteHandlerTests { var context = Substitute.For(); context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + context.Cameras.Returns(MockDbSetHelper.CreateFor()); var handler = new DeleteSiteHandler(context); var command = new DeleteSiteCommand(Guid.NewGuid()); @@ -42,6 +46,8 @@ public class DeleteSiteHandlerTests { var context = Substitute.For(); context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + context.Cameras.Returns(MockDbSetHelper.CreateFor()); var handler = new DeleteSiteHandler(context); var command = new DeleteSiteCommand(_existingSite.Id); @@ -49,6 +55,40 @@ public class DeleteSiteHandlerTests _existingSite.IsDeleted.ShouldBeTrue(); _existingSite.DeletedAt.ShouldNotBeNull(); - await context.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + await context.Received(2).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Delete_site_should_cascade_soft_delete_agents_and_cameras() + { + var siteId = _existingSite.Id; + var agent1 = new Agent(siteId, "Agent1", "host1", "1.0"); + var agent2 = new Agent(siteId, "Agent2", "host2", "1.0"); + var camera1 = new Camera(siteId, "Camera1"); + var camera2 = new Camera(siteId, "Camera2"); + + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + context.Agents.Returns(MockDbSetHelper.CreateFor([agent1, agent2])); + context.Cameras.Returns(MockDbSetHelper.CreateFor([camera1, camera2])); + var handler = new DeleteSiteHandler(context); + var command = new DeleteSiteCommand(siteId); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + // Site should be soft-deleted + _existingSite.IsDeleted.ShouldBeTrue(); + _existingSite.DeletedAt.ShouldNotBeNull(); + // Agents should be soft-deleted + agent1.IsDeleted.ShouldBeTrue(); + agent1.DeletedAt.ShouldNotBeNull(); + agent2.IsDeleted.ShouldBeTrue(); + agent2.DeletedAt.ShouldNotBeNull(); + // Cameras should be soft-deleted + camera1.IsDeleted.ShouldBeTrue(); + camera1.DeletedAt.ShouldNotBeNull(); + camera2.IsDeleted.ShouldBeTrue(); + camera2.DeletedAt.ShouldNotBeNull(); } }