using AutoMapper; using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.Core.Exceptions; using MediatR; using System.Text.Json.Serialization; using EnvelopeGenerator.Domain.Entities; using Microsoft.EntityFrameworkCore; using EnvelopeGenerator.Domain.Constants; using EnvelopeGenerator.Application.Common.Dto; namespace EnvelopeGenerator.Application.EmailTemplates.Commands.Update; /// /// Befehl zum Aktualisieren einer E-Mail-Vorlage. /// /// /// (Optional)Der neue Inhalt des E-Mail-Textkörpers. Wenn null, bleibt der vorhandene Inhalt unverändert. /// /// /// (Optional) Der neue Betreff der E-Mail. Wenn null, bleibt der vorhandene Betreff unverändert. /// public record UpdateEmailTemplateCommand(string? Body = null, string? Subject = null) : IRequest { /// /// Die Abfrage, die die E-Mail-Vorlage darstellt, die aktualisiert werden soll. /// [JsonIgnore] public EmailTemplateQueryBase? EmailTemplateQuery { get; set; } /// /// /// [JsonIgnore] public DateTime ChangedWhen { get; init; } = DateTime.Now; } /// /// /// public class UpdateEmailTemplateCommandHandler : IRequestHandler { private readonly IRepository _repository; private readonly IMapper _mapper; /// /// /// /// /// public UpdateEmailTemplateCommandHandler(IRepository repository, IMapper mapper) { _repository = repository; _mapper = mapper; } /// /// /// /// /// /// /// /// [Obsolete("Use Read-method returning IReadQuery instead.")] public async Task Handle(UpdateEmailTemplateCommand request, CancellationToken cancel) { EmailTemplateDto? tempDto; if (request.EmailTemplateQuery?.Id is int id) { var temp = await _repository.ReadOnly().Where(t => t.Id == id).FirstOrDefaultAsync(cancel); tempDto = _mapper.Map(temp); } else if (request!.EmailTemplateQuery!.Type is EmailTemplateType type) { var temp = await _repository.ReadOnly().Where(t => t.Name == type.ToString()).FirstOrDefaultAsync(cancel); tempDto = _mapper.Map(temp); } else { throw new InvalidOperationException("Both id and type is null. Id: " + request.EmailTemplateQuery.Id + ". Type: " + request.EmailTemplateQuery.Type.ToString()); } if (tempDto == null) { throw new NotFoundException(); } await _repository.UpdateAsync(tempDto, t => t.Id == tempDto.Id, cancel); } }