diff --git a/EnvelopeGenerator.Application/PdfSigning/FinalizeEnvelopeCommand.cs b/EnvelopeGenerator.Application/PdfSigning/FinalizeEnvelopeCommand.cs
index 3a649478..ca99fe9b 100644
--- a/EnvelopeGenerator.Application/PdfSigning/FinalizeEnvelopeCommand.cs
+++ b/EnvelopeGenerator.Application/PdfSigning/FinalizeEnvelopeCommand.cs
@@ -1,5 +1,6 @@
using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions;
+using DigitalData.UserManager.Domain.Entities;
using EnvelopeGenerator.Application.Common.Interfaces.Services.Notification;
using EnvelopeGenerator.Application.Common.Query;
using EnvelopeGenerator.Domain.Constants;
@@ -7,6 +8,7 @@ using EnvelopeGenerator.Domain.Entities;
using EnvelopeGenerator.Domain.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
namespace EnvelopeGenerator.Application.PdfSigning;
@@ -27,16 +29,6 @@ public record FinalizeEnvelopeCommand : EnvelopeQueryBase, IRequest
UserId = userId;
return this;
}
-
- ///
- ///
- ///
- public bool BurnedAllowed { get; init; } = false;
-
- ///
- ///
- ///
- public bool SaveDocResult { get; init; } = true;
}
///
@@ -45,7 +37,7 @@ public record FinalizeEnvelopeCommand : EnvelopeQueryBase, IRequest
///
///
///
-public class FinalizeEnvelopeCommandHandler(IRepository Repo, ISender Sender, IEnvelopeNotificationService NtfServer) : IRequestHandler
+public class FinalizeEnvelopeCommandHandler(IRepository Repo, ISender Sender, IEnvelopeNotificationService NtfServer, ILogger Logger, IRepository HistoryRepo) : IRequestHandler
{
///
///
@@ -56,54 +48,92 @@ public class FinalizeEnvelopeCommandHandler(IRepository Repo, ISender
///
public async Task Handle(FinalizeEnvelopeCommand request, CancellationToken cancel)
{
+ #region Read Envelope
var envelopeQuery = Repo.Query;
if (request.Id is int id)
envelopeQuery = envelopeQuery.Where(e => e.Id == id);
else if (request.Uuid is string uuid)
envelopeQuery = envelopeQuery.Where(e => e.Uuid == uuid);
-
+
var envelope = await envelopeQuery
.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)
- ?? 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)
- throw new InvalidOperationException($"Envelope is not owned by user ID: {request.Id} UUID: {request.Uuid}");
+ if (request.UserId is int userId && userId != envelope.UserId)
+ throw new InvalidOperationException($"Access denied: envelope {envelope.Id} is not owned by user {userId}.");
+ #endregion
- // already burned
- if (!request.BurnedAllowed && envelope.IsBurned())
- throw new InvalidOperationException($"Envelope is already burned ID: {request.Id} UUID: {request.Uuid}");
+ #region Check Envelope Status
+ if (envelope.IsBurned())
+ throw new InvalidOperationException($"Envelope {envelope.Id} has already been finalized and cannot be finalized again.");
- // envelope is not completely signed
- if (envelope.Status!= EnvelopeStatus.EnvelopeCompletelySigned)
- throw new InvalidOperationException($"Envelope status is not completely signed ID: {request.Id} UUID: {request.Uuid}");
+ var rcvMails = envelope.EnvelopeReceivers.Select(er => er.Receiver.EmailAddress).ToList();
+ foreach (var email in rcvMails)
+ {
+ 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()
{
Envelope = envelope
}, cancel);
- if (docStream.CanSeek)
+ if (docStream.CanSeek)
docStream.Position = 0;
using var ms = new MemoryStream();
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)
{
- await NtfServer.Notify(er.Receiver.EmailAddress, new DocumentSignedNotification()
+ try
{
- DocumentTitle = envelope.Title,
- NameReceiver = er.Name,
- Attachments = [($"unterzeichnetes-dokument.pdf", doc)],
- IsReadAndConfirm = envelope.IsReadAndConfirm(),
- }, cancel);
+ await NtfServer.Notify(er.Receiver.EmailAddress, new DocumentCompletedNotification()
+ {
+ DocumentTitle = envelope.Title,
+ NameReceiver = er.Name,
+ 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)
- await Repo.UpdateAsync(e => e.DocResult = doc, e => e.Id == envelope.Id, cancel);
+ try
+ {
+ 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);
+ }
}
}
\ No newline at end of file
diff --git a/EnvelopeGenerator.Server/EnvelopeGenerator.Server/BackgroundServices/EnvelopeFinalizationWorker.cs b/EnvelopeGenerator.Server/EnvelopeGenerator.Server/BackgroundServices/EnvelopeFinalizationWorker.cs
index 491e5e60..d4b40bd6 100644
--- a/EnvelopeGenerator.Server/EnvelopeGenerator.Server/BackgroundServices/EnvelopeFinalizationWorker.cs
+++ b/EnvelopeGenerator.Server/EnvelopeGenerator.Server/BackgroundServices/EnvelopeFinalizationWorker.cs
@@ -44,9 +44,7 @@ public sealed class EnvelopeFinalizationWorker(
{
await sender.Send(new FinalizeEnvelopeCommand()
{
- Id = envelopeId,
- BurnedAllowed = false,
- SaveDocResult = true,
+ Id = envelopeId
}, stoppingToken);
}
catch(Exception ex)