using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.Core.Exceptions; using EnvelopeGenerator.Domain; using EnvelopeGenerator.Domain.Entities; using EnvelopeGenerator.Extensions; using MediatR; using Microsoft.EntityFrameworkCore; namespace EnvelopeGenerator.Application.EnvelopeReceivers.Queries; /// /// /// public record ReceiverAlreadySignedQuery : IRequest { /// /// /// public string Key { get => (Envelope.Uuid, Receiver.Signature).EncodeEnvelopeReceiverId(); init { (string? EnvelopeUuid, string? ReceiverSignature) = value.DecodeEnvelopeReceiverId(); if (string.IsNullOrEmpty(EnvelopeUuid) || string.IsNullOrEmpty(ReceiverSignature)) { throw new BadRequestException("Der EnvelopeReceiverKey muss ein gültiger Base64-kodierter String sein, der die EnvelopeUuid und die ReceiverSignature enthält."); } } } /// /// /// public EnvelopeQuery Envelope { get; set; } = new EnvelopeQuery(); /// /// /// public ReceiverQuery Receiver { get; set; } = new ReceiverQuery(); } #region Queries /// /// /// public record EnvelopeQuery() { /// /// /// public string Uuid { get; set; } = null!; }; /// /// /// public record ReceiverQuery() { /// /// /// public string Signature { get; set; } = null!; }; #endregion /// /// /// public static class ReceiverAlreadySignedQueryExtensions { /// /// /// /// /// /// /// public static Task IsSignedAsync(this IMediator mediator, string key, CancellationToken cancel = default) => mediator.Send(new ReceiverAlreadySignedQuery { Key = key }, cancel); /// /// /// /// /// /// /// /// public static Task IsSignedAsync(this IMediator mediator, string uuid, string signature, CancellationToken cancel = default) => mediator.Send(new ReceiverAlreadySignedQuery { Envelope = new() { Uuid = uuid }, Receiver = new() { Signature = signature } }, cancel); } /// /// /// public class ReceiverAlreadySignedQueryHandler : IRequestHandler { private readonly IRepository _repo; /// /// /// /// public ReceiverAlreadySignedQueryHandler(IRepository repo) { _repo = repo; } /// /// /// /// /// /// public async Task Handle(ReceiverAlreadySignedQuery request, CancellationToken cancel = default) { return await _repo.Read() .Where(er => er.Envelope.Uuid == request.Envelope.Uuid) .Where(er => er.Receiver.Signature == request.Receiver.Signature) .Where(er => er.Envelope.History.Any(hist => hist.Status == Constants.EnvelopeStatus.DocumentSigned)) .AnyAsync(cancel); } }