50 lines
1.9 KiB
C#
50 lines
1.9 KiB
C#
using System.Text.Json;
|
|
using Heimdall.Application.Common;
|
|
using Heimdall.Application.DTOs;
|
|
using Heimdall.Domain.Entities;
|
|
using MediatR;
|
|
|
|
namespace Heimdall.Application.Persons.Commands.UpdatePerson;
|
|
|
|
public record UpdatePersonCommand(
|
|
Guid Id, string DisplayName, string? Notes, string? Category, bool IsWatchlisted, Guid? ActorId = null)
|
|
: IRequest<ServiceResult<PersonResponse>>;
|
|
|
|
public class UpdatePersonCommandHandler : IRequestHandler<UpdatePersonCommand, ServiceResult<PersonResponse>>
|
|
{
|
|
private readonly IApplicationDbContext _db;
|
|
|
|
public UpdatePersonCommandHandler(IApplicationDbContext db) => _db = db;
|
|
|
|
public async Task<ServiceResult<PersonResponse>> Handle(UpdatePersonCommand request, CancellationToken ct)
|
|
{
|
|
var person = await _db.Persons.FindAsync([request.Id], ct).ConfigureAwait(false);
|
|
if (person is null)
|
|
return ServiceResult<PersonResponse>.NotFound("Person not found");
|
|
|
|
var oldValue = new
|
|
{
|
|
person.DisplayName,
|
|
person.Category,
|
|
person.IsWatchlisted,
|
|
HasNotes = !string.IsNullOrWhiteSpace(person.Notes)
|
|
};
|
|
person.Update(request.DisplayName, request.Notes, request.Category, request.IsWatchlisted);
|
|
_db.AuditLogs.Add(new AuditLog(request.ActorId, "Person.Updated", "Person", person.Id.ToString(),
|
|
JsonSerializer.Serialize(oldValue), JsonSerializer.Serialize(new
|
|
{
|
|
person.DisplayName,
|
|
person.Category,
|
|
person.IsWatchlisted,
|
|
HasNotes = !string.IsNullOrWhiteSpace(person.Notes)
|
|
})));
|
|
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
return ServiceResult<PersonResponse>.Success(Map(person));
|
|
}
|
|
|
|
private static PersonResponse Map(Person p) => new(
|
|
p.Id, p.DisplayName, p.Notes, p.PhotoUrl,
|
|
p.Category, p.IsWatchlisted, p.Faces.Count, p.CreatedAt);
|
|
}
|