Refactor FinalizeEnvelopeCommand and handler logic

Simplified the `FinalizeEnvelopeCommand` by removing unused properties (`BurnedAllowed` and `SaveDocResult`) and streamlining its structure. Enhanced the `FinalizeEnvelopeCommandHandler` with additional dependencies (`ILogger` and `IRepository<History>`) for logging and history access.

Improved envelope query to include related entities (`Documents.Elements`, `Histories`, and `User`) for comprehensive data processing. Refined validation logic to ensure all receivers have signed the document and added detailed error messages for better user feedback.

Updated document processing to save the signed document (`docResult`) directly to the repository. Enhanced notification handling with improved content, error handling, and logging for both receivers and the sender.

Removed redundant code and updated `EnvelopeFinalizationWorker` to align with the new command structure. These changes improve maintainability, robustness, and clarity of the envelope finalization process.
This commit is contained in:
2026-11-26 17:08:28 +01:00
parent 67faa441b8
commit 98ef8005f0
2 changed files with 63 additions and 35 deletions

View File

@@ -1,5 +1,6 @@
using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions; using DigitalData.Core.Exceptions;
using DigitalData.UserManager.Domain.Entities;
using EnvelopeGenerator.Application.Common.Interfaces.Services.Notification; using EnvelopeGenerator.Application.Common.Interfaces.Services.Notification;
using EnvelopeGenerator.Application.Common.Query; using EnvelopeGenerator.Application.Common.Query;
using EnvelopeGenerator.Domain.Constants; using EnvelopeGenerator.Domain.Constants;
@@ -7,6 +8,7 @@ using EnvelopeGenerator.Domain.Entities;
using EnvelopeGenerator.Domain.Interfaces; using EnvelopeGenerator.Domain.Interfaces;
using MediatR; using MediatR;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace EnvelopeGenerator.Application.PdfSigning; namespace EnvelopeGenerator.Application.PdfSigning;
@@ -27,16 +29,6 @@ public record FinalizeEnvelopeCommand : EnvelopeQueryBase, IRequest
UserId = userId; UserId = userId;
return this; return this;
} }
/// <summary>
///
/// </summary>
public bool BurnedAllowed { get; init; } = false;
/// <summary>
///
/// </summary>
public bool SaveDocResult { get; init; } = true;
} }
/// <summary> /// <summary>
@@ -45,7 +37,7 @@ public record FinalizeEnvelopeCommand : EnvelopeQueryBase, IRequest
/// <param name="Repo"></param> /// <param name="Repo"></param>
/// <param name="Sender"></param> /// <param name="Sender"></param>
/// <param name="NtfServer"></param> /// <param name="NtfServer"></param>
public class FinalizeEnvelopeCommandHandler(IRepository<Envelope> Repo, ISender Sender, IEnvelopeNotificationService NtfServer) : IRequestHandler<FinalizeEnvelopeCommand> public class FinalizeEnvelopeCommandHandler(IRepository<Envelope> Repo, ISender Sender, IEnvelopeNotificationService NtfServer, ILogger<FinalizeEnvelopeCommandHandler> Logger, IRepository<History> HistoryRepo) : IRequestHandler<FinalizeEnvelopeCommand>
{ {
/// <summary> /// <summary>
/// ///
@@ -56,6 +48,7 @@ public class FinalizeEnvelopeCommandHandler(IRepository<Envelope> Repo, ISender
/// <exception cref="NotFoundException"></exception> /// <exception cref="NotFoundException"></exception>
public async Task Handle(FinalizeEnvelopeCommand request, CancellationToken cancel) public async Task Handle(FinalizeEnvelopeCommand request, CancellationToken cancel)
{ {
#region Read Envelope
var envelopeQuery = Repo.Query; var envelopeQuery = Repo.Query;
if (request.Id is int id) if (request.Id is int id)
@@ -65,20 +58,31 @@ public class FinalizeEnvelopeCommandHandler(IRepository<Envelope> Repo, ISender
var envelope = await envelopeQuery var envelope = await envelopeQuery
.Include(e => e.EnvelopeReceivers).ThenInclude(er => er.Receiver) .Include(e => e.EnvelopeReceivers).ThenInclude(er => er.Receiver)
.Include(e => e.Documents) .Include(e => e.Documents).ThenInclude(doc => doc.Elements)
.Include(e => e.Histories)
.Include(e => e.User)
.SingleOrDefaultAsync(cancel) .SingleOrDefaultAsync(cancel)
?? throw new NotFoundException($"Envelope is not found ID: {request.Id} UUID: {request.Uuid}"); ?? throw new NotFoundException($"Envelope not found. Id: {request.Id}, Uuid: {request.Uuid}.");
if(request.UserId is int userId && userId != envelope.UserId) if (request.UserId is int userId && userId != envelope.UserId)
throw new InvalidOperationException($"Envelope is not owned by user ID: {request.Id} UUID: {request.Uuid}"); throw new InvalidOperationException($"Access denied: envelope {envelope.Id} is not owned by user {userId}.");
#endregion
// already burned #region Check Envelope Status
if (!request.BurnedAllowed && envelope.IsBurned()) if (envelope.IsBurned())
throw new InvalidOperationException($"Envelope is already burned ID: {request.Id} UUID: {request.Uuid}"); throw new InvalidOperationException($"Envelope {envelope.Id} has already been finalized and cannot be finalized again.");
// envelope is not completely signed var rcvMails = envelope.EnvelopeReceivers.Select(er => er.Receiver.EmailAddress).ToList();
if (envelope.Status!= EnvelopeStatus.EnvelopeCompletelySigned) foreach (var email in rcvMails)
throw new InvalidOperationException($"Envelope status is not completely signed ID: {request.Id} UUID: {request.Uuid}"); {
if (email is null)
throw new InvalidOperationException($"Cannot finalize envelope {envelope.Id}: one of its receivers has no email address.");
var signed = envelope.Histories.Any(h => h.UserReference == email && h.Status == EnvelopeStatus.DocumentSigned);
if(!signed)
throw new InvalidOperationException($"Cannot finalize envelope {envelope.Id}: receiver '{email}' has not signed the document yet.");
}
#endregion
using var docStream = await Sender.Send(new SignPdfByEnvelopeCommand() using var docStream = await Sender.Send(new SignPdfByEnvelopeCommand()
{ {
@@ -90,20 +94,46 @@ public class FinalizeEnvelopeCommandHandler(IRepository<Envelope> Repo, ISender
using var ms = new MemoryStream(); using var ms = new MemoryStream();
docStream.CopyTo(ms); docStream.CopyTo(ms);
byte[] doc = ms.ToArray(); byte[] docResult = ms.ToArray();
// save document to envelope
await Repo.UpdateAsync(e => e.DocResult = docResult, e => e.Id == envelope.Id, cancel);
foreach (var er in envelope.EnvelopeReceivers) foreach (var er in envelope.EnvelopeReceivers)
{ {
await NtfServer.Notify(er.Receiver.EmailAddress, new DocumentSignedNotification() try
{ {
DocumentTitle = envelope.Title, await NtfServer.Notify(er.Receiver.EmailAddress, new DocumentCompletedNotification()
NameReceiver = er.Name, {
Attachments = [($"unterzeichnetes-dokument.pdf", doc)], DocumentTitle = envelope.Title,
IsReadAndConfirm = envelope.IsReadAndConfirm(), NameReceiver = er.Name,
}, cancel); Attachments = [($"unterzeichnetes-dokument.pdf", docResult)],
}, cancel);
}
catch (Exception ex)
{
Logger.LogError(ex, "Failed to send completion notification to receiver {receiverEmail} for envelope {envelopeId}.", er.Receiver.EmailAddress, envelope.Id);
}
} }
if (request.SaveDocResult) try
await Repo.UpdateAsync(e => e.DocResult = doc, e => e.Id == envelope.Id, cancel); {
if (envelope.User is not User user)
throw new InvalidOperationException($"Envelope {envelope.Id} has no associated sender user to notify.");
if (user.Email is not string userEmail)
throw new InvalidOperationException($"Sender user of envelope {envelope.Id} has no email address to notify.");
await NtfServer.Notify(userEmail, new DocumentCompletedNotification()
{
DocumentTitle = envelope.Title,
NameReceiver = user.Name ?? string.Empty,
Attachments = [($"unterzeichnetes-dokument.pdf", docResult)],
}, cancel);
}
catch (Exception ex)
{
Logger.LogError(ex, "Failed to send completion notification to sender {senderEmail} for envelope {envelopeId}.", envelope.User?.Email, envelope.Id);
}
} }
} }

View File

@@ -44,9 +44,7 @@ public sealed class EnvelopeFinalizationWorker(
{ {
await sender.Send(new FinalizeEnvelopeCommand() await sender.Send(new FinalizeEnvelopeCommand()
{ {
Id = envelopeId, Id = envelopeId
BurnedAllowed = false,
SaveDocResult = true,
}, stoppingToken); }, stoppingToken);
} }
catch(Exception ex) catch(Exception ex)