From e873a777bff0043e63de2c8933e36b5f36a1686a Mon Sep 17 00:00:00 2001 From: no84by <50858621+no84by@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:46:21 +0000 Subject: [PATCH] feat: mail the signed document to chosen signers and archive addresses Add the signed_copy_mail policy (disabled by default). When enabled for the requester, a completed request queues one mail per recipient in the notification delivery outbox: - each signer the requester chose with the new sendSignedCopy signer field (a switch in the signer editor); - the optional archive addresses configured in the policy. For an envelope each recipient gets one mail with all of their documents: a signer gets the documents they signed, archive addresses get every document. The delivery key is derived from the request and the recipient, so a repeated completion never mails a recipient twice. The DeliverNotification job reads the signed PDFs at send time. When the documents of one mail exceed 15 MiB, or a signed file cannot be read, the mail links to the validation page instead. Signed-off-by: no84by <50858621+no84by@users.noreply.github.com> --- lib/AppInfo/Application.php | 4 + lib/Controller/RequestSignatureController.php | 2 +- lib/Events/SigningRequestCompletedEvent.php | 4 + lib/Listener/SignedCopyMailListener.php | 43 +++ lib/ResponseDefinitions.php | 2 + lib/Service/File/FileListService.php | 6 + lib/Service/MailService.php | 43 +++ lib/Service/Notification/MailChannel.php | 11 + lib/Service/Notification/MailPayload.php | 2 + .../NotificationEnvelopeCodec.php | 4 + .../Policy/Provider/PolicyProviders.php | 2 + .../SignedCopyMail/SignedCopyMailPolicy.php | 84 +++++ .../SignedCopyMailPolicyValue.php | 79 +++++ lib/Service/RequestSignatureService.php | 21 +- lib/Service/SignedCopyAttachmentProvider.php | 95 ++++++ lib/Service/SignedCopyMailService.php | 167 +++++++++ openapi-full.json | 8 +- openapi.json | 8 +- src/components/Request/IdentifySigner.vue | 23 +- .../RightSidebar/RequestSignatureTab.vue | 2 + src/store/files.js | 2 + .../components/Request/IdentifySigner.spec.ts | 69 ++++ src/tests/store/files.spec.ts | 2 + .../settings/realDefinitions.spec.ts | 2 + .../SignedCopyMailRuleEditor.spec.ts | 78 +++++ .../settings/signed-copy-mail/model.spec.ts | 40 +++ .../signed-copy-mail/realDefinition.spec.ts | 32 ++ src/types/openapi/openapi-full.ts | 4 +- src/types/openapi/openapi.ts | 4 +- .../settings/realDefinitions.ts | 2 + .../SignedCopyMailRuleEditor.vue | 107 ++++++ .../settings/signed-copy-mail/model.ts | 99 ++++++ .../signed-copy-mail/realDefinition.ts | 67 ++++ .../Unit/Listener/MailNotifyListenerTest.php | 3 +- .../Listener/SignedCopyMailListenerTest.php | 63 ++++ .../Unit/Service/File/FileListServiceTest.php | 25 ++ tests/php/Unit/Service/MailServiceTest.php | 68 ++++ .../Notification/NotificationChannelsTest.php | 27 +- .../SignedCopyMailPolicyTest.php | 50 +++ .../SignedCopyMailPolicyValueTest.php | 57 ++++ .../Service/RequestSignatureServiceTest.php | 82 +++++ .../SignedCopyAttachmentProviderTest.php | 125 +++++++ .../Service/SignedCopyMailServiceTest.php | 321 ++++++++++++++++++ 43 files changed, 1928 insertions(+), 11 deletions(-) create mode 100644 lib/Listener/SignedCopyMailListener.php create mode 100644 lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicy.php create mode 100644 lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicyValue.php create mode 100644 lib/Service/SignedCopyAttachmentProvider.php create mode 100644 lib/Service/SignedCopyMailService.php create mode 100644 src/tests/views/Settings/PolicyWorkbench/settings/signed-copy-mail/SignedCopyMailRuleEditor.spec.ts create mode 100644 src/tests/views/Settings/PolicyWorkbench/settings/signed-copy-mail/model.spec.ts create mode 100644 src/tests/views/Settings/PolicyWorkbench/settings/signed-copy-mail/realDefinition.spec.ts create mode 100644 src/views/Settings/PolicyWorkbench/settings/signed-copy-mail/SignedCopyMailRuleEditor.vue create mode 100644 src/views/Settings/PolicyWorkbench/settings/signed-copy-mail/model.ts create mode 100644 src/views/Settings/PolicyWorkbench/settings/signed-copy-mail/realDefinition.ts create mode 100644 tests/php/Unit/Listener/SignedCopyMailListenerTest.php create mode 100644 tests/php/Unit/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicyTest.php create mode 100644 tests/php/Unit/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicyValueTest.php create mode 100644 tests/php/Unit/Service/SignedCopyAttachmentProviderTest.php create mode 100644 tests/php/Unit/Service/SignedCopyMailServiceTest.php diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index a39c0636fb..a5243e8a81 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -15,6 +15,7 @@ use OCA\Libresign\Events\SendSignNotificationEvent; use OCA\Libresign\Events\SignatureRejectedEvent; use OCA\Libresign\Events\SignedEvent; +use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Events\SignRequestCanceledEvent; use OCA\Libresign\Files\TemplateLoader; use OCA\Libresign\Listener\BeforeNodeDeletedListener; @@ -22,6 +23,7 @@ use OCA\Libresign\Listener\MailNotifyListener; use OCA\Libresign\Listener\NotificationListener; use OCA\Libresign\Listener\RevokeClickToSignCertificateListener; +use OCA\Libresign\Listener\SignedCopyMailListener; use OCA\Libresign\Listener\TwofactorGatewayListener; use OCA\Libresign\Listener\UserDeletedListener; use OCA\Libresign\Middleware\GlobalInjectionMiddleware; @@ -98,6 +100,8 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(SignedEvent::class, NotificationEventRouter::class); $context->registerEventListener(SignRequestCanceledEvent::class, NotificationEventRouter::class); + $context->registerEventListener(SigningRequestCompletedEvent::class, SignedCopyMailListener::class); + $context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class); $context->registerDashboardWidget(PendingSignaturesWidget::class); diff --git a/lib/Controller/RequestSignatureController.php b/lib/Controller/RequestSignatureController.php index 4d27495eca..1ba5e0439b 100644 --- a/lib/Controller/RequestSignatureController.php +++ b/lib/Controller/RequestSignatureController.php @@ -60,7 +60,7 @@ public function __construct( * For `nodeType=file`, `filesCount=1` and `files` contains the current file. * For `nodeType=envelope`, `files` contains envelope child files. * - * @param list $signers Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired + * @param list $signers Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired, sendSignedCopy * @param string $name The name of file to sign * @param LibresignFolderSettings $settings Settings to define how and where the file should be stored * @param LibresignNewFile $file File object. Supports nodeId (a non-negative integer or its canonical decimal string, as Nextcloud node ids can exceed a JavaScript number), url, base64 or path. diff --git a/lib/Events/SigningRequestCompletedEvent.php b/lib/Events/SigningRequestCompletedEvent.php index 8fc5013b5d..ba1b70e736 100644 --- a/lib/Events/SigningRequestCompletedEvent.php +++ b/lib/Events/SigningRequestCompletedEvent.php @@ -35,6 +35,10 @@ public static function fromTransition(FileEntity $request, int $previousStatus): return new self($request->getUuid(), $request->isEnvelope() ? 'envelope' : 'document'); } + public function getRequestUuid(): string { + return $this->requestUuid; + } + #[\Override] public function getWebhookSerializable(): array { return [ diff --git a/lib/Listener/SignedCopyMailListener.php b/lib/Listener/SignedCopyMailListener.php new file mode 100644 index 0000000000..2116219057 --- /dev/null +++ b/lib/Listener/SignedCopyMailListener.php @@ -0,0 +1,43 @@ + + */ +final class SignedCopyMailListener implements IEventListener { + public function __construct( + private FileMapper $fileMapper, + private SignedCopyMailService $signedCopyMailService, + ) { + } + + #[\Override] + public function handle(Event $event): void { + if (!$event instanceof SigningRequestCompletedEvent) { + return; + } + try { + $file = $this->fileMapper->getByUuid($event->getRequestUuid()); + } catch (DoesNotExistException) { + return; + } + $this->signedCopyMailService->queue($file); + } +} diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 81fe277cdf..b066b4a32f 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -110,6 +110,7 @@ * status?: int, * participantRole?: LibresignParticipantRole, * deviceGeolocationRequired?: bool, + * sendSignedCopy?: bool, * } * @psalm-type LibresignNewFile = array{ * base64?: string, @@ -271,6 +272,7 @@ * uid?: string, * metadata?: LibresignSignerMetadata, * rejection?: LibresignSignerRejection, + * sendSignedCopy?: bool, * } * * Notification delivery status diff --git a/lib/Service/File/FileListService.php b/lib/Service/File/FileListService.php index c2ccf344d4..253e924589 100644 --- a/lib/Service/File/FileListService.php +++ b/lib/Service/File/FileListService.php @@ -30,6 +30,7 @@ use OCA\Libresign\Service\IdentifyMethodService; use OCA\Libresign\Service\SignatureRejection\RejectionViewer; use OCA\Libresign\Service\SignatureRejection\SignatureRejectionVisibilityService; +use OCA\Libresign\Service\SignedCopyMailService; use OCA\Libresign\Service\SignerGeolocation\SignerGeolocationMetadataValidator; use OCA\Libresign\Service\SignerGeolocation\SignerGeolocationPolicyService; use OCP\AppFramework\Db\DoesNotExistException; @@ -508,6 +509,11 @@ private function formatSignerData( $data['metadata'] = $geolocationMetadata; } + if ($requesterUserId !== '' && $user?->getUID() === $requesterUserId + && ($signer->getMetadata()[SignedCopyMailService::METADATA_KEY] ?? false) === true) { + $data['sendSignedCopy'] = true; + } + /** @var LibresignSignerDetail $data */ $data = $this->signatureRejectionVisibilityService->presentSigner( $signer, diff --git a/lib/Service/MailService.php b/lib/Service/MailService.php index c70a09b23d..295ad42d38 100644 --- a/lib/Service/MailService.php +++ b/lib/Service/MailService.php @@ -356,6 +356,49 @@ public function notifySignedUser(SignRequest $signRequest, string $email, File $ } } + /** + * Sends the fully signed documents of a completed request. Without + * attachments the mail links to the validation page instead. + * + * @param array $attachments file name => PDF content + */ + public function notifySignedCopy(File $request, string $email, string $displayName, array $attachments): void { + $emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail'); + // TRANSLATORS Email subject sent with the fully signed document after every participant signed. %s is the document or envelope name. + $emailTemplate->setSubject($this->l10n->t('LibreSign: "%s" has been signed by everyone', [$request->getName()])); + $emailTemplate->addHeader(); + // TRANSLATORS Email heading shown when every participant signed the document. + $emailTemplate->addHeading($this->l10n->t('Signed document'), false); + if ($attachments !== []) { + $emailTemplate->addBodyText($this->l10n->n( + // TRANSLATORS Email body sent with the fully signed document attached. %s is the document or envelope name. + 'All signatures on "%s" are complete. The signed document is attached.', + 'All signatures on "%s" are complete. The signed documents are attached.', + count($attachments), + [$request->getName()], + )); + } else { + // TRANSLATORS Email body sent when the fully signed document cannot be attached, for example because it is too large. %s is the document or envelope name. + $emailTemplate->addBodyText($this->l10n->t('All signatures on "%s" are complete. The signed document is too large to attach. You can access it using the link below:', [$request->getName()])); + $emailTemplate->addBodyButton( + // TRANSLATORS Email button label that opens the validation view of the signed document. %s is the document filename. + $this->l10n->t('View signed document "%s"', [$request->getName()]), + $this->buildValidationLink($request), + ); + } + $message = $this->mailer->createMessage(); + $message->setTo($displayName !== '' ? [$email => $displayName] : [$email]); + $replyTo = $this->replyToAddress($this->userManager->get($request->getUserId())); + if ($replyTo !== null) { + $message->setReplyTo($replyTo); + } + $message->useTemplate($emailTemplate); + foreach ($attachments as $name => $content) { + $message->attach($this->mailer->createAttachment($content, (string)$name, 'application/pdf')); + } + $this->sendAndCheck($message); + } + public function notifyCanceledRequest(SignRequest $signRequest, string $email, File $libreSignFile): void { $emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail'); // TRANSLATORS Email subject shown when the requester cancels a pending signature request. diff --git a/lib/Service/Notification/MailChannel.php b/lib/Service/Notification/MailChannel.php index 777c8e05a7..433e2f1e6f 100644 --- a/lib/Service/Notification/MailChannel.php +++ b/lib/Service/Notification/MailChannel.php @@ -9,10 +9,13 @@ namespace OCA\Libresign\Service\Notification; use OCA\Libresign\Service\MailService; +use OCA\Libresign\Service\SignedCopyAttachmentProvider; +use OCA\Libresign\Service\SignedCopyMailService; final class MailChannel implements NotificationChannel { public function __construct( private MailService $mail, + private SignedCopyAttachmentProvider $signedCopyAttachments, ) { } @@ -42,6 +45,14 @@ public function deliver(NotificationMessage $message): void { case 'sign_request_canceled': $this->mail->notifyCanceledRequest($signRequest, $email, $message->file); break; + case SignedCopyMailService::EVENT_TYPE: + $this->mail->notifySignedCopy( + $message->file, + $email, + $message->payload->displayName ?? '', + $this->signedCopyAttachments->load($message->file, $message->payload->documentIds), + ); + break; default: throw new \InvalidArgumentException('Unsupported mail notification event'); } diff --git a/lib/Service/Notification/MailPayload.php b/lib/Service/Notification/MailPayload.php index 59dd4c4ef3..77398b9d1b 100644 --- a/lib/Service/Notification/MailPayload.php +++ b/lib/Service/Notification/MailPayload.php @@ -10,9 +10,11 @@ /** The caller selects the business event; the mail adapter selects its template. */ final readonly class MailPayload implements NotificationPayload { + /** @param list $documentIds Documents attached to a signed copy mail. */ public function __construct( public ?string $displayName = null, public bool $firstNotification = false, + public array $documentIds = [], ) { } } diff --git a/lib/Service/Notification/NotificationEnvelopeCodec.php b/lib/Service/Notification/NotificationEnvelopeCodec.php index 210f09f53b..56d106fc00 100644 --- a/lib/Service/Notification/NotificationEnvelopeCodec.php +++ b/lib/Service/Notification/NotificationEnvelopeCodec.php @@ -34,6 +34,7 @@ public function encode(NotificationMessage $message): string { 'type' => 'mail', 'displayName' => $message->payload->displayName, 'firstNotification' => $message->payload->firstNotification, + 'documentIds' => $message->payload->documentIds, ], $message->payload instanceof GatewayPayload => [ 'type' => 'gateway', @@ -138,6 +139,9 @@ private function restorePayload(array $payload): NotificationPayload { 'mail' => new MailPayload( isset($payload['displayName']) ? (string)$payload['displayName'] : null, $payload['firstNotification'] === true, + array_values(array_map('intval', is_array($payload['documentIds'] ?? []) + ? $payload['documentIds'] ?? [] + : throw new \UnexpectedValueException('Invalid mail delivery documents'))), ), 'gateway' => new GatewayPayload( (string)$payload['gatewayName'], diff --git a/lib/Service/Policy/Provider/PolicyProviders.php b/lib/Service/Policy/Provider/PolicyProviders.php index 4319d04f57..60e00c55b8 100644 --- a/lib/Service/Policy/Provider/PolicyProviders.php +++ b/lib/Service/Policy/Provider/PolicyProviders.php @@ -30,6 +30,7 @@ use OCA\Libresign\Service\Policy\Provider\SignatureHashAlgorithm\SignatureHashAlgorithmPolicy; use OCA\Libresign\Service\Policy\Provider\SignatureRejection\SignatureRejectionPolicy; use OCA\Libresign\Service\Policy\Provider\SignatureText\SignatureTextPolicy; +use OCA\Libresign\Service\Policy\Provider\SignedCopyMail\SignedCopyMailPolicy; use OCA\Libresign\Service\Policy\Provider\SignerGeolocation\SignerGeolocationPolicy; use OCA\Libresign\Service\Policy\Provider\SignerIpGeolocation\SignerIpGeolocationPolicy; use OCA\Libresign\Service\Policy\Provider\Tsa\TsaPolicy; @@ -71,6 +72,7 @@ final class PolicyProviders { IdentifyMethodsPolicy::KEY => IdentifyMethodsPolicy::class, ObserverProfilePolicy::KEY => ObserverProfilePolicy::class, SignatureTextPolicy::KEY => SignatureTextPolicy::class, + SignedCopyMailPolicy::KEY => SignedCopyMailPolicy::class, SignerGeolocationPolicy::KEY => SignerGeolocationPolicy::class, SignerIpGeolocationPolicy::KEY => SignerIpGeolocationPolicy::class, TsaPolicy::KEY => TsaPolicy::class, diff --git a/lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicy.php b/lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicy.php new file mode 100644 index 0000000000..c949bfc1e3 --- /dev/null +++ b/lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicy.php @@ -0,0 +1,84 @@ + new PolicySpec( + key: self::KEY, + defaultSystemValue: SignedCopyMailPolicyValue::encode(SignedCopyMailPolicyValue::defaults()), + allowedValues: static fn (): array => [], + normalizer: static fn (mixed $rawValue): string => SignedCopyMailPolicyValue::encode(SignedCopyMailPolicyValue::normalize($rawValue)), + appConfigKey: self::SYSTEM_APP_CONFIG_KEY, + supportsRequestOverride: false, + requestLifecycle: PolicySpec::LIFECYCLE_RUNTIME, + groupPolicyManager: static function (PolicyContext $context, ?PolicyLayer $systemPolicy, array $groupLayers): bool { + $actorRole = $context->getActorRole(); + if ($actorRole->canManageSystemPolicies) { + return true; + } + + if (!$actorRole->canManageGroupPolicies || $actorRole->manageableGroupCount < 1) { + return false; + } + + return DelegationLayerHelper::hasExplicitGlobalDelegation($systemPolicy) + || DelegationLayerHelper::hasSystemCreatedGroupDelegation($groupLayers); + }, + systemCreatedGroupRuleEditor: static function (PolicyContext $context, ?PolicyLayer $systemPolicy, PolicyLayer $existingPolicy): bool { + $actorRole = $context->getActorRole(); + if ($actorRole->canManageSystemPolicies) { + return true; + } + + if (!$actorRole->canManageGroupPolicies) { + return false; + } + + if (!$existingPolicy->isVisibleToChild() || !$existingPolicy->isAllowChildOverride() || $existingPolicy->getValue() === null) { + return false; + } + + if (DelegationLayerHelper::hasExplicitGlobalDelegation($systemPolicy)) { + return true; + } + + return $existingPolicy->isCreatedBySystemAdmin(); + }, + supportsGroupAdminDelegation: true, + ), + default => throw new \InvalidArgumentException('Unknown policy key: ' . PolicyKeyNormalizer::normalize($policyKey)), + }; + } +} diff --git a/lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicyValue.php b/lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicyValue.php new file mode 100644 index 0000000000..0e95bbf2ed --- /dev/null +++ b/lib/Service/Policy/Provider/SignedCopyMail/SignedCopyMailPolicyValue.php @@ -0,0 +1,79 @@ +} */ + public static function defaults(): array { + return [ + 'enabled' => false, + 'archive_addresses' => [], + ]; + } + + /** @return array{enabled: bool, archive_addresses: list} */ + public static function normalize(mixed $rawValue): array { + if (is_string($rawValue)) { + $trimmed = trim($rawValue); + if ($trimmed !== '') { + $decoded = json_decode($trimmed, true); + if (is_array($decoded)) { + $rawValue = $decoded; + } + } + } + + if (!is_array($rawValue)) { + return self::defaults(); + } + + return [ + 'enabled' => filter_var($rawValue['enabled'] ?? false, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false, + 'archive_addresses' => self::normalizeAddresses($rawValue['archive_addresses'] ?? []), + ]; + } + + /** @param array $value */ + public static function encode(array $value): string { + return (string)json_encode(self::normalize($value), JSON_UNESCAPED_SLASHES); + } + + /** + * Keeps valid, unique addresses in their given order. Invalid entries + * are dropped instead of failing so a stored value can always be read. + * + * @return list + */ + private static function normalizeAddresses(mixed $rawValue): array { + if (is_string($rawValue)) { + $rawValue = preg_split('/[\s,;]+/', $rawValue) ?: []; + } + if (!is_array($rawValue)) { + return []; + } + + $addresses = []; + foreach ($rawValue as $candidate) { + if (!is_string($candidate)) { + continue; + } + $address = trim($candidate); + if (filter_var($address, FILTER_VALIDATE_EMAIL) === false) { + continue; + } + $addresses[strtolower($address)] ??= $address; + if (count($addresses) >= self::MAX_ARCHIVE_ADDRESSES) { + break; + } + } + return array_values($addresses); + } +} diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 484bf57c52..76c2a23e3b 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -614,6 +614,11 @@ private function associateToSigners(array $data, FileEntity $file): array { ) ?? false; } + // Absent key leaves the stored choice unchanged on updates. + $sendSignedCopy = array_key_exists('sendSignedCopy', $signer) + ? (filter_var($signer['sendSignedCopy'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false) + : null; + foreach ($signer['identifyMethods'] as $identifyMethod) { $lastSignRequest = $this->signRequestService->createOrUpdateSignRequest( identifyMethods: [ @@ -627,7 +632,10 @@ private function associateToSigners(array $data, FileEntity $file): array { fileStatus: $fileStatus, signerStatus: $signerStatus, participantRole: $participantRole, - afterPersist: function (SignRequestEntity $signRequest) use ($file, $requesterRequiresGeolocation): void { + afterPersist: function (SignRequestEntity $signRequest) use ($file, $requesterRequiresGeolocation, $sendSignedCopy): void { + if ($sendSignedCopy !== null) { + $this->persistSendSignedCopy($signRequest, $sendSignedCopy); + } $requiresGeolocation = $requesterRequiresGeolocation; if ($requiresGeolocation === null) { if ($this->signerGeolocationPolicyService->getFrozenRequirement($signRequest) !== null) { @@ -650,6 +658,17 @@ private function associateToSigners(array $data, FileEntity $file): array { return $return; } + private function persistSendSignedCopy(SignRequestEntity $signRequest, bool $sendSignedCopy): void { + $metadata = $signRequest->getMetadata() ?? []; + if ($sendSignedCopy) { + $metadata[SignedCopyMailService::METADATA_KEY] = true; + } else { + unset($metadata[SignedCopyMailService::METADATA_KEY]); + } + $signRequest->setMetadata($metadata); + $this->signRequestMapper->update($signRequest); + } + private function saveVisibleElements(array $data, FileEntity $file): array { if (empty($data['visibleElements'])) { return []; diff --git a/lib/Service/SignedCopyAttachmentProvider.php b/lib/Service/SignedCopyAttachmentProvider.php new file mode 100644 index 0000000000..c85f4ff61f --- /dev/null +++ b/lib/Service/SignedCopyAttachmentProvider.php @@ -0,0 +1,95 @@ + $documentIds + * @return array file name => content + */ + public function load(FileEntity $request, array $documentIds): array { + $request = $this->fileMapper->getById($request->getId()); + $documents = $request->isEnvelope() + ? $this->fileMapper->getChildrenFiles($request->getId()) + : [$request]; + + $nodes = []; + $size = 0; + foreach ($documents as $document) { + if (!in_array($document->getId(), $documentIds, true)) { + continue; + } + $node = $this->getSignedNode($document); + if ($node === null) { + return []; + } + $size += $node->getSize(); + $nodes[] = $node; + } + if ($nodes === [] || count($nodes) !== count($documentIds) || $size > self::MAX_ATTACHMENT_BYTES) { + return []; + } + + $attachments = []; + foreach ($nodes as $node) { + $attachments[$this->uniqueName($node->getName(), $attachments)] = $node->getContent(); + } + return $attachments; + } + + private function getSignedNode(FileEntity $document): ?File { + $nodeId = $document->getSignedNodeId(); + if ($nodeId === null) { + return null; + } + try { + $node = $this->folderService->getReadableNodeById($document->getUserId(), $nodeId); + } catch (\Exception) { + $node = null; + } + return $node instanceof File ? $node : null; + } + + /** @param array $attachments */ + private function uniqueName(string $name, array $attachments): string { + $candidate = $name; + $counter = 1; + while (isset($attachments[$candidate])) { + $counter++; + $extension = pathinfo($name, PATHINFO_EXTENSION); + $base = $extension === '' ? $name : substr($name, 0, -strlen($extension) - 1); + $candidate = $base . ' (' . $counter . ')' . ($extension === '' ? '' : '.' . $extension); + } + return $candidate; + } +} diff --git a/lib/Service/SignedCopyMailService.php b/lib/Service/SignedCopyMailService.php new file mode 100644 index 0000000000..441cd74cbd --- /dev/null +++ b/lib/Service/SignedCopyMailService.php @@ -0,0 +1,167 @@ +getStatus() !== FileStatus::SIGNED->value || $file->hasParent()) { + return 0; + } + $policy = $this->resolvePolicy($file); + if (!$policy['enabled']) { + return 0; + } + + $documents = $file->isEnvelope() + ? $this->fileMapper->getChildrenFiles($file->getId()) + : [$file]; + + $queued = 0; + foreach ($this->collectRecipients($documents, $policy['archive_addresses']) as $recipient) { + $message = new NotificationMessage( + // One stable source per request: the delivery key then only + // differs by recipient, which makes a repeated completion a no-op. + self::EVENT_TYPE . ':' . $file->getUuid(), + self::EVENT_TYPE, + 'mail', + $file, + $recipient['signRequest'], + $recipient['email'], + new MailPayload($recipient['displayName'], documentIds: $recipient['documentIds']), + ); + $delivery = $this->registrar->register($message, $this->mailChannel, $this->codec->encode($message)); + if ($delivery->getState() !== NotificationDeliveryState::PENDING->value) { + continue; + } + $argument = ['id' => $delivery->getId()]; + if (!$this->jobList->has(DeliverNotification::class, $argument)) { + $this->jobList->add(DeliverNotification::class, $argument); + $queued++; + } + } + return $queued; + } + + /** @return array{enabled: bool, archive_addresses: list} */ + private function resolvePolicy(FileEntity $file): array { + $userId = $file->getUserId(); + $value = $this->policyService + ->resolveForUserId(SignedCopyMailPolicy::KEY, $userId !== '' ? $userId : null) + ->getEffectiveValue(); + return SignedCopyMailPolicyValue::normalize($value); + } + + /** + * @param FileEntity[] $documents + * @param list $archiveAddresses + * @return array}> + */ + private function collectRecipients(array $documents, array $archiveAddresses): array { + $recipients = []; + foreach ($documents as $document) { + foreach ($this->signRequestMapper->getByFileId($document->getId()) as $signRequest) { + if (!$this->wantsSignedCopy($signRequest)) { + continue; + } + $email = $this->resolveEmail($signRequest); + if ($email !== null) { + $this->addRecipient($recipients, $email, $signRequest->getDisplayName(), $signRequest, $document->getId()); + } + } + } + foreach ($archiveAddresses as $address) { + foreach ($documents as $document) { + // An archive address belongs to no sign request. + $this->addRecipient($recipients, $address, '', new SignRequest(), $document->getId()); + } + } + return $recipients; + } + + private function wantsSignedCopy(SignRequest $signRequest): bool { + $metadata = $signRequest->getMetadata() ?? []; + return ($metadata[self::METADATA_KEY] ?? false) === true + && $signRequest->getSigned() !== null; + } + + private function resolveEmail(SignRequest $signRequest): ?string { + foreach ($this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId()) as $identifyMethod) { + if ($identifyMethod->isDeletedAccount()) { + continue; + } + $value = $identifyMethod->getIdentifierValue(); + if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT) { + $user = $this->userManager->get($value); + $value = $user instanceof IUser ? (string)$user->getEMailAddress() : ''; + } + if (filter_var($value, FILTER_VALIDATE_EMAIL) !== false) { + return $value; + } + } + return null; + } + + /** + * @param array}> $recipients + */ + private function addRecipient(array &$recipients, string $email, string $displayName, SignRequest $signRequest, int $documentId): void { + $key = strtolower($email); + $recipients[$key] ??= ['email' => $email, 'displayName' => $displayName, 'signRequest' => $signRequest, 'documentIds' => []]; + if (!in_array($documentId, $recipients[$key]['documentIds'], true)) { + $recipients[$key]['documentIds'][] = $documentId; + } + } +} diff --git a/openapi-full.json b/openapi-full.json index c7c79e3450..fc36c47cb1 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -2126,6 +2126,9 @@ }, "deviceGeolocationRequired": { "type": "boolean" + }, + "sendSignedCopy": { + "type": "boolean" } } }, @@ -3243,6 +3246,9 @@ }, "rejection": { "$ref": "#/components/schemas/SignerRejection" + }, + "sendSignedCopy": { + "type": "boolean" } } } @@ -12248,7 +12254,7 @@ "signers": { "type": "array", "default": [], - "description": "Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired", + "description": "Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired, sendSignedCopy", "items": { "$ref": "#/components/schemas/NewSigner" } diff --git a/openapi.json b/openapi.json index 6b4e635e67..c7a7065386 100644 --- a/openapi.json +++ b/openapi.json @@ -1711,6 +1711,9 @@ }, "deviceGeolocationRequired": { "type": "boolean" + }, + "sendSignedCopy": { + "type": "boolean" } } }, @@ -2769,6 +2772,9 @@ }, "rejection": { "$ref": "#/components/schemas/SignerRejection" + }, + "sendSignedCopy": { + "type": "boolean" } } } @@ -11511,7 +11517,7 @@ "signers": { "type": "array", "default": [], - "description": "Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired", + "description": "Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired, sendSignedCopy", "items": { "$ref": "#/components/schemas/NewSigner" } diff --git a/src/components/Request/IdentifySigner.vue b/src/components/Request/IdentifySigner.vue index 461325c665..ab4743e875 100644 --- a/src/components/Request/IdentifySigner.vue +++ b/src/components/Request/IdentifySigner.vue @@ -57,6 +57,14 @@ +
+ + + {{ t('libresign', 'Email the signed document to this signer') }} + +
+