feat(sites): suppression de site en cascade — agents et caméras (#177)

This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-30 09:49:17 +02:00
1 parent e6e8690588
commit eef8c95d98
7 files changed
+177 -4

No files matched your search

@@ -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<DeleteSiteCommand, ServiceResul
{
private readonly IApplicationDbContext _context;
public DeleteSiteHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult> 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();
@@ -0,0 +1,12 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Sites.Commands.DeleteSite;
/// <summary>
/// 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.
/// </summary>
public record GetSiteCascadeInfoQuery(Guid SiteId) : IRequest<ServiceResult<SiteCascadeInfoResponse>>;
public record SiteCascadeInfoResponse(int AgentCount, int CameraCount);
@@ -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<GetSiteCascadeInfoQuery, ServiceResult<SiteCascadeInfoResponse>>
{
private readonly IApplicationDbContext _context;
public GetSiteCascadeInfoHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<SiteCascadeInfoResponse>> Handle(GetSiteCascadeInfoQuery request, CancellationToken cancellationToken)
{
var site = await _context.Sites.FindAsync([request.SiteId], cancellationToken).ConfigureAwait(false);
if (site is null)
return ServiceResult<SiteCascadeInfoResponse>.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<SiteCascadeInfoResponse>.Success(
new SiteCascadeInfoResponse(agentCount, cameraCount));
}
}
@@ -115,10 +115,30 @@ else
<TitleContent><MudText Typo="Typo.h6">Confirmer la suppression</MudText></TitleContent>
<DialogContent>
<MudText>Supprimer le site &quot;@_confirmDeleteName&quot; ? Cette action est irréversible.</MudText>
@if (_cascadeInfoLoading)
{
<MudProgressCircular Size="Size.Small" Class="mt-2" />
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="ml-2 d-inline">Chargement du périmètre...</MudText>
}
else if (_cascadeInfo is not null)
{
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Class="mt-3">
<MudText Typo="Typo.body2">
Cette action supprimera également :
</MudText>
<MudText Typo="Typo.body2" Class="mt-1">
• <strong>@(_cascadeInfo.AgentCount)</strong> agent(s)
</MudText>
<MudText Typo="Typo.body2">
• <strong>@(_cascadeInfo.CameraCount)</strong> caméra(s)
</MudText>
</MudAlert>
}
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteShow = false)">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@ExecuteDelete">Supprimer</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@ExecuteDelete"
Disabled="@_cascadeInfoLoading">Supprimer</MudButton>
</DialogActions>
</MudDialog>
@@ -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()
@@ -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 });
}
/// <summary>Get cascade info (agent/camera counts) before deleting a site.</summary>
[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<IActionResult> 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 });
}
/// <summary>Delete a site (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)]
[HttpDelete("{id:guid}")]
@@ -369,6 +369,14 @@ public class HeimdallApiClient
return response.IsSuccessStatusCode;
}
public async Task<SiteCascadeInfo?> 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<SiteCascadeInfo>(Json);
}
public async Task<bool> 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<string, PlatformAssetInfo> 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);