using AutoMapper; using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.Core.Exceptions; using EnvelopeGenerator.Application.Common.Dto; using EnvelopeGenerator.Application.DocReceiverElements.Commands; using EnvelopeGenerator.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; namespace EnvelopeGenerator.Application.DocReceiverElements.Behaviors; /// /// Pipeline behavior that creates document status. /// Executes second in the signing process. /// public class SaveSignatureBehavior : IPipelineBehavior { private readonly ISender _sender; private readonly IRepository _elementRepo; private readonly IMapper _mapper; /// /// /// /// /// /// public SaveSignatureBehavior(ISender sender, IRepository elementRepo, IMapper mapper) { _sender = sender; _elementRepo = elementRepo; _elementRepo = elementRepo; _mapper = mapper; } /// /// /// /// /// /// /// public async Task Handle(SigningCommand request, RequestHandlerDelegate next, CancellationToken cancel) { if (request.ReceiverAppType == ReceiverAppType.LegacyWeb) return await next(cancel); else if(request.Signatures is not IEnumerable signatures) throw new BadRequestException($"Signatures are required for saving signature behavior."); var elements = await _elementRepo .Where(e => e.Document.EnvelopeId == request.Envelope.Id) .Where(e => e.ReceiverId == request.Receiver.Id) .ToListAsync(cancel); foreach (var element in elements) { var signatures = request.Signatures.Where(s => s.Id == element.Id).ToList(); if(signatures.Count == 0) throw new BadRequestException("No signature found for element with id {element.Id}."); else if(signatures.Count > 1) throw new BadRequestException("Multiple signatures found for element with id {element.Id}."); await _elementRepo.UpdateAsync(signatures.First(), e => e.Id == element.Id, cancel); } return await next(cancel); } }