#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Email shared-signing participants and requesters as a request progresses (#8312)
ConnorYoh2853bf6dc67e
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 0fe589164f..f8296a767b 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -188,7 +188,7 @@ system:maxDPI: 500 # Maximum allowed DPI for PDF to image conversioncorsAllowedOrigins: [] # List of allowed origins for CORS (e.g. ['http://localhost:5173', 'https://app.example.com']). WARNING: leaving this empty falls back to allowing ALL origins (with credentials), it does NOT disable CORS. Set explicit origins to lock it down.backendUrl: "" # Backend base URL for SAML/OAuth/API callbacks (e.g. 'http://localhost:8080' for dev, 'https://api.example.com' for production). REQUIRED for SSO authentication to work correctly. This is where your IdP will send SAML responses and OAuth callbacks. Leave empty to default to 'http://localhost:8080' in development.- frontendUrl: "" # Base URL of the web app, as a browser reaches it (e.g. 'https://app.example.com', or 'https://example.com/app' if served under a base path). Optional - if not set, will use backendUrl. Used for any link handed to a browser: invite emails, share links, mobile QR codes, and the account-link handshake.+ frontendUrl: "" # Base URL of the web app, as a browser reaches it (e.g. 'https://app.example.com', or 'https://example.com/app' if served under a base path). Optional - if not set, will use backendUrl. Used for any link handed to a browser: invite and signing emails, share links, mobile QR codes, and the account-link handshake.enableMobileScanner: true # Enable mobile phone QR code upload feature. Requires frontendUrl to be configured.enableMobileSignature: true # Enable drawing signatures on a phone via QR code from the Sign tool. Requires frontendUrl to be configured.mobileScannerSettings:diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/EmailService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/EmailService.javaindex 5c1cf75450..cc617eac8b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/EmailService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/EmailService.java@@ -1,6 +1,7 @@package stirling.software.proprietary.security.service;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;+import org.springframework.core.io.ClassPathResource;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.scheduling.annotation.Async;@@ -27,6 +28,15 @@ import stirling.software.proprietary.security.model.api.Email;@ConditionalOnProperty(value = "mail.enabled", havingValue = "true", matchIfMissing = false)public class EmailService {+ /** Content id {@link #sendBrandedEmail} attaches the brand lockup under. */+ public static final String BRAND_LOGO_CONTENT_ID = "stirling-logo";++ // The ui/Logo.tsx lockup (logo-mark.svg + wordmark-light.svg) rasterised at 3x on white: most+ // email clients do not render SVG, and the white ground keeps it legible if a client darkens+ // the email.+ private static final ClassPathResource BRAND_LOGO =+ new ClassPathResource("email/stirling-lockup.png");+private final JavaMailSender mailSender;private final ApplicationProperties applicationProperties;@@ -309,4 +319,27 @@ public class EmailService {sendPlainEmail(to, subject, body, true);}++ /**+ * Sends an HTML email with the Stirling lockup attached inline, so the body can show it as+ * {@code <img src="cid:stirling-logo">} without the recipient's client fetching anything.+ *+ * @throws MessagingException if the recipient is blank or the message cannot be sent+ */+ @Async+ public void sendBrandedEmail(String to, String subject, String html) throws MessagingException {+ if (to == null || to.trim().isEmpty()) {+ throw new MessagingException("Invalid recipient email address");+ }+ MimeMessage message = mailSender.createMimeMessage();+ MimeMessageHelper helper =+ new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_RELATED, "UTF-8");+ helper.addTo(to);+ helper.setSubject(subject);+ helper.setFrom(applicationProperties.getMail().getFrom());+ // After setText: some mail readers cannot resolve a cid added before the body.+ helper.setText(html, true);+ helper.addInline(BRAND_LOGO_CONTENT_ID, BRAND_LOGO, "image/png");+ mailSender.send(message);+ }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.javaindex ca155a9087..a55bd8ebdc 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.java@@ -8,6 +8,7 @@ import java.util.HashMap;import java.util.List;import java.util.Map;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.http.ContentDisposition;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;@@ -41,6 +42,7 @@ import stirling.software.proprietary.workflow.dto.WorkflowSessionResponse;import stirling.software.proprietary.workflow.model.ParticipantStatus;import stirling.software.proprietary.workflow.model.WorkflowParticipant;import stirling.software.proprietary.workflow.model.WorkflowSession;+import stirling.software.proprietary.workflow.notification.SigningResponseEvent;import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;import stirling.software.proprietary.workflow.service.CertificateSubmissionValidator;import stirling.software.proprietary.workflow.service.MetadataEncryptionService;@@ -68,6 +70,7 @@ public class WorkflowParticipantController {private final ObjectMapper objectMapper;private final MetadataEncryptionService metadataEncryptionService;private final CertificateSubmissionValidator certificateSubmissionValidator;+ private final ApplicationEventPublisher eventPublisher;private static final DateTimeFormatter ISO_UTC =DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC);@@ -164,6 +167,7 @@ public class WorkflowParticipantController {// Update status to SIGNEDparticipant.setStatus(ParticipantStatus.SIGNED);participant = participantRepository.save(participant);+ eventPublisher.publishEvent(new SigningResponseEvent(participant.getId(), null));log.info("Participant {} submitted signature for session {}",@@ -212,6 +216,7 @@ public class WorkflowParticipantController {}participant = participantRepository.save(participant);+ eventPublisher.publishEvent(new SigningResponseEvent(participant.getId(), reason));log.info("Participant {} declined workflow session {}",@@ -222,39 +227,28 @@ public class WorkflowParticipantController {}@Operation(- summary = "Get original PDF for review",- description = "Participant downloads the original document")+ summary = "Get the session PDF",+ description =+ "Participant downloads the original document, or the signed document once the"+ + " owner has finalized the session")@GetMapping(value = "/document", produces = MediaType.APPLICATION_PDF_VALUE)public ResponseEntity<byte[]> getDocument(@RequestParam("token") @NotBlank String token) {workflowSessionService.ensureSigningEnabled();- WorkflowParticipant participant =- participantRepository- .findByShareToken(token)- .orElseThrow(- () ->- new ResponseStatusException(- HttpStatus.FORBIDDEN,- "Invalid or expired participant token"));-- if (participant.isExpired()) {- throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Participant access expired");- }-try {- WorkflowSession session = participant.getWorkflowSession();- byte[] pdf = workflowSessionService.getOriginalFile(session.getSessionId());+ WorkflowSessionService.ParticipantDocument document =+ workflowSessionService.getParticipantDocument(token);return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,ContentDisposition.attachment()- .filename(session.getDocumentName(), StandardCharsets.UTF_8)+ .filename(document.filename(), StandardCharsets.UTF_8).build().toString()).contentType(org.springframework.http.MediaType.APPLICATION_PDF)- .body(pdf);+ .body(document.content());} catch (IOException e) {log.error("Error retrieving document for participant", e);diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/ParticipantRequest.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/ParticipantRequest.javaindex 9f47f45b90..7f9404b1c4 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/ParticipantRequest.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/ParticipantRequest.java@@ -2,7 +2,6 @@ package stirling.software.proprietary.workflow.dto;import java.time.LocalDateTime;-import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@@ -11,10 +10,12 @@ import stirling.software.proprietary.storage.model.ShareAccessRole;/*** Request DTO for adding or configuring a workflow participant. Supports both registered users and* external email participants.+ *+ * <p>No all-args constructor: Jackson would bind through it and drop the field defaults below, so+ * an omitted {@code sendNotification} would arrive as false.*/@Data@NoArgsConstructor-@AllArgsConstructorpublic class ParticipantRequest {/** User ID if participant is a registered user */diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningCompletionEvent.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningCompletionEvent.javanew file mode 100644index 0000000000..8b24211b56--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningCompletionEvent.java@@ -0,0 +1,4 @@+package stirling.software.proprietary.workflow.notification;++/** The owner finalized a signing session. {@code sessionId} is the public session UUID. */+public record SigningCompletionEvent(String sessionId) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningEmailTemplates.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningEmailTemplates.javanew file mode 100644index 0000000000..313e973ad2--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningEmailTemplates.java@@ -0,0 +1,358 @@+package stirling.software.proprietary.workflow.notification;++import java.util.List;++import org.springframework.web.util.HtmlUtils;++import stirling.software.proprietary.security.service.EmailService;+import stirling.software.proprietary.workflow.model.ParticipantStatus;++/**+ * Subject and HTML body for each signing notification. Every value passed in is untrusted: bodies+ * HTML-escape it, and subjects strip control characters so a document name cannot inject a mail+ * header.+ */+final class SigningEmailTemplates {++ private static final int MAX_LISTED_NAMES = 10;+ private static final int MAX_SUBJECT_VALUE_LENGTH = 80;+ private static final int MAX_REASON_LENGTH = 500;++ // Light-theme values of the frontend tokens (frontend/editor/src/core/theme/colors.css),+ // inlined because email clients do not support CSS variables. BRAND is --c-brand, the fill of+ // the sign-in CTAs a recipient lands on.+ private static final String BRAND = "#af3434";+ private static final String TEXT_ON_BRAND = "#ffffff";+ private static final String TEXT = "#373530";+ private static final String TEXT_MUTED = "#4b5563";+ private static final String TEXT_SUBTLE = "#5d636d";+ private static final String BACKGROUND = "#f5f4f1";+ private static final String SURFACE = "#ffffff";+ private static final String BORDER = "#e5e7eb";+ private static final String FONT =+ "Inter,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";++ record Email(String to, String subject, String html) {}++ /**+ * What the emails report about a session, counted when the email is prepared.+ *+ * @param awaiting display names of participants who have neither responded nor expired+ */+ record Summary(+ String documentName,+ String ownerName,+ String message,+ String dueDate,+ int participants,+ int signed,+ int declined,+ List<String> awaiting) {++ /** Nobody is left to respond, and at least one signature can be applied. */+ boolean readyToFinalize() {+ return awaiting.isEmpty() && signed > 0;+ }+ }++ private SigningEmailTemplates() {}++ /**+ * @param link where the participant signs, or null when no base URL is configured+ * @param guestLink whether {@code link} carries the participant's share token+ */+ static Email invitation(String to, Summary summary, String link, boolean guestLink) {+ String owner = summary.ownerName();+ StringBuilder body = new StringBuilder();+ body.append(+ paragraph(+ escape(owner)+ + " has asked you to sign "+ + strong(summary.documentName())+ + "."));+ if (hasText(summary.message())) {+ body.append(paragraph("Message from " + escape(owner) + ":"))+ .append(quote(summary.message()));+ }+ if (hasText(summary.dueDate())) {+ body.append(paragraph("Please sign by " + escape(summary.dueDate()) + "."));+ }+ if (link == null) {+ body.append(paragraph("Sign in to Stirling PDF and open Shared Signing to review it."));+ }+ String note =+ guestLink+ ? "This link lets anyone who has it sign as you, so do not forward this"+ + " email."+ : null;+ return new Email(+ to,+ subjectText(owner)+ + " requested your signature on "+ + quoted(summary.documentName()),+ layout(+ "Your signature is requested",+ body.toString(),+ link,+ "Review and sign",+ note,+ "You received this email because "+ + owner+ + " added you to a signing request in Stirling PDF."));+ }++ /**+ * @param signed true for a signature, false for a decline+ * @param declineReason shown only for a decline, and only when not blank+ * @param link the requester's Shared Signing page, or null when no base URL is configured+ */+ static Email response(+ String to,+ Summary summary,+ String responderName,+ boolean signed,+ String declineReason,+ String link) {+ String action = signed ? " signed " : " declined to sign ";+ StringBuilder body = new StringBuilder();+ body.append(+ paragraph(escape(responderName) + action + strong(summary.documentName()) + "."));+ if (!signed && hasText(declineReason)) {+ body.append(paragraph("Their reason:"))+ .append(quote(truncate(declineReason.strip(), MAX_REASON_LENGTH)));+ }+ body.append(progress(summary)).append(paragraph(nextStep(summary)));+ if (link == null) {+ body.append(paragraph("Sign in to Stirling PDF and open Shared Signing to review it."));+ }+ boolean ready = summary.readyToFinalize();+ String subject =+ ready+ ? quoted(summary.documentName()) + " is ready to finalize"+ : subjectText(responderName) + action + quoted(summary.documentName());+ String heading =+ ready ? "Ready to finalize" : signed ? "New signature" : "Signature declined";+ return new Email(+ to,+ subject,+ layout(+ heading,+ body.toString(),+ link,+ ready ? "Review and finalize" : "Open Shared Signing",+ null,+ "You received this email because you requested signatures on "+ + summary.documentName()+ + " in Stirling PDF."));+ }++ /**+ * @param recipientStatus the recipient's status when the session was finalized+ * @param link where the recipient downloads the signed PDF, or null when no base URL is+ * configured+ * @param guestLink whether {@code link} carries the participant's share token+ */+ static Email completion(+ String to,+ Summary summary,+ ParticipantStatus recipientStatus,+ String link,+ boolean guestLink) {+ String owner = summary.ownerName();+ StringBuilder body = new StringBuilder();+ body.append(+ paragraph(escape(owner) + " finalized " + strong(summary.documentName()) + "."));+ body.append(+ paragraph(+ "Signatures included: "+ + summary.signed()+ + " of "+ + summary.participants()));+ body.append(+ paragraph(+ switch (recipientStatus) {+ case SIGNED -> "Your signature is included.";+ case DECLINED ->+ "You declined this request, so your signature is not"+ + " included.";+ default ->+ "The request closed before you signed, so your signature is"+ + " not included. You do not need to do anything"+ + " else.";+ }));+ if (link == null) {+ body.append(+ paragraph(+ "Sign in to Stirling PDF and open Shared Signing to download the"+ + " signed document."));+ }+ return new Email(+ to,+ quoted(summary.documentName()) + " has been finalized",+ layout(+ "Document finalized",+ body.toString(),+ link,+ "View signed document",+ guestLink+ ? "This link opens the signed document for anyone who has it, so"+ + " do not forward this email."+ : null,+ "You received this email because you were a participant in a signing"+ + " request from "+ + owner+ + " in Stirling PDF."));+ }++ private static String progress(Summary summary) {+ StringBuilder lines =+ new StringBuilder("Signed: " + summary.signed() + " of " + summary.participants());+ if (summary.declined() > 0) {+ lines.append("<br>Declined: ").append(summary.declined());+ }+ if (!summary.awaiting().isEmpty()) {+ lines.append("<br>Awaiting: ")+ .append(summary.awaiting().size())+ .append(" (")+ .append(names(summary.awaiting()))+ .append(")");+ }+ return paragraph(lines.toString());+ }++ private static String nextStep(Summary summary) {+ if (summary.readyToFinalize()) {+ return "Everyone has responded, so the document is ready to finalize.";+ }+ if (summary.awaiting().isEmpty()) {+ return "Everyone declined, so there is nothing to finalize.";+ }+ if (summary.signed() > 0) {+ return "You can finalize now, but anyone who has not signed yet will be left out.";+ }+ return "The document can be finalized once someone signs.";+ }++ private static String names(List<String> names) {+ String listed =+ String.join(+ ", ",+ names.stream()+ .limit(MAX_LISTED_NAMES)+ .map(SigningEmailTemplates::escape)+ .toList());+ int rest = names.size() - MAX_LISTED_NAMES;+ return rest > 0 ? listed + " and " + rest + " more" : listed;+ }++ /**+ * {@code body} is trusted HTML; every other argument is escaped here. Tables rather than divs+ * because Outlook's Word renderer ignores widths and padding on divs.+ */+ private static String layout(+ String heading,+ String body,+ String link,+ String linkLabel,+ String linkNote,+ String footer) {+ StringBuilder action = new StringBuilder();+ if (link != null) {+ String href = escape(link);+ action.append(+ """+ <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:24px 0 12px;">+ <tr><td style="border-radius:8px;background-color:%1$s;">+ <a href="%2$s" style="display:inline-block;padding:12px 22px;border-radius:8px;font-family:%3$s;font-size:15px;font-weight:600;line-height:1.2;color:%4$s;text-decoration:none;">%5$s</a>+ </td></tr>+ </table>+ <p style="margin:0;font-size:13px;color:%6$s;word-break:break-all;">Or copy this link into your browser: <a href="%2$s" style="color:%1$s;">%2$s</a></p>+ """+ .formatted(+ BRAND,+ href,+ FONT,+ TEXT_ON_BRAND,+ escape(linkLabel),+ TEXT_MUTED));+ if (linkNote != null) {+ action.append(+ "<p style=\"margin:12px 0 0;font-size:13px;color:%s;\">%s</p>"+ .formatted(TEXT_MUTED, escape(linkNote)));+ }+ }+ return """+ <!doctype html>+ <html lang="en">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="color-scheme" content="light only">+ <meta name="supported-color-schemes" content="light only">+ <title>%1$s</title>+ </head>+ <body style="margin:0;padding:0;background-color:%2$s;">+ <table role="presentation" width="100%%" cellpadding="0" cellspacing="0" border="0" style="background-color:%2$s;">+ <tr><td align="center" style="padding:32px 12px;">+ <table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="width:100%%;max-width:560px;background-color:%3$s;border:1px solid %4$s;border-radius:8px;">+ <tr><td style="padding:28px 32px 0;"><img src="cid:%5$s" width="89" height="32" alt="Stirling" style="display:block;width:89px;height:32px;border:0;"></td></tr>+ <tr><td style="padding:24px 32px 32px;font-family:%6$s;font-size:15px;line-height:1.6;color:%7$s;">+ <h1 style="margin:0 0 16px;font-size:20px;line-height:1.3;font-weight:600;color:%7$s;">%1$s</h1>+ %8$s%9$s+ </td></tr>+ <tr><td style="padding:16px 32px 20px;border-top:1px solid %4$s;font-family:%6$s;font-size:12px;line-height:1.5;color:%10$s;">%11$s</td></tr>+ </table>+ </td></tr>+ </table>+ </body>+ </html>+ """+ .formatted(+ escape(heading),+ BACKGROUND,+ SURFACE,+ BORDER,+ EmailService.BRAND_LOGO_CONTENT_ID,+ FONT,+ TEXT,+ body,+ action,+ TEXT_SUBTLE,+ escape(footer));+ }++ private static String paragraph(String html) {+ return "<p style=\"margin:0 0 12px;\">" + html + "</p>";+ }++ private static String strong(String text) {+ return "<strong>" + escape(text) + "</strong>";+ }++ private static String quote(String text) {+ return ("<div style=\"margin:0 0 12px;padding:10px 14px;border-left:3px solid %s;"+ + "background-color:%s;color:%s;\">%s</div>")+ .formatted(BORDER, BACKGROUND, TEXT, escape(text).replaceAll("\\R", "<br>"));+ }++ private static String escape(String text) {+ return text == null ? "" : HtmlUtils.htmlEscape(text);+ }++ private static String subjectText(String value) {+ String flat = value == null ? "" : value.replaceAll("[\\p{Cntrl}\\s]+", " ").strip();+ return truncate(flat, MAX_SUBJECT_VALUE_LENGTH);+ }++ private static String quoted(String value) {+ return "\"" + subjectText(value) + "\"";+ }++ private static String truncate(String value, int max) {+ return value.length() <= max ? value : value.substring(0, max - 3) + "...";+ }++ private static boolean hasText(String value) {+ return value != null && !value.isBlank();+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningInvitationEvent.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningInvitationEvent.javanew file mode 100644index 0000000000..a461bdb863--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningInvitationEvent.java@@ -0,0 +1,11 @@+package stirling.software.proprietary.workflow.notification;++import java.util.List;++/**+ * Participants were added to a signing session and should be emailed an invitation.+ *+ * @param sessionId the public session UUID+ * @param participantIds the added participants to invite; other participants are not re-invited+ */+public record SigningInvitationEvent(String sessionId, List<Long> participantIds) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningNotificationListener.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningNotificationListener.javanew file mode 100644index 0000000000..99aed5ddf8--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningNotificationListener.java@@ -0,0 +1,320 @@+package stirling.software.proprietary.workflow.notification;++import java.util.ArrayList;+import java.util.List;+import java.util.Objects;+import java.util.Optional;+import java.util.function.Supplier;+import java.util.regex.Pattern;+import java.util.stream.Stream;++import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;+import org.springframework.stereotype.Component;+import org.springframework.transaction.PlatformTransactionManager;+import org.springframework.transaction.TransactionDefinition;+import org.springframework.transaction.event.TransactionPhase;+import org.springframework.transaction.event.TransactionalEventListener;+import org.springframework.transaction.support.TransactionTemplate;++import jakarta.mail.MessagingException;++import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.EmailService;+import stirling.software.proprietary.workflow.model.ParticipantStatus;+import stirling.software.proprietary.workflow.model.WorkflowParticipant;+import stirling.software.proprietary.workflow.model.WorkflowSession;+import stirling.software.proprietary.workflow.model.WorkflowType;+import stirling.software.proprietary.workflow.notification.SigningEmailTemplates.Email;+import stirling.software.proprietary.workflow.notification.SigningEmailTemplates.Summary;+import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;+import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;++/**+ * Emails signing participants and the requester: an invitation when a participant is added, a+ * progress update to the requester on each signature or decline, and a completion notice to+ * participants when the requester finalizes. Nobody is emailed about their own action.+ *+ * <p>Runs after the publishing transaction commits, so a rolled-back action sends nothing, and+ * reloads the session in a read-only transaction of its own because open-in-view is off and the+ * publisher's entities are detached by then. Every failure is logged and swallowed: without a+ * surrounding transaction the listener runs inside {@code publishEvent}, and a saved signature must+ * not come back as an error because the mail server is down.+ */+@Slf4j+@Component+@ConditionalOnProperty(value = "mail.enabled", havingValue = "true")+public class SigningNotificationListener {++ // Must match the frontend routes: getToolUrlPath("sharedSign") and the token-gated participant+ // route in proprietary/App.tsx.+ static final String SHARED_SIGNING_PATH = "/shared-sign";+ static final String GUEST_SIGNING_PATH = "/workflow/sign/";++ // Same shape FileStorageService accepts for email shares; rejects usernames such as "admin".+ private static final Pattern EMAIL_ADDRESS =+ Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$");++ private final EmailService emailService;+ private final ApplicationProperties applicationProperties;+ private final WorkflowSessionRepository workflowSessionRepository;+ private final WorkflowParticipantRepository workflowParticipantRepository;+ private final TransactionTemplate readOnlyTransaction;++ public SigningNotificationListener(+ EmailService emailService,+ ApplicationProperties applicationProperties,+ WorkflowSessionRepository workflowSessionRepository,+ WorkflowParticipantRepository workflowParticipantRepository,+ PlatformTransactionManager transactionManager) {+ this.emailService = emailService;+ this.applicationProperties = applicationProperties;+ this.workflowSessionRepository = workflowSessionRepository;+ this.workflowParticipantRepository = workflowParticipantRepository;+ // REQUIRES_NEW: after commit the publisher's transaction is still bound to the thread, and+ // REQUIRED would join that finished transaction instead of starting one.+ this.readOnlyTransaction = new TransactionTemplate(transactionManager);+ this.readOnlyTransaction.setPropagationBehavior(+ TransactionDefinition.PROPAGATION_REQUIRES_NEW);+ this.readOnlyTransaction.setReadOnly(true);+ }++ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)+ public void onInvitation(SigningInvitationEvent event) {+ deliver("invitation", () -> invitations(event));+ }++ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)+ public void onResponse(SigningResponseEvent event) {+ deliver("response", () -> response(event));+ }++ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)+ public void onCompletion(SigningCompletionEvent event) {+ deliver("completion", () -> completions(event));+ }++ private void deliver(String kind, Supplier<List<Email>> compose) {+ List<Email> emails;+ try {+ emails =+ Objects.requireNonNullElse(+ readOnlyTransaction.execute(status -> compose.get()), List.of());+ } catch (RuntimeException e) {+ log.warn("Could not prepare signing {} emails", kind, e);+ return;+ }+ for (Email email : emails) {+ try {+ emailService.sendBrandedEmail(email.to(), email.subject(), email.html());+ } catch (MessagingException | RuntimeException e) {+ log.warn("Could not send a signing {} email", kind, e);+ }+ }+ }++ private List<Email> invitations(SigningInvitationEvent event) {+ WorkflowSession session = signingSession(event.sessionId());+ if (session == null || !session.isActive()) {+ return List.of();+ }+ Summary summary = summarize(session);+ List<Email> emails = new ArrayList<>();+ for (WorkflowParticipant participant : session.getParticipants()) {+ if (!event.participantIds().contains(participant.getId())+ || isOwner(session, participant)) {+ continue;+ }+ Optional<String> to = participantAddress(participant);+ Optional<String> link = participantLink(participant);+ if (to.isEmpty() || unusableGuestLink(participant, link)) {+ continue;+ }+ emails.add(+ SigningEmailTemplates.invitation(+ to.get(), summary, link.orElse(null), isGuest(participant)));+ }+ return emails;+ }++ private List<Email> response(SigningResponseEvent event) {+ WorkflowParticipant responder =+ workflowParticipantRepository.findById(event.participantId()).orElse(null);+ if (responder == null) {+ return List.of();+ }+ WorkflowSession session = responder.getWorkflowSession();+ ParticipantStatus status = responder.getStatus();+ // Inactive: a response that lands after finalization has nothing left to report, and+ // "ready to finalize" would mislead.+ if (session.getWorkflowType() != WorkflowType.SIGNING+ || !session.isActive()+ || isOwner(session, responder)+ || (status != ParticipantStatus.SIGNED && status != ParticipantStatus.DECLINED)) {+ return List.of();+ }+ Optional<String> to = ownerAddress(session);+ if (to.isEmpty()) {+ log.debug(+ "No email address for the owner of signing session {}", session.getSessionId());+ return List.of();+ }+ return List.of(+ SigningEmailTemplates.response(+ to.get(),+ summarize(session),+ displayName(responder),+ status == ParticipantStatus.SIGNED,+ event.declineReason(),+ appLink().orElse(null)));+ }++ private List<Email> completions(SigningCompletionEvent event) {+ WorkflowSession session = signingSession(event.sessionId());+ if (session == null) {+ return List.of();+ }+ Summary summary = summarize(session);+ List<Email> emails = new ArrayList<>();+ for (WorkflowParticipant participant : session.getParticipants()) {+ if (isOwner(session, participant)) {+ continue;+ }+ Optional<String> to = participantAddress(participant);+ Optional<String> link = participantLink(participant);+ if (to.isEmpty() || unusableGuestLink(participant, link)) {+ continue;+ }+ emails.add(+ SigningEmailTemplates.completion(+ to.get(),+ summary,+ participant.getStatus(),+ link.orElse(null),+ isGuest(participant)));+ }+ return emails;+ }++ private WorkflowSession signingSession(String sessionId) {+ return workflowSessionRepository+ .findBySessionIdWithParticipants(sessionId)+ .filter(session -> session.getWorkflowType() == WorkflowType.SIGNING)+ .orElse(null);+ }++ private static Summary summarize(WorkflowSession session) {+ int signed = 0;+ int declined = 0;+ List<String> awaiting = new ArrayList<>();+ for (WorkflowParticipant participant : session.getParticipants()) {+ switch (participant.getStatus()) {+ case SIGNED -> signed++;+ case DECLINED -> declined++;+ default -> {+ if (!participant.isExpired()) {+ awaiting.add(displayName(participant));+ }+ }+ }+ }+ return new Summary(+ session.getDocumentName(),+ session.getOwner().getUsername(),+ session.getMessage(),+ session.getDueDate(),+ session.getParticipants().size(),+ signed,+ declined,+ awaiting);+ }++ /**+ * A guest has no account to sign in to, so an email is only useful with a token link that+ * opens: not when no base URL is configured, and not once their access has expired, because the+ * token endpoints then answer 403.+ */+ private static boolean unusableGuestLink(+ WorkflowParticipant participant, Optional<String> link) {+ if (!isGuest(participant)) {+ return false;+ }+ if (participant.isExpired()) {+ return true;+ }+ if (link.isPresent()) {+ return false;+ }+ log.warn(+ "Skipped a signing email to a guest participant: set system.frontendUrl so it can"+ + " link to the signing page");+ return true;+ }++ private static boolean isGuest(WorkflowParticipant participant) {+ return participant.getUser() == null;+ }++ private static boolean isOwner(WorkflowSession session, WorkflowParticipant participant) {+ return participant.getUser() != null && participant.getUser().equals(session.getOwner());+ }++ private static String displayName(WorkflowParticipant participant) {+ if (hasText(participant.getName())) {+ return participant.getName().strip();+ }+ return hasText(participant.getEmail()) ? participant.getEmail().strip() : "A participant";+ }++ private static Optional<String> participantAddress(WorkflowParticipant participant) {+ User user = participant.getUser();+ return user != null ? userAddress(user) : emailAddress(participant.getEmail());+ }++ /** An address the owner gave for this session wins over the account's own. */+ private static Optional<String> ownerAddress(WorkflowSession session) {+ return emailAddress(session.getOwnerEmail()).or(() -> userAddress(session.getOwner()));+ }++ /** Self-hosted accounts often have no email column set, but are named by their address. */+ private static Optional<String> userAddress(User user) {+ return emailAddress(user.getEmail()).or(() -> emailAddress(user.getUsername()));+ }++ private static Optional<String> emailAddress(String value) {+ if (value == null) {+ return Optional.empty();+ }+ String trimmed = value.strip();+ return EMAIL_ADDRESS.matcher(trimmed).matches() ? Optional.of(trimmed) : Optional.empty();+ }++ /** Guests follow their share token; account holders sign in, so no bearer link is mailed. */+ private Optional<String> participantLink(WorkflowParticipant participant) {+ return isGuest(participant)+ ? baseUrl().map(base -> base + GUEST_SIGNING_PATH + participant.getShareToken())+ : appLink();+ }++ private Optional<String> appLink() {+ return baseUrl().map(base -> base + SHARED_SIGNING_PATH);+ }++ /**+ * Configured URLs only: the request's Host header is caller-controlled, and guests reach these+ * paths without signing in, so it must not decide where a link in someone else's inbox goes.+ */+ private Optional<String> baseUrl() {+ var system = applicationProperties.getSystem();+ return Stream.of(system.getFrontendUrl(), system.getBackendUrl())+ .filter(SigningNotificationListener::hasText)+ .map(url -> url.strip().replaceAll("/+$", ""))+ .findFirst();+ }++ private static boolean hasText(String value) {+ return value != null && !value.isBlank();+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningResponseEvent.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningResponseEvent.javanew file mode 100644index 0000000000..778f094fc4--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/notification/SigningResponseEvent.java@@ -0,0 +1,9 @@+package stirling.software.proprietary.workflow.notification;++/**+ * A participant signed or declined. The listener reads which from the participant's stored status,+ * so publish only after that status is saved.+ *+ * @param declineReason free text from the participant, or null+ */+public record SigningResponseEvent(Long participantId, String declineReason) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.javaindex e7d5ae0173..5c168941a5 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.java@@ -29,6 +29,7 @@ import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;import org.bouncycastle.operator.InputDecryptorProvider;import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;@@ -61,6 +62,9 @@ import stirling.software.proprietary.workflow.model.ParticipantStatus;import stirling.software.proprietary.workflow.model.WorkflowParticipant;import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.model.WorkflowStatus;+import stirling.software.proprietary.workflow.notification.SigningCompletionEvent;+import stirling.software.proprietary.workflow.notification.SigningInvitationEvent;+import stirling.software.proprietary.workflow.notification.SigningResponseEvent;import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;@@ -92,6 +96,7 @@ public class WorkflowSessionService {private final CertificateSubmissionValidator certificateSubmissionValidator;private final LicenseServiceInterface licenseService;private final CustomPDFDocumentFactory pdfDocumentFactory;+ private final ApplicationEventPublisher eventPublisher;/*** Personal account certificates require a paid entitlement; organization certificates do not.@@ -240,7 +245,7 @@ public class WorkflowSessionService {/*** Creates a new workflow session with participants. Stores the original file using- * StorageProvider.+ * StorageProvider. Participants are emailed an invitation once the transaction commits.*/public WorkflowSession createSession(User owner, MultipartFile file, WorkflowCreationRequest request) throws IOException {@@ -352,6 +357,7 @@ public class WorkflowSessionService {identities.add(existing.getEmail().strip().toLowerCase(Locale.ROOT));}List<WorkflowParticipant> additions = new ArrayList<>();+ List<WorkflowParticipant> invited = new ArrayList<>();for (ParticipantRequest request : participantRequests) {WorkflowParticipant participant = new WorkflowParticipant();participant.setShareToken(UUID.randomUUID().toString());@@ -421,11 +427,20 @@ public class WorkflowSessionService {HttpStatus.BAD_REQUEST, "Each participant may only be added once");}additions.add(participant);+ if (request.isSendNotification()) {+ invited.add(participant);+ }}for (WorkflowParticipant participant : additions) {session.addParticipant(participant);workflowParticipantRepository.save(participant);}+ if (!invited.isEmpty()) {+ eventPublisher.publishEvent(+ new SigningInvitationEvent(+ session.getSessionId(),+ invited.stream().map(WorkflowParticipant::getId).toList()));+ }}/** Stores a file as part of a workflow using the StorageProvider. */@@ -522,7 +537,10 @@ public class WorkflowSessionService {return workflowSessionRepository.findActiveSessionsByOwner(owner);}- /** Adds additional participants to an existing session. */+ /**+ * Adds additional participants to an existing session. Each one whose request has {@code+ * sendNotification} set is emailed an invitation once the transaction commits.+ */@Transactionalpublic void addParticipants(String sessionId, List<ParticipantRequest> participants, User owner) {@@ -613,7 +631,10 @@ public class WorkflowSessionService {workflowSessionRepository.save(session);}- /** Marks a workflow session as finalized. */+ /**+ * Marks a workflow session as finalized. Participants are emailed that it is complete once the+ * transaction commits, so store the processed file first.+ */public void finalizeSession(String sessionId, User owner) {WorkflowSession session = lockActiveSessionForOwner(sessionId, owner);@@ -625,6 +646,7 @@ public class WorkflowSessionService {session.setFinalized(true);session.setStatus(WorkflowStatus.COMPLETED);workflowSessionRepository.save(session);+ eventPublisher.publishEvent(new SigningCompletionEvent(sessionId));log.info("Finalized workflow session {}", sessionId);}@@ -656,6 +678,38 @@ public class WorkflowSessionService {}}+ /**+ * The document a share-token holder downloads: the signed PDF once the session is finalized, so+ * the link in the completion email delivers it, otherwise the original. Resolves the token in+ * its own transaction because the participant's session is lazy and open-in-view is off.+ */+ @Transactional(readOnly = true)+ public ParticipantDocument getParticipantDocument(String shareToken) throws IOException {+ WorkflowParticipant participant =+ workflowParticipantRepository+ .findByShareToken(shareToken)+ .orElseThrow(+ () ->+ new ResponseStatusException(+ HttpStatus.FORBIDDEN,+ "Invalid or expired participant token"));+ if (participant.isExpired()) {+ throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Participant access expired");+ }+ WorkflowSession session = participant.getWorkflowSession();+ boolean signed = session.isFinalized() && session.getProcessedFile() != null;+ StoredFile file = signed ? session.getProcessedFile() : session.getOriginalFile();+ if (file == null) {+ throw new ResponseStatusException(+ HttpStatus.NOT_FOUND, "Document not available for this session");+ }+ return new ParticipantDocument(+ readBlob(file.getStorageKey()),+ signed ? file.getOriginalFilename() : session.getDocumentName());+ }++ public record ParticipantDocument(byte[] content, String filename) {}+/** Retrieves the original file data for a workflow session. */@Transactional(readOnly = true)public byte[] getOriginalFile(String sessionId) throws IOException {@@ -868,7 +922,8 @@ public class WorkflowSessionService {}/**- * Sign a document in a workflow session.+ * Sign a document in a workflow session. The owner is emailed the session's progress once the+ * transaction commits.** @param sessionId The session ID* @param user The participant user@@ -1052,6 +1107,7 @@ public class WorkflowSessionService {// 5. Update participant statusparticipant.setStatus(ParticipantStatus.SIGNED);workflowParticipantRepository.save(participant);+ eventPublisher.publishEvent(new SigningResponseEvent(participant.getId(), null));log.info("User {} signed document in session {} - certificate and signature data stored",@@ -1060,7 +1116,8 @@ public class WorkflowSessionService {}/**- * Decline a sign request.+ * Decline a sign request. The owner is emailed the session's progress once the transaction+ * commits.** @param sessionId The session ID* @param user The participant user@@ -1072,6 +1129,7 @@ public class WorkflowSessionService {participant.setStatus(ParticipantStatus.DECLINED);workflowParticipantRepository.save(participant); // updatedAt is auto-updated+ eventPublisher.publishEvent(new SigningResponseEvent(participant.getId(), null));log.info("User {} declined sign request for session {}", user.getUsername(), sessionId);}diff --git a/app/proprietary/src/main/resources/email/stirling-lockup.png b/app/proprietary/src/main/resources/email/stirling-lockup.pngnew file mode 100644index 0000000000..39d9232082Binary files /dev/null and b/app/proprietary/src/main/resources/email/stirling-lockup.png differdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/EmailServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/EmailServiceTest.javaindex 66719e3726..9f09bdc362 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/EmailServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/EmailServiceTest.java@@ -3,18 +3,27 @@ package stirling.software.proprietary.security.service;import static org.junit.jupiter.api.Assertions.*;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;+import java.nio.charset.StandardCharsets;+import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.web.multipart.MultipartFile;+import jakarta.mail.BodyPart;import jakarta.mail.MessagingException;+import jakarta.mail.Part;+import jakarta.mail.Session;+import jakarta.mail.internet.MimeBodyPart;import jakarta.mail.internet.MimeMessage;+import jakarta.mail.internet.MimeMultipart;import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.security.model.api.Email;@@ -164,4 +173,43 @@ public class EmailServiceTest {assertEquals("Invalid Addresses", e.getMessage());}}++ @Test+ void sendBrandedEmailAttachesTheLockupInlineAfterTheHtmlBody() throws Exception {+ when(applicationProperties.getMail()).thenReturn(mailProperties);+ when(mailProperties.getFrom()).thenReturn("[email protected]");+ when(mailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));++ emailService.sendBrandedEmail(+ "[email protected]", "Signed", "<p><img src=\"cid:stirling-logo\"></p>");++ ArgumentCaptor<MimeMessage> sent = ArgumentCaptor.forClass(MimeMessage.class);+ verify(mailSender).send(sent.capture());+ MimeMessage message = sent.getValue();+ message.saveChanges();+ MimeMultipart related = (MimeMultipart) message.getContent();+ assertTrue(related.getContentType().startsWith("multipart/related"));+ assertEquals(2, related.getCount());++ BodyPart html = related.getBodyPart(0);+ assertTrue(html.isMimeType("text/html"));+ MimeBodyPart logo = (MimeBodyPart) related.getBodyPart(1);+ assertEquals("<" + EmailService.BRAND_LOGO_CONTENT_ID + ">", logo.getContentID());+ assertEquals(Part.INLINE, logo.getDisposition());+ assertTrue(logo.isMimeType("image/png"));+ byte[] png = logo.getInputStream().readAllBytes();+ assertEquals((byte) 0x89, png[0]);+ assertEquals("PNG", new String(png, 1, 3, StandardCharsets.US_ASCII));+ }++ @Test+ void sendBrandedEmailRejectsABlankRecipient() {+ MessagingException e =+ assertThrows(+ MessagingException.class,+ () -> emailService.sendBrandedEmail(" ", "Signed", "<p>x</p>"));++ assertEquals("Invalid recipient email address", e.getMessage());+ verifyNoInteractions(mailSender);+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/CertificateValidationIntegrationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/CertificateValidationIntegrationTest.javaindex 7311354138..04f8774005 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/CertificateValidationIntegrationTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/CertificateValidationIntegrationTest.java@@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.mock.web.MockMultipartFile;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;@@ -52,6 +53,7 @@ class CertificateValidationIntegrationTest {@Mock private WorkflowSessionService workflowSessionService;@Mock private WorkflowParticipantRepository participantRepository;@Mock private MetadataEncryptionService metadataEncryptionService;+ @Mock private ApplicationEventPublisher eventPublisher;// Mock PdfSigningService so the test-sign step succeeds without a real PDF engine@Mock private PdfSigningService pdfSigningService;@@ -72,7 +74,8 @@ class CertificateValidationIntegrationTest {participantRepository,new ObjectMapper(),metadataEncryptionService,- realValidator);+ realValidator,+ eventPublisher);mockMvc = MockMvcBuilders.standaloneSetup(controller).build();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.javaindex e84bb4f6e5..274924e9de 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.java@@ -3,8 +3,10 @@ package stirling.software.proprietary.workflow.controller;import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;+import java.io.IOException;import java.util.ArrayList;import java.util.Optional;@@ -15,6 +17,8 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.context.ApplicationEventPublisher;+import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.server.ResponseStatusException;@@ -28,6 +32,7 @@ import stirling.software.proprietary.workflow.model.ParticipantStatus;import stirling.software.proprietary.workflow.model.WorkflowParticipant;import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.model.WorkflowStatus;+import stirling.software.proprietary.workflow.notification.SigningResponseEvent;import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;import stirling.software.proprietary.workflow.service.CertificateSubmissionValidator;import stirling.software.proprietary.workflow.service.MetadataEncryptionService;@@ -43,6 +48,7 @@ class WorkflowParticipantControllerMoreTest {@Mock private WorkflowParticipantRepository participantRepository;@Mock private MetadataEncryptionService metadataEncryptionService;@Mock private CertificateSubmissionValidator certificateSubmissionValidator;+ @Mock private ApplicationEventPublisher eventPublisher;private WorkflowParticipantController controller;@@ -60,7 +66,8 @@ class WorkflowParticipantControllerMoreTest {participantRepository,new ObjectMapper(),metadataEncryptionService,- certificateSubmissionValidator);+ certificateSubmissionValidator,+ eventPublisher);}private WorkflowSession activeSession() {@@ -216,6 +223,7 @@ class WorkflowParticipantControllerMoreTest {.isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode()).isEqualTo(HttpStatus.CONFLICT);+ verifyNoInteractions(eventPublisher);}@Test@@ -244,6 +252,7 @@ class WorkflowParticipantControllerMoreTest {assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);assertThat(p.getStatus()).isEqualTo(ParticipantStatus.SIGNED);+ verify(eventPublisher).publishEvent(new SigningResponseEvent(5L, null));}}@@ -290,6 +299,7 @@ class WorkflowParticipantControllerMoreTest {assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);assertThat(p.getStatus()).isEqualTo(ParticipantStatus.DECLINED);verify(workflowSessionService).addParticipantNotification(5L, "Declined: not me");+ verify(eventPublisher).publishEvent(new SigningResponseEvent(5L, "not me"));}@Test@@ -302,6 +312,7 @@ class WorkflowParticipantControllerMoreTest {controller.declineParticipation(TOKEN, null);verify(workflowSessionService).addParticipantNotification(5L, "Declined participation");+ verify(eventPublisher).publishEvent(new SigningResponseEvent(5L, null));}}@@ -314,8 +325,9 @@ class WorkflowParticipantControllerMoreTest {class GetDocument {@Test- void invalidToken_throwsForbidden() {- when(participantRepository.findByShareToken("bad")).thenReturn(Optional.empty());+ void rejectedToken_propagatesTheServiceStatus() throws Exception {+ when(workflowSessionService.getParticipantDocument("bad"))+ .thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN));assertThatThrownBy(() -> controller.getDocument("bad")).isInstanceOf(ResponseStatusException.class)@@ -324,27 +336,29 @@ class WorkflowParticipantControllerMoreTest {}@Test- void expiredParticipant_throwsForbidden() {- WorkflowParticipant p = participant(ParticipantStatus.PENDING);- p.setExpiresAt(java.time.LocalDateTime.now().minusDays(1));- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));-- assertThatThrownBy(() -> controller.getDocument(TOKEN))- .isInstanceOf(ResponseStatusException.class)- .extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.FORBIDDEN);- }-- @Test- void validParticipant_returnsPdf() throws Exception {- WorkflowParticipant p = participant(ParticipantStatus.PENDING);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));- when(workflowSessionService.getOriginalFile("s1")).thenReturn(new byte[] {1, 2, 3});+ void returnsTheServiceDocumentUnderItsFilename() throws Exception {+ when(workflowSessionService.getParticipantDocument(TOKEN))+ .thenReturn(+ new WorkflowSessionService.ParticipantDocument(+ new byte[] {1, 2, 3}, "doc_shared_signed.pdf"));ResponseEntity<byte[]> response = controller.getDocument(TOKEN);assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);assertThat(response.getBody()).containsExactly(1, 2, 3);+ assertThat(response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION))+ .contains("doc_shared_signed.pdf");+ }++ @Test+ void unreadableDocument_isServerError() throws Exception {+ when(workflowSessionService.getParticipantDocument(TOKEN))+ .thenThrow(new IOException("disk gone"));++ assertThatThrownBy(() -> controller.getDocument(TOKEN))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);}}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantValidateCertificateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantValidateCertificateTest.javaindex 695612abdc..7c688d72f3 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantValidateCertificateTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantValidateCertificateTest.java@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.http.HttpStatus;import org.springframework.mock.web.MockMultipartFile;import org.springframework.test.web.servlet.MockMvc;@@ -37,6 +38,7 @@ class WorkflowParticipantValidateCertificateTest {@Mock private WorkflowParticipantRepository participantRepository;@Mock private MetadataEncryptionService metadataEncryptionService;@Mock private CertificateSubmissionValidator certificateSubmissionValidator;+ @Mock private ApplicationEventPublisher eventPublisher;private MockMvc mockMvc;@@ -51,7 +53,8 @@ class WorkflowParticipantValidateCertificateTest {participantRepository,new ObjectMapper(),metadataEncryptionService,- certificateSubmissionValidator);+ certificateSubmissionValidator,+ eventPublisher);mockMvc = MockMvcBuilders.standaloneSetup(controller).build();}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/dto/ParticipantRequestTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/dto/ParticipantRequestTest.javanew file mode 100644index 0000000000..49829f8809--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/dto/ParticipantRequestTest.java@@ -0,0 +1,31 @@+package stirling.software.proprietary.workflow.dto;++import static org.assertj.core.api.Assertions.assertThat;++import org.junit.jupiter.api.Test;++import tools.jackson.databind.ObjectMapper;++class ParticipantRequestTest {++ private final ObjectMapper mapper = new ObjectMapper();++ @Test+ void omittedSendNotificationDefaultsToTrue() {+ ParticipantRequest request =+ mapper.readValue("{\"email\":\"[email protected]\"}", ParticipantRequest.class);++ assertThat(request.isSendNotification()).isTrue();+ assertThat(request.getEmail()).isEqualTo("[email protected]");+ }++ @Test+ void explicitFalseIsKept() {+ ParticipantRequest request =+ mapper.readValue(+ "{\"email\":\"[email protected]\",\"sendNotification\":false}",+ ParticipantRequest.class);++ assertThat(request.isSendNotification()).isFalse();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningEmailTemplatesTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningEmailTemplatesTest.javanew file mode 100644index 0000000000..5000b972fe--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningEmailTemplatesTest.java@@ -0,0 +1,356 @@+package stirling.software.proprietary.workflow.notification;++import static org.assertj.core.api.Assertions.assertThat;++import java.util.List;+import java.util.stream.IntStream;++import org.junit.jupiter.api.Nested;+import org.junit.jupiter.api.Test;++import stirling.software.proprietary.security.service.EmailService;+import stirling.software.proprietary.workflow.model.ParticipantStatus;+import stirling.software.proprietary.workflow.notification.SigningEmailTemplates.Email;+import stirling.software.proprietary.workflow.notification.SigningEmailTemplates.Summary;++class SigningEmailTemplatesTest {++ private static final String LINK = "https://pdf.example.com/shared-sign";++ private static Summary summary(int participants, int signed, int declined, String... awaiting) {+ return new Summary(+ "Contract.pdf",+ "[email protected]",+ null,+ null,+ participants,+ signed,+ declined,+ List.of(awaiting));+ }++ @Nested+ class Invitation {++ @Test+ void carriesTheBrandLockupAndABrandColouredCta() {+ String html =+ SigningEmailTemplates.invitation(+ "[email protected]", summary(1, 0, 0, "Bob"), LINK, false)+ .html();++ assertThat(html)+ .contains("src=\"cid:" + EmailService.BRAND_LOGO_CONTENT_ID + "\"")+ .contains("alt=\"Stirling\"")+ .contains("background-color:#af3434")+ .doesNotContain("#007bff");+ }++ @Test+ void namesTheRequesterAndDocumentAndLinksToSigning() {+ Email email =+ SigningEmailTemplates.invitation(+ "[email protected]", summary(2, 0, 0, "Bob", "Carol"), LINK, false);++ assertThat(email.to()).isEqualTo("[email protected]");+ assertThat(email.subject())+ .isEqualTo("[email protected] requested your signature on \"Contract.pdf\"");+ assertThat(email.html())+ .contains("[email protected] has asked you to sign")+ .contains("<strong>Contract.pdf</strong>")+ .contains("href=\"" + LINK + "\"")+ .contains("Review and sign")+ .doesNotContain("do not forward");+ }++ @Test+ void guestLinkWarnsThatItActsAsTheParticipant() {+ Email email =+ SigningEmailTemplates.invitation(+ "[email protected]",+ summary(1, 0, 0, "[email protected]"),+ "https://pdf.example.com/workflow/sign/token-1",+ true);++ assertThat(email.html())+ .contains("href=\"https://pdf.example.com/workflow/sign/token-1\"")+ .contains("do not forward this email");+ }++ @Test+ void includesTheOwnersMessageAndDueDate() {+ Summary summary =+ new Summary(+ "Contract.pdf",+ "[email protected]",+ "Please sign\nby Friday",+ "2026-10-15",+ 1,+ 0,+ 0,+ List.of("Bob"));++ String html =+ SigningEmailTemplates.invitation("[email protected]", summary, LINK, false)+ .html();++ assertThat(html)+ .contains("Message from [email protected]:")+ .contains("Please sign<br>by Friday")+ .contains("Please sign by 2026-10-15.");+ }++ @Test+ void withoutALinkTellsTheParticipantWhereToFindIt() {+ String html =+ SigningEmailTemplates.invitation(+ "[email protected]", summary(1, 0, 0, "Bob"), null, false)+ .html();++ assertThat(html).contains("open Shared Signing to review it").doesNotContain("<a href");+ }+ }++ @Nested+ class Response {++ @Test+ void signatureWithOthersOutstandingReportsWhoIsLeft() {+ Email email =+ SigningEmailTemplates.response(+ "[email protected]",+ summary(3, 1, 0, "Bob", "Carol"),+ "Alice",+ true,+ null,+ LINK);++ assertThat(email.subject()).isEqualTo("Alice signed \"Contract.pdf\"");+ assertThat(email.html())+ .contains("New signature")+ .contains("Alice signed <strong>Contract.pdf</strong>.")+ .contains("Signed: 1 of 3")+ .contains("Awaiting: 2 (Bob, Carol)")+ .contains("You can finalize now, but anyone who has not signed yet")+ .contains("Open Shared Signing")+ .doesNotContain("Declined:");+ }++ @Test+ void lastSignatureMarksTheDocumentReady() {+ Email email =+ SigningEmailTemplates.response(+ "[email protected]", summary(2, 2, 0), "Alice", true, null, LINK);++ assertThat(email.subject()).isEqualTo("\"Contract.pdf\" is ready to finalize");+ assertThat(email.html())+ .contains("Ready to finalize")+ .contains("Signed: 2 of 2")+ .contains("Everyone has responded, so the document is ready to finalize.")+ .contains("Review and finalize")+ .doesNotContain("Awaiting:");+ }++ @Test+ void lastResponseBeingADeclineStillMarksTheDocumentReady() {+ Email email =+ SigningEmailTemplates.response(+ "[email protected]", summary(2, 1, 1), "Bob", false, null, LINK);++ assertThat(email.subject()).isEqualTo("\"Contract.pdf\" is ready to finalize");+ assertThat(email.html())+ .contains("Bob declined to sign <strong>Contract.pdf</strong>.")+ .contains("Declined: 1")+ .contains("ready to finalize");+ }++ @Test+ void declineShowsTheParticipantsReason() {+ Email email =+ SigningEmailTemplates.response(+ "[email protected]",+ summary(3, 0, 1, "Carol", "Dan"),+ "Bob",+ false,+ "Wrong entity name",+ LINK);++ assertThat(email.subject()).isEqualTo("Bob declined to sign \"Contract.pdf\"");+ assertThat(email.html())+ .contains("Signature declined")+ .contains("Their reason:")+ .contains("Wrong entity name")+ .contains("The document can be finalized once someone signs.");+ }++ @Test+ void everyoneDecliningLeavesNothingToFinalize() {+ String html =+ SigningEmailTemplates.response(+ "[email protected]", summary(1, 0, 1), "Bob", false, null, LINK)+ .html();++ assertThat(html)+ .contains("Everyone declined, so there is nothing to finalize.")+ .doesNotContain("Their reason:");+ }++ @Test+ void longAwaitingListsAreShortened() {+ String[] names =+ IntStream.rangeClosed(1, 12).mapToObj(i -> "P" + i).toArray(String[]::new);++ String html =+ SigningEmailTemplates.response(+ "[email protected]",+ summary(13, 1, 0, names),+ "Alice",+ true,+ null,+ LINK)+ .html();++ assertThat(html).contains("Awaiting: 12 (P1, P2").contains("P10 and 2 more)");+ assertThat(html).doesNotContain("P11");+ }+ }++ @Nested+ class Completion {++ @Test+ void signerIsToldTheirSignatureIsIncluded() {+ Email email =+ SigningEmailTemplates.completion(+ "[email protected]",+ summary(3, 2, 1),+ ParticipantStatus.SIGNED,+ LINK,+ false);++ assertThat(email.subject()).isEqualTo("\"Contract.pdf\" has been finalized");+ assertThat(email.html())+ .contains("[email protected] finalized <strong>Contract.pdf</strong>.")+ .contains("Signatures included: 2 of 3")+ .contains("Your signature is included.")+ .contains("View signed document");+ }++ @Test+ void decliningParticipantIsToldTheirSignatureIsNotIncluded() {+ String html =+ SigningEmailTemplates.completion(+ "[email protected]",+ summary(2, 1, 1),+ ParticipantStatus.DECLINED,+ LINK,+ false)+ .html();++ assertThat(html).contains("You declined this request");+ }++ @Test+ void participantWhoNeverRespondedIsToldTheRequestClosed() {+ String html =+ SigningEmailTemplates.completion(+ "[email protected]",+ summary(2, 1, 0, "Bob"),+ ParticipantStatus.VIEWED,+ null,+ false)+ .html();++ assertThat(html)+ .contains("The request closed before you signed")+ .contains("open Shared Signing to download the signed document");+ }++ @Test+ void guestLinkWarnsThatItOpensTheSignedDocument() {+ String html =+ SigningEmailTemplates.completion(+ "[email protected]",+ summary(2, 2, 0),+ ParticipantStatus.SIGNED,+ "https://pdf.example.com/workflow/sign/token-1",+ true)+ .html();++ assertThat(html)+ .contains("href=\"https://pdf.example.com/workflow/sign/token-1\"")+ .contains("opens the signed document for anyone who has it");+ }+ }++ @Nested+ class UntrustedInput {++ @Test+ void bodyEscapesHtmlFromUsers() {+ Summary summary =+ new Summary(+ "<img src=x onerror=alert(1)>.pdf",+ "a&b <owner>",+ "<script>steal()</script>",+ null,+ 1,+ 0,+ 0,+ List.of("<b>Bob</b>"));++ String html =+ SigningEmailTemplates.invitation("[email protected]", summary, LINK, false)+ .html();++ assertThat(html)+ .doesNotContain("<img src=x")+ .doesNotContain("<script>")+ .doesNotContain("<owner>")+ .contains("<img src=x onerror=alert(1)>.pdf")+ .contains("a&b <owner>")+ .contains("<script>steal()</script>");+ }++ @Test+ void subjectCannotCarryAHeaderBreak() {+ Summary summary =+ new Summary(+ "Contract.pdf\r\nBcc: [email protected]",+ "owner\[email protected]",+ null,+ null,+ 1,+ 0,+ 0,+ List.of("Bob"));++ String subject =+ SigningEmailTemplates.invitation("[email protected]", summary, LINK, false)+ .subject();++ assertThat(subject).doesNotContain("\r").doesNotContain("\n");+ assertThat(subject)+ .isEqualTo(+ "owner @example.com requested your signature on \"Contract.pdf Bcc:"+ + " [email protected]\"");+ }++ @Test+ void longDocumentNamesAreTruncatedInTheSubject() {+ String longName = "A".repeat(200) + ".pdf";+ Summary summary = new Summary(longName, "owner", null, null, 1, 1, 0, List.of());++ String subject =+ SigningEmailTemplates.completion(+ "[email protected]",+ summary,+ ParticipantStatus.SIGNED,+ LINK,+ false)+ .subject();++ assertThat(subject).isEqualTo("\"" + "A".repeat(77) + "...\" has been finalized");+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningNotificationListenerDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningNotificationListenerDbTest.javanew file mode 100644index 0000000000..1de6cf10bc--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningNotificationListenerDbTest.java@@ -0,0 +1,268 @@+package stirling.software.proprietary.workflow.notification;++import static org.assertj.core.api.Assertions.assertThatCode;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.contains;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.reset;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;++import java.util.UUID;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.boot.SpringBootConfiguration;+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;+import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;+import org.springframework.boot.persistence.autoconfigure.EntityScan;+import org.springframework.context.ApplicationEventPublisher;+import org.springframework.context.annotation.Bean;+import org.springframework.context.annotation.Import;+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;+import org.springframework.test.context.TestPropertySource;+import org.springframework.transaction.PlatformTransactionManager;+import org.springframework.transaction.annotation.Propagation;+import org.springframework.transaction.annotation.Transactional;+import org.springframework.transaction.support.TransactionTemplate;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.EmailService;+import stirling.software.proprietary.storage.model.ShareAccessRole;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.repository.StoredFileRepository;+import stirling.software.proprietary.workflow.model.ParticipantStatus;+import stirling.software.proprietary.workflow.model.WorkflowParticipant;+import stirling.software.proprietary.workflow.model.WorkflowSession;+import stirling.software.proprietary.workflow.model.WorkflowStatus;+import stirling.software.proprietary.workflow.model.WorkflowType;+import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;+import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;++/**+ * Drives the listener through real Spring transactions and Hibernate: mail goes out only after+ * commit, never after a rollback, and the session graph is reloaded rather than read from the+ * publisher's detached entities.+ */+@DataJpaTest+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)+@Import(SigningNotificationListener.class)+@Transactional(propagation = Propagation.NOT_SUPPORTED)+// H2 has no jsonb type; the domain lets the workflow entities build their schema here.+@TestPropertySource(+ properties = {+ "spring.datasource.url=jdbc:h2:mem:signingnotify;DB_CLOSE_DELAY=-1;INIT=CREATE DOMAIN"+ + " IF NOT EXISTS JSONB AS JSON",+ "spring.datasource.driver-class-name=org.h2.Driver",+ "spring.datasource.username=sa",+ "spring.datasource.password=",+ "mail.enabled=true"+ })+class SigningNotificationListenerDbTest {++ @Autowired private ApplicationEventPublisher publisher;+ @Autowired private PlatformTransactionManager transactionManager;+ @Autowired private EmailService emailService;+ @Autowired private UserRepository userRepository;+ @Autowired private StoredFileRepository storedFileRepository;+ @Autowired private WorkflowSessionRepository sessionRepository;+ @Autowired private WorkflowParticipantRepository participantRepository;++ @BeforeEach+ void clear() {+ reset(emailService);+ inTransaction(+ () -> {+ sessionRepository.deleteAll();+ storedFileRepository.deleteAll();+ userRepository.deleteAll();+ });+ }++ @Test+ void ownerIsEmailedOnlyOnceTheSignatureCommits() throws Exception {+ Long signerId = seedSession().signerId();++ inTransaction(+ () -> {+ markSigned(signerId);+ publisher.publishEvent(new SigningResponseEvent(signerId, null));+ verifyNoInteractions(emailService);+ });++ verify(emailService)+ .sendBrandedEmail(+ eq("[email protected]"),+ eq("[email protected] signed \"Contract.pdf\""),+ contains("Signed: 1 of 2"));+ }++ @Test+ void rolledBackSignatureSendsNothing() {+ Long signerId = seedSession().signerId();++ new TransactionTemplate(transactionManager)+ .executeWithoutResult(+ status -> {+ markSigned(signerId);+ publisher.publishEvent(new SigningResponseEvent(signerId, null));+ status.setRollbackOnly();+ });++ verifyNoInteractions(emailService);+ }++ @Test+ void publishedWithoutATransactionItLoadsTheSessionItself() throws Exception {+ Long signerId = seedSession().signerId();+ inTransaction(() -> markSigned(signerId));++ publisher.publishEvent(new SigningResponseEvent(signerId, null));++ verify(emailService)+ .sendBrandedEmail(+ eq("[email protected]"),+ anyString(),+ contains("Awaiting: 1 ([email protected])"));+ }++ @Test+ void completionReachesEachParticipantThroughTheirOwnLink() throws Exception {+ Seeded seeded = seedSession();+ inTransaction(+ () -> {+ markSigned(seeded.signerId());+ WorkflowSession session =+ sessionRepository.findBySessionId(seeded.sessionId()).orElseThrow();+ session.setFinalized(true);+ session.setStatus(WorkflowStatus.COMPLETED);+ sessionRepository.save(session);+ });++ publisher.publishEvent(new SigningCompletionEvent(seeded.sessionId()));++ verify(emailService)+ .sendBrandedEmail(+ eq("[email protected]"),+ eq("\"Contract.pdf\" has been finalized"),+ contains("https://pdf.example.com/shared-sign"));+ verify(emailService)+ .sendBrandedEmail(+ eq("[email protected]"),+ anyString(),+ contains("https://pdf.example.com/workflow/sign/" + seeded.guestToken()));+ verify(emailService, never())+ .sendBrandedEmail(eq("[email protected]"), anyString(), anyString());+ }++ @Test+ void failingMailServerNeverFailsTheAction() throws Exception {+ Long signerId = seedSession().signerId();+ inTransaction(() -> markSigned(signerId));+ doThrow(new IllegalStateException("smtp down"))+ .when(emailService)+ .sendBrandedEmail(anyString(), anyString(), anyString());++ assertThatCode(() -> publisher.publishEvent(new SigningResponseEvent(signerId, null)))+ .doesNotThrowAnyException();+ assertThatCode(+ () ->+ inTransaction(+ () ->+ publisher.publishEvent(+ new SigningResponseEvent(signerId, null))))+ .doesNotThrowAnyException();+ }++ private record Seeded(String sessionId, Long signerId, String guestToken) {}++ /** An owner, a signed-in participant (alice) and a guest, all still pending. */+ private Seeded seedSession() {+ return new TransactionTemplate(transactionManager)+ .execute(+ status -> {+ User owner = saveUser("[email protected]");+ StoredFile file = new StoredFile();+ file.setOwner(owner);+ file.setOriginalFilename("Contract.pdf");+ file.setStorageKey("key-" + UUID.randomUUID());+ storedFileRepository.save(file);++ WorkflowSession session = new WorkflowSession();+ session.setOwner(owner);+ session.setWorkflowType(WorkflowType.SIGNING);+ session.setDocumentName("Contract.pdf");+ session.setOriginalFile(file);+ WorkflowParticipant signer =+ participant(saveUser("[email protected]"), "[email protected]");+ WorkflowParticipant guest = participant(null, "[email protected]");+ session.addParticipant(signer);+ session.addParticipant(guest);+ sessionRepository.save(session);+ return new Seeded(+ session.getSessionId(), signer.getId(), guest.getShareToken());+ });+ }++ private User saveUser(String username) {+ User user = new User();+ user.setUsername(username);+ user.setPassword("x");+ return userRepository.save(user);+ }++ private static WorkflowParticipant participant(User account, String email) {+ WorkflowParticipant participant = new WorkflowParticipant();+ participant.setUser(account);+ participant.setEmail(email);+ participant.setName(email);+ participant.setShareToken(UUID.randomUUID().toString());+ participant.setAccessRole(ShareAccessRole.EDITOR);+ return participant;+ }++ private void markSigned(Long participantId) {+ WorkflowParticipant participant =+ participantRepository.findById(participantId).orElseThrow();+ participant.setStatus(ParticipantStatus.SIGNED);+ participantRepository.save(participant);+ }++ private void inTransaction(Runnable work) {+ new TransactionTemplate(transactionManager).executeWithoutResult(status -> work.run());+ }++ @SpringBootConfiguration+ @EntityScan(+ basePackages = {+ "stirling.software.proprietary.workflow.model",+ "stirling.software.proprietary.storage.model",+ "stirling.software.proprietary.security.model",+ "stirling.software.proprietary.model"+ })+ @EnableJpaRepositories(+ basePackages = {+ "stirling.software.proprietary.workflow.repository",+ "stirling.software.proprietary.storage.repository",+ "stirling.software.proprietary.security.database.repository"+ })+ static class TestApp {+ @Bean+ EmailService emailService() {+ return mock(EmailService.class);+ }++ @Bean+ ApplicationProperties applicationProperties() {+ ApplicationProperties properties = new ApplicationProperties();+ properties.getSystem().setFrontendUrl("https://pdf.example.com");+ return properties;+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningNotificationListenerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningNotificationListenerTest.javanew file mode 100644index 0000000000..a1be5b154b--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/notification/SigningNotificationListenerTest.java@@ -0,0 +1,475 @@+package stirling.software.proprietary.workflow.notification;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatCode;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.argThat;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.atLeast;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.time.LocalDateTime;+import java.util.ArrayList;+import java.util.List;+import java.util.Optional;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Nested;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.transaction.PlatformTransactionManager;+import org.springframework.transaction.TransactionDefinition;+import org.springframework.transaction.support.SimpleTransactionStatus;++import jakarta.mail.MessagingException;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.EmailService;+import stirling.software.proprietary.storage.model.ShareAccessRole;+import stirling.software.proprietary.workflow.model.ParticipantStatus;+import stirling.software.proprietary.workflow.model.WorkflowParticipant;+import stirling.software.proprietary.workflow.model.WorkflowSession;+import stirling.software.proprietary.workflow.model.WorkflowStatus;+import stirling.software.proprietary.workflow.model.WorkflowType;+import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;+import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;++@ExtendWith(MockitoExtension.class)+class SigningNotificationListenerTest {++ private static final String BASE = "https://pdf.example.com";++ @Mock private EmailService emailService;+ @Mock private WorkflowSessionRepository sessionRepository;+ @Mock private WorkflowParticipantRepository participantRepository;+ @Mock private PlatformTransactionManager transactionManager;++ private final ApplicationProperties properties = new ApplicationProperties();+ private SigningNotificationListener listener;+ private User owner;+ private WorkflowSession session;++ private record Sent(String to, String subject, String html) {}++ @BeforeEach+ void setUp() {+ lenient()+ .when(transactionManager.getTransaction(any()))+ .thenReturn(new SimpleTransactionStatus());+ properties.getSystem().setFrontendUrl(BASE + "/");+ listener =+ new SigningNotificationListener(+ emailService,+ properties,+ sessionRepository,+ participantRepository,+ transactionManager);+ owner = user(1L, "[email protected]");+ session = new WorkflowSession();+ session.setSessionId("s1");+ session.setOwner(owner);+ session.setWorkflowType(WorkflowType.SIGNING);+ session.setDocumentName("Contract.pdf");+ session.setStatus(WorkflowStatus.IN_PROGRESS);+ }++ private static User user(long id, String username) {+ User user = new User();+ user.setId(id);+ user.setUsername(username);+ return user;+ }++ private WorkflowParticipant participant(+ long id, User account, String email, ParticipantStatus status) {+ WorkflowParticipant participant = new WorkflowParticipant();+ participant.setId(id);+ participant.setUser(account);+ participant.setEmail(email);+ participant.setName(account != null ? account.getUsername() : email);+ participant.setStatus(status);+ participant.setShareToken("token-" + id);+ participant.setAccessRole(ShareAccessRole.EDITOR);+ session.addParticipant(participant);+ return participant;+ }++ private void sessionIsStored() {+ when(sessionRepository.findBySessionIdWithParticipants("s1"))+ .thenReturn(Optional.of(session));+ }++ private void participantIsStored(WorkflowParticipant participant) {+ when(participantRepository.findById(participant.getId()))+ .thenReturn(Optional.of(participant));+ }++ private List<Sent> sent() throws MessagingException {+ ArgumentCaptor<String> to = ArgumentCaptor.forClass(String.class);+ ArgumentCaptor<String> subject = ArgumentCaptor.forClass(String.class);+ ArgumentCaptor<String> html = ArgumentCaptor.forClass(String.class);+ verify(emailService, atLeast(0))+ .sendBrandedEmail(to.capture(), subject.capture(), html.capture());+ List<Sent> sent = new ArrayList<>();+ for (int i = 0; i < to.getAllValues().size(); i++) {+ sent.add(+ new Sent(+ to.getAllValues().get(i),+ subject.getAllValues().get(i),+ html.getAllValues().get(i)));+ }+ return sent;+ }++ @Nested+ class Invitation {++ @Test+ void accountHolderGetsALinkToSharedSigningRatherThanTheirToken() throws Exception {+ participant(+ 2L, user(2L, "[email protected]"), "[email protected]", ParticipantStatus.PENDING);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L)));++ List<Sent> sent = sent();+ assertThat(sent).extracting(Sent::to).containsExactly("[email protected]");+ assertThat(sent.get(0).html())+ .contains("href=\"" + BASE + "/shared-sign\"")+ .doesNotContain("token-2");+ }++ @Test+ void guestGetsTheirTokenLink() throws Exception {+ participant(3L, null, "[email protected]", ParticipantStatus.PENDING);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(3L)));++ List<Sent> sent = sent();+ assertThat(sent).extracting(Sent::to).containsExactly("[email protected]");+ assertThat(sent.get(0).html()).contains(BASE + "/workflow/sign/token-3");+ }++ @Test+ void onlyTheParticipantsInTheEventAreInvited() throws Exception {+ participant(+ 2L, user(2L, "[email protected]"), "[email protected]", ParticipantStatus.PENDING);+ participant(3L, null, "[email protected]", ParticipantStatus.VIEWED);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L)));++ assertThat(sent()).extracting(Sent::to).containsExactly("[email protected]");+ }++ @Test+ void ownerAddingThemselvesIsNotInvited() throws Exception {+ participant(2L, owner, "[email protected]", ParticipantStatus.PENDING);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L)));++ verifyNoInteractions(emailService);+ }++ @Test+ void accountEmailWinsAndUsernamesThatAreNotAddressesAreSkipped() throws Exception {+ User bob = user(2L, "bob");+ bob.setEmail("[email protected]");+ participant(2L, bob, "bob", ParticipantStatus.PENDING);+ participant(3L, user(3L, "carol"), "carol", ParticipantStatus.PENDING);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L, 3L)));++ assertThat(sent()).extracting(Sent::to).containsExactly("[email protected]");+ }++ @Test+ void closedSessionsSendNothing() {+ participant(+ 2L, user(2L, "[email protected]"), "[email protected]", ParticipantStatus.PENDING);+ session.setFinalized(true);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L)));++ verifyNoInteractions(emailService);+ }++ @Test+ void expiredGuestIsNotInvited() throws Exception {+ participant(+ 2L, user(2L, "[email protected]"), "[email protected]", ParticipantStatus.PENDING);+ participant(3L, null, "[email protected]", ParticipantStatus.PENDING)+ .setExpiresAt(LocalDateTime.now().minusMinutes(1));+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L, 3L)));++ assertThat(sent()).extracting(Sent::to).containsExactly("[email protected]");+ }++ @Test+ void otherWorkflowTypesSendNothing() {+ participant(+ 2L, user(2L, "[email protected]"), "[email protected]", ParticipantStatus.PENDING);+ session.setWorkflowType(WorkflowType.REVIEW);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L)));++ verifyNoInteractions(emailService);+ }++ @Test+ void withoutAConfiguredUrlGuestsAreSkippedAndAccountHoldersGetNoLink() throws Exception {+ properties.getSystem().setFrontendUrl("");+ properties.getSystem().setBackendUrl(" ");+ participant(+ 2L, user(2L, "[email protected]"), "[email protected]", ParticipantStatus.PENDING);+ participant(3L, null, "[email protected]", ParticipantStatus.PENDING);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L, 3L)));++ List<Sent> sent = sent();+ assertThat(sent).extracting(Sent::to).containsExactly("[email protected]");+ assertThat(sent.get(0).html())+ .doesNotContain("<a href")+ .contains("open Shared Signing");+ }++ @Test+ void fallsBackToTheBackendUrl() throws Exception {+ properties.getSystem().setFrontendUrl(null);+ properties.getSystem().setBackendUrl("http://host:8080");+ participant(+ 2L, user(2L, "[email protected]"), "[email protected]", ParticipantStatus.PENDING);+ sessionIsStored();++ listener.onInvitation(new SigningInvitationEvent("s1", List.of(2L)));++ assertThat(sent().get(0).html()).contains("href=\"http://host:8080/shared-sign\"");+ }+ }++ @Nested+ class Response {++ @Test+ void ownerGetsTheProgressAfterASignature() throws Exception {+ WorkflowParticipant alice =+ participant(+ 2L,+ user(2L, "[email protected]"),+ "[email protected]",+ ParticipantStatus.SIGNED);+ participant(3L, null, "[email protected]", ParticipantStatus.VIEWED);+ participantIsStored(alice);++ listener.onResponse(new SigningResponseEvent(2L, null));++ List<Sent> sent = sent();+ assertThat(sent).extracting(Sent::to).containsExactly("[email protected]");+ assertThat(sent.get(0).subject())+ .isEqualTo("[email protected] signed \"Contract.pdf\"");+ assertThat(sent.get(0).html())+ .contains("Signed: 1 of 2")+ .contains("Awaiting: 1 ([email protected])")+ .contains("href=\"" + BASE + "/shared-sign\"");+ }++ @Test+ void addressGivenForTheSessionWins() throws Exception {+ session.setOwnerEmail("[email protected]");+ WorkflowParticipant alice =+ participant(2L, null, "[email protected]", ParticipantStatus.SIGNED);+ participantIsStored(alice);++ listener.onResponse(new SigningResponseEvent(2L, null));++ assertThat(sent()).extracting(Sent::to).containsExactly("[email protected]");+ }++ @Test+ void declineCarriesTheReasonAndCountsTowardReadiness() throws Exception {+ participant(2L, null, "[email protected]", ParticipantStatus.SIGNED);+ WorkflowParticipant bob =+ participant(3L, null, "[email protected]", ParticipantStatus.DECLINED);+ participantIsStored(bob);++ listener.onResponse(new SigningResponseEvent(3L, "Not my department"));++ Sent sent = sent().get(0);+ assertThat(sent.subject()).isEqualTo("\"Contract.pdf\" is ready to finalize");+ assertThat(sent.html())+ .contains("[email protected] declined to sign")+ .contains("Not my department")+ .contains("Declined: 1");+ }++ @Test+ void ownerIsNotEmailedAboutTheirOwnSignature() {+ WorkflowParticipant self =+ participant(2L, owner, "[email protected]", ParticipantStatus.SIGNED);+ participantIsStored(self);++ listener.onResponse(new SigningResponseEvent(2L, null));++ verifyNoInteractions(emailService);+ }++ @Test+ void participantWhoHasNotRespondedSendsNothing() {+ WorkflowParticipant pending =+ participant(2L, null, "[email protected]", ParticipantStatus.VIEWED);+ participantIsStored(pending);++ listener.onResponse(new SigningResponseEvent(2L, null));++ verifyNoInteractions(emailService);+ }++ @Test+ void ownerWithoutAnAddressIsSkipped() {+ session.setOwner(user(1L, "admin"));+ WorkflowParticipant alice =+ participant(2L, null, "[email protected]", ParticipantStatus.SIGNED);+ participantIsStored(alice);++ listener.onResponse(new SigningResponseEvent(2L, null));++ verifyNoInteractions(emailService);+ }++ @Test+ void removedParticipantSendsNothing() {+ when(participantRepository.findById(9L)).thenReturn(Optional.empty());++ listener.onResponse(new SigningResponseEvent(9L, null));++ verifyNoInteractions(emailService);+ }++ @Test+ void responseAfterFinalizationSendsNothing() {+ WorkflowParticipant late =+ participant(2L, null, "[email protected]", ParticipantStatus.SIGNED);+ session.setFinalized(true);+ session.setStatus(WorkflowStatus.COMPLETED);+ participantIsStored(late);++ listener.onResponse(new SigningResponseEvent(2L, null));++ verifyNoInteractions(emailService);+ }+ }++ @Nested+ class Completion {++ @Test+ void everyParticipantButTheOwnerHearsTheDocumentIsDone() throws Exception {+ participant(2L, owner, "[email protected]", ParticipantStatus.SIGNED);+ participant(+ 3L,+ user(3L, "[email protected]"),+ "[email protected]",+ ParticipantStatus.SIGNED);+ participant(4L, null, "[email protected]", ParticipantStatus.VIEWED);+ session.setFinalized(true);+ session.setStatus(WorkflowStatus.COMPLETED);+ sessionIsStored();++ listener.onCompletion(new SigningCompletionEvent("s1"));++ List<Sent> sent = sent();+ assertThat(sent)+ .extracting(Sent::to)+ .containsExactly("[email protected]", "[email protected]");+ assertThat(sent.get(0).html())+ .contains("Your signature is included.")+ .contains("href=\"" + BASE + "/shared-sign\"");+ assertThat(sent.get(1).html())+ .contains("The request closed before you signed")+ .contains(BASE + "/workflow/sign/token-4")+ .contains("do not forward this email");+ assertThat(sent.get(0).html()).doesNotContain("do not forward");+ }++ @Test+ void expiredGuestIsSkippedBecauseTheirTokenNoLongerOpens() throws Exception {+ User alice = user(3L, "[email protected]");+ participant(3L, alice, "[email protected]", ParticipantStatus.SIGNED)+ .setExpiresAt(LocalDateTime.now().minusDays(1));+ participant(4L, null, "[email protected]", ParticipantStatus.SIGNED)+ .setExpiresAt(LocalDateTime.now().minusDays(1));+ session.setFinalized(true);+ session.setStatus(WorkflowStatus.COMPLETED);+ sessionIsStored();++ listener.onCompletion(new SigningCompletionEvent("s1"));++ assertThat(sent()).extracting(Sent::to).containsExactly("[email protected]");+ }+ }++ @Nested+ class Resilience {++ @Test+ void failedLookupSendsNothingAndDoesNotReachTheCaller() {+ when(sessionRepository.findBySessionIdWithParticipants("s1"))+ .thenThrow(new IllegalStateException("database down"));++ assertThatCode(() -> listener.onCompletion(new SigningCompletionEvent("s1")))+ .doesNotThrowAnyException();+ verifyNoInteractions(emailService);+ }++ @Test+ void oneFailedSendDoesNotStopTheRest() throws Exception {+ participant(2L, null, "[email protected]", ParticipantStatus.PENDING);+ participant(3L, null, "[email protected]", ParticipantStatus.PENDING);+ sessionIsStored();+ lenient()+ .doThrow(new MessagingException("rejected"))+ .when(emailService)+ .sendBrandedEmail(eq("[email protected]"), anyString(), anyString());++ assertThatCode(+ () ->+ listener.onInvitation(+ new SigningInvitationEvent("s1", List.of(2L, 3L))))+ .doesNotThrowAnyException();++ verify(emailService).sendBrandedEmail(eq("[email protected]"), anyString(), anyString());+ }++ @Test+ void readsInAReadOnlyTransactionOfItsOwn() {+ sessionIsStored();++ listener.onCompletion(new SigningCompletionEvent("s1"));++ verify(transactionManager)+ .getTransaction(+ argThat(+ definition ->+ definition.getPropagationBehavior()+ == TransactionDefinition+ .PROPAGATION_REQUIRES_NEW+ && definition.isReadOnly()));+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.javaindex 4c2ea45987..a2cee628c1 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.java@@ -6,6 +6,7 @@ import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;import java.io.IOException;@@ -15,6 +16,7 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;+import java.util.concurrent.atomic.AtomicLong;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;@@ -25,6 +27,7 @@ import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.mockito.junit.jupiter.MockitoSettings;import org.mockito.quality.Strictness;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.core.io.ByteArrayResource;import org.springframework.core.io.Resource;import org.springframework.http.HttpStatus;@@ -44,6 +47,9 @@ import stirling.software.proprietary.workflow.model.ParticipantStatus;import stirling.software.proprietary.workflow.model.WorkflowParticipant;import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.model.WorkflowStatus;+import stirling.software.proprietary.workflow.notification.SigningCompletionEvent;+import stirling.software.proprietary.workflow.notification.SigningInvitationEvent;+import stirling.software.proprietary.workflow.notification.SigningResponseEvent;import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;@@ -68,6 +74,7 @@ class WorkflowSessionServiceMoreTest {@Mock private ApplicationProperties applicationProperties;@Mock private MetadataEncryptionService metadataEncryptionService;@Mock private CertificateSubmissionValidator certificateSubmissionValidator;+ @Mock private ApplicationEventPublisher eventPublisher;@InjectMocks private WorkflowSessionService service;@@ -263,6 +270,53 @@ class WorkflowSessionServiceMoreTest {assertThat(s.getParticipants().get(0).getEmail()).isEqualTo("[email protected]");}+ @Test+ void invitesOnlyParticipantsThatAskForIt() {+ User owner = user("alice", 1L);+ WorkflowSession s = session("s1", owner);+ s.setStatus(WorkflowStatus.IN_PROGRESS);+ when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));+ AtomicLong ids = new AtomicLong(10L);+ when(workflowParticipantRepository.save(any()))+ .thenAnswer(+ i -> {+ WorkflowParticipant saved = i.getArgument(0);+ saved.setId(ids.getAndIncrement());+ return saved;+ });++ ParticipantRequest notified = new ParticipantRequest();+ notified.setEmail("[email protected]");+ ParticipantRequest quiet = new ParticipantRequest();+ quiet.setEmail("[email protected]");+ quiet.setSendNotification(false);++ service.addParticipants("s1", List.of(notified, quiet), owner);++ verify(eventPublisher).publishEvent(new SigningInvitationEvent("s1", List.of(10L)));+ }++ @Test+ void nobodyAsksForAnInvitation_publishesNothing() {+ User owner = user("alice", 1L);+ WorkflowSession s = session("s1", owner);+ s.setStatus(WorkflowStatus.IN_PROGRESS);+ when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));+ when(workflowParticipantRepository.save(any())).thenAnswer(i -> i.getArgument(0));++ ParticipantRequest quiet = new ParticipantRequest();+ quiet.setEmail("[email protected]");+ quiet.setSendNotification(false);++ service.addParticipants("s1", List.of(quiet), owner);++ verifyNoInteractions(eventPublisher);+ }+@Testvoid participantWithoutUserIdOrEmail_throwsBadRequest() {User owner = user("alice", 1L);@@ -432,6 +486,7 @@ class WorkflowSessionServiceMoreTest {.isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode()).isEqualTo(HttpStatus.CONFLICT);+ verifyNoInteractions(eventPublisher);}@Test@@ -447,6 +502,7 @@ class WorkflowSessionServiceMoreTest {assertThat(s.isFinalized()).isTrue();assertThat(s.getStatus()).isEqualTo(WorkflowStatus.COMPLETED);verify(workflowSessionRepository).save(s);+ verify(eventPublisher).publishEvent(new SigningCompletionEvent("s1"));}}@@ -517,6 +573,71 @@ class WorkflowSessionServiceMoreTest {assertThat(service.getOriginalFile("s1")).containsExactly(7);}++ private WorkflowSession sessionWithToken(String token) throws IOException {+ WorkflowSession s = session("s1", user("owner", 2L));+ StoredFile original = new StoredFile();+ original.setStorageKey("orig-key");+ s.setOriginalFile(original);+ WorkflowParticipant p = participant(null, ParticipantStatus.SIGNED);+ p.setShareToken(token);+ s.addParticipant(p);+ when(workflowParticipantRepository.findByShareToken(token)).thenReturn(Optional.of(p));+ when(storageProvider.load("orig-key"))+ .thenReturn(new ByteArrayResource(new byte[] {1}));+ return s;+ }++ @Test+ void getParticipantDocument_beforeFinalize_servesOriginal() throws IOException {+ sessionWithToken("tok");++ WorkflowSessionService.ParticipantDocument document =+ service.getParticipantDocument("tok");++ assertThat(document.content()).containsExactly(1);+ assertThat(document.filename()).isEqualTo("doc.pdf");+ }++ @Test+ void getParticipantDocument_afterFinalize_servesSignedCopy() throws IOException {+ WorkflowSession s = sessionWithToken("tok");+ StoredFile signed = new StoredFile();+ signed.setStorageKey("signed-key");+ signed.setOriginalFilename("doc_shared_signed.pdf");+ s.setProcessedFile(signed);+ s.setFinalized(true);+ when(storageProvider.load("signed-key"))+ .thenReturn(new ByteArrayResource(new byte[] {9}));++ WorkflowSessionService.ParticipantDocument document =+ service.getParticipantDocument("tok");++ assertThat(document.content()).containsExactly(9);+ assertThat(document.filename()).isEqualTo("doc_shared_signed.pdf");+ }++ @Test+ void getParticipantDocument_unknownToken_throwsForbidden() {+ when(workflowParticipantRepository.findByShareToken("nope"))+ .thenReturn(Optional.empty());++ assertThatThrownBy(() -> service.getParticipantDocument("nope"))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ }++ @Test+ void getParticipantDocument_expiredAccess_throwsForbidden() throws IOException {+ WorkflowSession s = sessionWithToken("tok");+ s.getParticipants().get(0).setExpiresAt(LocalDateTime.now().minusDays(1));++ assertThatThrownBy(() -> service.getParticipantDocument("tok"))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ }}// -------------------------------------------------------------------------@@ -726,6 +847,7 @@ class WorkflowSessionServiceMoreTest {.isEqualTo(HttpStatus.CONFLICT);verify(workflowParticipantRepository, never()).save(any());+ verifyNoInteractions(eventPublisher);}@Test@@ -734,6 +856,7 @@ class WorkflowSessionServiceMoreTest {User owner = user("owner", 2L);WorkflowSession s = session("s1", owner);WorkflowParticipant p = participant(user, ParticipantStatus.PENDING);+ p.setId(7L);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));when(workflowSessionRepository.findBySessionIdForUpdate("s1"))@@ -743,6 +866,7 @@ class WorkflowSessionServiceMoreTest {assertThat(p.getStatus()).isEqualTo(ParticipantStatus.DECLINED);verify(workflowParticipantRepository).save(p);+ verify(eventPublisher).publishEvent(new SigningResponseEvent(7L, null));}}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.javaindex faac8a3780..0e03288081 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.java@@ -11,6 +11,7 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;+import java.util.concurrent.atomic.AtomicLong;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -20,6 +21,7 @@ import org.mockito.InOrder;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.http.HttpStatus;import org.springframework.mock.web.MockMultipartFile;import org.springframework.web.server.ResponseStatusException;@@ -43,6 +45,8 @@ import stirling.software.proprietary.workflow.model.WorkflowParticipant;import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.model.WorkflowStatus;import stirling.software.proprietary.workflow.model.WorkflowType;+import stirling.software.proprietary.workflow.notification.SigningInvitationEvent;+import stirling.software.proprietary.workflow.notification.SigningResponseEvent;import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;@@ -59,6 +63,7 @@ class WorkflowSessionServiceTest {@Mock private ObjectMapper objectMapper;@Mock private ApplicationProperties applicationProperties;@Mock private MetadataEncryptionService metadataEncryptionService;+ @Mock private ApplicationEventPublisher eventPublisher;@Mock private LicenseServiceInterface licenseService;@Mock private stirling.software.common.service.CustomPDFDocumentFactory pdfDocumentFactory;@@ -195,6 +200,7 @@ class WorkflowSessionServiceTest {void signDocument_transitionsParticipantToSigned() {User user = user("alice");WorkflowParticipant participant = pendingParticipant(user);+ participant.setId(5L);sessionWithParticipant("s1", participant);when(metadataEncryptionService.encrypt(any())).thenReturn("enc:pw");@@ -209,6 +215,7 @@ class WorkflowSessionServiceTest {ArgumentCaptor.forClass(WorkflowParticipant.class);verify(workflowParticipantRepository).save(captor.capture());assertThat(captor.getValue().getStatus()).isEqualTo(ParticipantStatus.SIGNED);+ verify(eventPublisher).publishEvent(new SigningResponseEvent(5L, null));}// -------------------------------------------------------------------------@@ -271,7 +278,8 @@ class WorkflowSessionServiceTest {realEncryption,validator,licenseService,- pdfDocumentFactory);+ pdfDocumentFactory,+ eventPublisher);User user = user("dave");WorkflowParticipant participant = pendingParticipant(user);@@ -580,6 +588,51 @@ class WorkflowSessionServiceTest {assertThat(captor.getValue().getDocumentName()).isEqualTo("uploaded.pdf");}+ @Test+ void createSession_invitesEveryParticipantOnceSaved() throws IOException {+ MockMultipartFile file =+ new MockMultipartFile("file", "doc.pdf", "application/pdf", new byte[] {1});+ WorkflowCreationRequest request = new WorkflowCreationRequest();+ request.setWorkflowType(WorkflowType.SIGNING);+ request.setParticipantUserIds(List.of(20L));+ request.setParticipantEmails(List.of("[email protected]"));+ when(pdfDocumentFactory.load(+ any(org.springframework.web.multipart.MultipartFile.class), eq(true)))+ .thenAnswer(+ invocation -> {+ var document = new org.apache.pdfbox.pdmodel.PDDocument();+ document.addPage(new org.apache.pdfbox.pdmodel.PDPage());+ return document;+ });++ when(storageProvider.store(any(), any()))+ .thenReturn(+ StoredObject.builder()+ .storageKey("k")+ .originalFilename("doc.pdf")+ .contentType("application/pdf")+ .sizeBytes(1L)+ .build());+ when(storedFileRepository.save(any())).thenReturn(new StoredFile());+ WorkflowSession savedSession = new WorkflowSession();+ savedSession.setSessionId("s-3");+ savedSession.setParticipants(new ArrayList<>());+ when(workflowSessionRepository.save(any())).thenReturn(savedSession);+ when(userRepository.findById(20L)).thenReturn(Optional.of(user("[email protected]")));+ AtomicLong ids = new AtomicLong(100L);+ when(workflowParticipantRepository.save(any()))+ .thenAnswer(+ i -> {+ WorkflowParticipant saved = i.getArgument(0);+ saved.setId(ids.getAndIncrement());+ return saved;+ });++ service.createSession(user("alice"), file, request);++ verify(eventPublisher).publishEvent(new SigningInvitationEvent("s-3", List.of(100L, 101L)));+ }+// -------------------------------------------------------------------------// getSessionForOwner// -------------------------------------------------------------------------