Files
DbFirst/DbFirst.Application/Catalogs/Commands/UpdateCatalogHandler.cs
OlgunR de5d1b666c Add current user service and use for catalog audit fields
Introduce ICurrentUserService and its implementation to access the current user's username. Inject this service into CreateCatalogHandler and UpdateCatalogHandler to set AddedWho and ChangedWho fields dynamically. Register the service and IHttpContextAccessor in DI, and enable authentication middleware. Update project and using statements accordingly.
2026-05-13 09:05:04 +02:00

49 lines
1.8 KiB
C#

using AutoMapper;
using DbFirst.Application.Abstractions;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.Catalogs;
using DbFirst.Domain;
using DbFirst.Domain.Entities;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
public class UpdateCatalogHandler : IRequestHandler<UpdateCatalogCommand, CatalogReadDto?>
{
private readonly ICatalogRepository _repository;
private readonly IMapper _mapper;
private readonly ICurrentUserService _currentUserService;
public UpdateCatalogHandler(ICatalogRepository repository, IMapper mapper, ICurrentUserService currentUserService)
{
_repository = repository;
_mapper = mapper;
_currentUserService = currentUserService;
}
public async Task<CatalogReadDto?> Handle(UpdateCatalogCommand request, CancellationToken cancellationToken)
{
var existing = await _repository.GetByIdAsync(request.Id, cancellationToken);
if (existing == null)
{
return null;
}
if (request.Dto.UpdateProcedure == CatalogUpdateProcedure.Update &&
!string.Equals(existing.CatTitle, request.Dto.CatTitle, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Titel kann nicht geändert werden.");
}
var entity = _mapper.Map<VwmyCatalog>(request.Dto);
entity.Guid = request.Id;
entity.AddedWho = existing.AddedWho;
entity.AddedWhen = existing.AddedWhen;
entity.ChangedWho = _currentUserService.UserName;
entity.ChangedWhen = DateTime.UtcNow;
var updated = await _repository.UpdateAsync(request.Id, entity, request.Dto.UpdateProcedure, cancellationToken);
return updated == null ? null : _mapper.Map<CatalogReadDto>(updated);
}
}