using DigitalData.Core.Abstraction.Application.Repository; using EnvelopeGenerator.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; using AutoMapper; using EnvelopeGenerator.Application.Common.Dto; using EnvelopeGenerator.Application.Common.Extensions; namespace EnvelopeGenerator.Application.DocStatus.Commands; /// /// Represents a command to save the status of a document, either by creating a new status or updating an existing one based on the provided envelope and receiver identifiers. /// It returns the identifier of the saved document status. /// public record SaveDocStatusCommand : ModifyDocStatusCommandBase, IRequest; /// /// /// public class SaveDocStatusCommandHandler : IRequestHandler { private readonly IMapper _mapper; private readonly IRepository _repo; private readonly IRepository _envRepo; private readonly IRepository _rcvRepo; /// /// /// /// /// /// /// public SaveDocStatusCommandHandler(IMapper mapper, IRepository repo, IRepository rcvRepo, IRepository envRepo) { _mapper = mapper; _repo = repo; _rcvRepo = rcvRepo; _envRepo = envRepo; } /// /// /// /// /// /// public async Task Handle(SaveDocStatusCommand request, CancellationToken cancel) { // ceck if exists bool isExists = await _repo.ReadOnly().Where(request).AnyAsync(cancel); var env = await _envRepo.ReadOnly().Where(request.Envelope).FirstAsync(cancel); var rcv = await _rcvRepo.ReadOnly().Where(request.Receiver).FirstAsync(cancel); request.Envelope.Id = env.Id; request.Receiver.Id = rcv.Id; if (isExists) { var uReq = request.To(); await _repo.UpdateAsync(uReq, q => q.Where(request), cancel); } else { var cReq = request.To(); await _repo.CreateAsync(cReq, cancel); } var docStatus = await _repo.ReadOnly().Where(request).SingleOrDefaultAsync(cancel); return _mapper.Map(docStatus); } }