using AutoMapper; using EnvelopeGenerator.Application.Contracts.SQLExecutor; using EnvelopeGenerator.Application.DTOs.Receiver; using EnvelopeGenerator.Domain.Entities; using MediatR; namespace EnvelopeGenerator.Application.EnvelopeReceivers.Commands.Create; /// /// Handles the creation of an envelope along with its associated document and recipients. /// This command processes the envelope data, including title, message, document content, /// recipient list, and optional two-factor authentication settings. /// public class CreateEnvelopeReceiverCommandHandler : IRequestHandler { private readonly IMapper _mapper; private readonly IEnvelopeExecutor _envelopeExecutor; private readonly IEnvelopeReceiverExecutor _erExecutor; /// /// /// /// /// /// public CreateEnvelopeReceiverCommandHandler(IMapper mapper, IEnvelopeExecutor envelopeExecutor, IEnvelopeReceiverExecutor erExecutor) { _mapper = mapper; _envelopeExecutor = envelopeExecutor; _erExecutor = erExecutor; } /// /// Handles the execution of the . /// Responsible for validating input data, creating or retrieving recipients, associating signatures, /// and storing the envelope and document details. /// /// The command containing all necessary information to create an envelope. /// Token to observe while waiting for the task to complete. /// A task representing the asynchronous operation. public async Task Handle(CreateEnvelopeReceiverCommand request, CancellationToken cancel) { int userId = request.UserId ?? throw new InvalidOperationException("UserId cannot be null when creating an envelope."); var envelope = await _envelopeExecutor.CreateEnvelopeAsync(userId, request.Title, request.Message, request.TFAEnabled, cancel); List sentRecipients = new(); List unsentRecipients = new(); foreach (var receiver in request.Receivers) { var envelopeReceiver = await _erExecutor.AddEnvelopeReceiverAsync(envelope.Uuid, receiver.EmailAddress, receiver.Salution, receiver.PhoneNumber, cancel); if (envelopeReceiver is null) unsentRecipients.Add(receiver); else sentRecipients.Add(envelopeReceiver); } var res = _mapper.Map(envelope); res.UnsentReceivers = unsentRecipients; res.SentReceiver = _mapper.Map>(sentRecipients); return res; } }