From 0a58ebdf136291c29a85296eadded2a7a3bee115 Mon Sep 17 00:00:00 2001 From: no84by <50858621+no84by@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:44:46 +0000 Subject: [PATCH 1/2] feat(mail): send participant e-mails in a per-signer language A signer can carry an optional `language` (a language code LibreSign has translations for). It is stored in the sign request metadata and used for the invitation, change/reminder and cancellation e-mails sent to that participant, including the footer and the HTML lang/dir attributes. Without a value the e-mails keep using the default language. An absent key keeps the stored language, an empty value clears it and an unknown code is rejected. The available codes are provided to the request page as the `signer_languages` initial state. Signed-off-by: no84by <50858621+no84by@users.noreply.github.com> --- lib/Controller/PageController.php | 3 + lib/Controller/RequestSignatureController.php | 2 +- lib/Files/TemplateLoader.php | 3 + lib/ResponseDefinitions.php | 2 + lib/Service/MailService.php | 63 ++++++--- lib/Service/RequestSignatureService.php | 12 +- .../SignRequest/SignerLanguageService.php | 83 ++++++++++++ lib/Service/Validation/SignerValidator.php | 17 +++ openapi-full.json | 8 +- openapi.json | 8 +- src/types/openapi/openapi-full.ts | 4 +- src/types/openapi/openapi.ts | 4 +- .../Controller/PageControllerTest.php | 3 + tests/php/Unit/Files/TemplateLoaderTest.php | 12 +- tests/php/Unit/Service/MailServiceTest.php | 86 ++++++++++++ .../Service/RequestSignatureServiceTest.php | 78 +++++++++++ .../SignRequest/SignerLanguageServiceTest.php | 125 ++++++++++++++++++ .../Validation/SignerValidatorTest.php | 41 ++++++ 18 files changed, 528 insertions(+), 26 deletions(-) create mode 100644 lib/Service/SignRequest/SignerLanguageService.php create mode 100644 tests/php/Unit/Service/SignRequest/SignerLanguageServiceTest.php diff --git a/lib/Controller/PageController.php b/lib/Controller/PageController.php index 6a8b395574..5178703cef 100644 --- a/lib/Controller/PageController.php +++ b/lib/Controller/PageController.php @@ -32,6 +32,7 @@ use OCA\Libresign\Service\SessionService; use OCA\Libresign\Service\SignerElementsService; use OCA\Libresign\Service\SignFileService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCA\Libresign\Service\Validation\SigningRequestValidator; use OCA\Viewer\Event\LoadViewer; use OCP\AppFramework\Db\DoesNotExistException; @@ -84,6 +85,7 @@ public function __construct( private IEventDispatcher $eventDispatcher, private IURLGenerator $urlGenerator, private EmailSignerElementsService $emailSignerElementsService, + private SignerLanguageService $signerLanguageService, ) { parent::__construct( request: $request, @@ -116,6 +118,7 @@ public function index(): TemplateResponse { } catch (LibresignException) { $this->initialState->provideInitialState('can_request_sign', false); } + $this->initialState->provideInitialState('signer_languages', $this->signerLanguageService->getAvailableLanguages()); $this->provideSignerSignatues(); $this->initialState->provideInitialState('effective_policies', [ diff --git a/lib/Controller/RequestSignatureController.php b/lib/Controller/RequestSignatureController.php index 4d27495eca..c00c4c878b 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, language (language code for the e-mails to the signer; empty uses the default) * @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/Files/TemplateLoader.php b/lib/Files/TemplateLoader.php index 7579267f62..369d4c6054 100644 --- a/lib/Files/TemplateLoader.php +++ b/lib/Files/TemplateLoader.php @@ -15,6 +15,7 @@ use OCA\Libresign\Service\AccountService; use OCA\Libresign\Service\IdentifyMethodService; use OCA\Libresign\Service\Policy\PolicyService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCA\Libresign\Service\Validation\SigningRequestValidator; use OCP\App\IAppManager; use OCP\AppFramework\Services\IInitialState; @@ -38,6 +39,7 @@ public function __construct( private PolicyService $policyService, private IAppManager $appManager, private TemplateLoaderAssets $assets, + private SignerLanguageService $signerLanguageService, ) { } @@ -71,6 +73,7 @@ protected function getInitialStatePayload(): array { 'policies' => $this->policyService->resolveKnownPolicyStates(), ], 'can_request_sign' => $this->canRequestSign(), + 'signer_languages' => $this->signerLanguageService->getAvailableLanguages(), ]; } diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 81fe277cdf..f6911c5733 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -110,6 +110,7 @@ * status?: int, * participantRole?: LibresignParticipantRole, * deviceGeolocationRequired?: bool, + * language?: string, * } * @psalm-type LibresignNewFile = array{ * base64?: string, @@ -231,6 +232,7 @@ * geolocation?: LibresignSignerGeolocation, * notify?: list, * certificate_info?: LibresignSignerCertificateInfo, + * language?: string, * } * @psalm-type LibresignSignerDisplayStatus = 'draft'|'ready_to_sign'|'signed'|'rejected'|'observing'|'not_signed' * @psalm-type LibresignSignerSummary = array{ diff --git a/lib/Service/MailService.php b/lib/Service/MailService.php index c70a09b23d..00d8f73898 100644 --- a/lib/Service/MailService.php +++ b/lib/Service/MailService.php @@ -16,6 +16,7 @@ use OCA\Libresign\Exception\MailTransportException; use OCA\Libresign\Service\Policy\PolicyService; use OCA\Libresign\Service\Policy\Provider\MailSenderStrategy\MailSenderStrategyPolicy; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCP\IAppConfig; use OCP\IL10N; use OCP\IURLGenerator; @@ -44,6 +45,7 @@ public function __construct( private PolicyService $policyService, private IMailProviderManager $mailProviderManager, private IUserManager $userManager, + private SignerLanguageService $signerLanguageService, ) { } @@ -57,21 +59,39 @@ private function getFileById(int $fileId): File { return $this->files[$fileId]; } + /** + * Translations for a mail to a participant: the language the requester + * chose for them, or the default one. + */ + private function getParticipantL10n(SignRequest $signRequest): IL10N { + return $this->signerLanguageService->getL10n($signRequest) ?? $this->l10n; + } + + private function createParticipantEmailTemplate(IL10N $l10n): IEMailTemplate { + $emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail'); + if ($l10n !== $this->l10n) { + $emailTemplate->setLanguage($l10n->getLanguageCode()); + } + return $emailTemplate; + } + /** * @psalm-suppress MixedMethodCall */ public function notifySignDataUpdated(SignRequest $data, string $email, ?string $description = null): void { $file = $this->getFileById($data->getFileId()); $isObserver = $data->isObserver(); + $l10n = $this->getParticipantL10n($data); - $emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail'); + $emailTemplate = $this->createParticipantEmailTemplate($l10n); $this->applyParticipantNotificationHeader( $emailTemplate, + $l10n, $isObserver, // TRANSLATORS Email subject notifying an observer that a document changed and should be reviewed again. - $this->l10n->t('LibreSign: Changes were made to a document'), + $l10n->t('LibreSign: Changes were made to a document'), // TRANSLATORS Email subject notifying a signer that a pending signature request changed and should be reviewed again. - $this->l10n->t('LibreSign: Changes were made to a document waiting for your signature'), + $l10n->t('LibreSign: Changes were made to a document waiting for your signature'), ); if (!empty($description)) { @@ -81,13 +101,14 @@ public function notifySignDataUpdated(SignRequest $data, string $email, ?string $this->applyParticipantNotificationAction( $emailTemplate, + $l10n, $data, $file, $isObserver, // TRANSLATORS Email body telling an observer to reopen the document because some request details changed. - $this->l10n->t('Changes were made to a document. Open the link below:'), + $l10n->t('Changes were made to a document. Open the link below:'), // TRANSLATORS Email body telling the signer to reopen the request because some request details changed. - $this->l10n->t('Changes were made to a document you need to sign. Open the link below:'), + $l10n->t('Changes were made to a document you need to sign. Open the link below:'), ); try { $this->sendSignRequestNotification($emailTemplate, $data, $email); @@ -103,15 +124,17 @@ public function notifySignDataUpdated(SignRequest $data, string $email, ?string public function notifyUnsignedUser(SignRequest $data, string $email, ?string $description = null): void { $file = $this->getFileById($data->getFileId()); $isObserver = $data->isObserver(); + $l10n = $this->getParticipantL10n($data); - $emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail'); + $emailTemplate = $this->createParticipantEmailTemplate($l10n); $this->applyParticipantNotificationHeader( $emailTemplate, + $l10n, $isObserver, // TRANSLATORS Email subject notifying an observer that a document is available to view. - $this->l10n->t('LibreSign: A document is ready to view'), + $l10n->t('LibreSign: A document is ready to view'), // TRANSLATORS Email subject notifying a signer that a document is ready for their digital signature. - $this->l10n->t('LibreSign: A document is ready for your signature'), + $l10n->t('LibreSign: A document is ready for your signature'), ); if (!empty($description)) { @@ -121,13 +144,14 @@ public function notifyUnsignedUser(SignRequest $data, string $email, ?string $de $this->applyParticipantNotificationAction( $emailTemplate, + $l10n, $data, $file, $isObserver, // TRANSLATORS Email body inviting an observer to open the document and view it. - $this->l10n->t('A document is ready to view. Open the link below:'), + $l10n->t('A document is ready to view. Open the link below:'), // TRANSLATORS Email body inviting the signer to open the document and sign it. - $this->l10n->t('A document is ready for your signature. Open the link below:'), + $l10n->t('A document is ready for your signature. Open the link below:'), ); try { $this->sendSignRequestNotification($emailTemplate, $data, $email); @@ -139,6 +163,7 @@ public function notifyUnsignedUser(SignRequest $data, string $email, ?string $de private function applyParticipantNotificationHeader( IEMailTemplate $emailTemplate, + IL10N $l10n, bool $isObserver, string $observerSubject, string $signerSubject, @@ -148,15 +173,16 @@ private function applyParticipantNotificationHeader( $emailTemplate->addHeading( $isObserver // TRANSLATORS Email heading shown above a document available for viewing. - ? $this->l10n->t('Document to view') + ? $l10n->t('Document to view') // TRANSLATORS Email heading shown above a document awaiting the recipient's signature. - : $this->l10n->t('Document to sign'), + : $l10n->t('Document to sign'), false, ); } private function applyParticipantNotificationAction( IEMailTemplate $emailTemplate, + IL10N $l10n, SignRequest $data, File $file, bool $isObserver, @@ -167,7 +193,7 @@ private function applyParticipantNotificationAction( if ($isObserver) { $emailTemplate->addBodyButton( // TRANSLATORS Email button label that opens the document validation view. %s is the document filename. - $this->l10n->t('View "%s"', [$file->getName()]), + $l10n->t('View "%s"', [$file->getName()]), $this->buildValidationLink($file), ); return; @@ -175,7 +201,7 @@ private function applyParticipantNotificationAction( $emailTemplate->addBodyButton( // TRANSLATORS Email button label that opens the signing page. %s is the document filename. - $this->l10n->t('Sign "%s"', [$file->getName()]), + $l10n->t('Sign "%s"', [$file->getName()]), $this->urlGenerator->linkToRouteAbsolute('libresign.page.sign', ['uuid' => $data->getUuid()]), ); } @@ -357,14 +383,15 @@ public function notifySignedUser(SignRequest $signRequest, string $email, File $ } public function notifyCanceledRequest(SignRequest $signRequest, string $email, File $libreSignFile): void { - $emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail'); + $l10n = $this->getParticipantL10n($signRequest); + $emailTemplate = $this->createParticipantEmailTemplate($l10n); // TRANSLATORS Email subject shown when the requester cancels a pending signature request. - $emailTemplate->setSubject($this->l10n->t('LibreSign: A signature request has been canceled')); + $emailTemplate->setSubject($l10n->t('LibreSign: A signature request has been canceled')); $emailTemplate->addHeader(); // TRANSLATORS Email heading shown when a signature request is no longer active. - $emailTemplate->addHeading($this->l10n->t('Signature request canceled'), false); + $emailTemplate->addHeading($l10n->t('Signature request canceled'), false); // TRANSLATORS Email body text shown after cancellation. %s is the document filename that no longer needs a signature. - $emailTemplate->addBodyText($this->l10n->t('The request for you to sign "%s" has been canceled.', [$libreSignFile->getName()])); + $emailTemplate->addBodyText($l10n->t('The request for you to sign "%s" has been canceled.', [$libreSignFile->getName()])); $message = $this->mailer->createMessage(); if ($signRequest->getDisplayName()) { $message->setTo([$email => $signRequest->getDisplayName()]); diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 484bf57c52..acaea127ab 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -26,6 +26,7 @@ use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod; use OCA\Libresign\Service\Policy\FilePolicyApplier; use OCA\Libresign\Service\SignerGeolocation\SignerGeolocationPolicyService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCA\Libresign\Service\SignRequest\SignRequestService; use OCA\Libresign\Service\Validation\FileInputValidator; use OCA\Libresign\Service\Validation\SignerValidator; @@ -81,6 +82,7 @@ public function __construct( protected IDBConnection $db, protected NotificationDeliveryService $notifications, protected NativeWebhookEventPublisher $webhooks, + protected SignerLanguageService $signerLanguageService, ) { } @@ -613,6 +615,11 @@ private function associateToSigners(array $data, FileEntity $file): array { FILTER_NULL_ON_FAILURE, ) ?? false; } + // Absent key keeps the stored language; an empty value clears it. + $language = null; + if (array_key_exists('language', $signer)) { + $language = is_string($signer['language']) ? $signer['language'] : ''; + } foreach ($signer['identifyMethods'] as $identifyMethod) { $lastSignRequest = $this->signRequestService->createOrUpdateSignRequest( @@ -627,7 +634,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, $language): void { + if ($language !== null) { + $this->signerLanguageService->setLanguage($signRequest, $language); + } $requiresGeolocation = $requesterRequiresGeolocation; if ($requiresGeolocation === null) { if ($this->signerGeolocationPolicyService->getFrozenRequirement($signRequest) !== null) { diff --git a/lib/Service/SignRequest/SignerLanguageService.php b/lib/Service/SignRequest/SignerLanguageService.php new file mode 100644 index 0000000000..29d0c91552 --- /dev/null +++ b/lib/Service/SignRequest/SignerLanguageService.php @@ -0,0 +1,83 @@ + + */ + public function getAvailableLanguages(): array { + $languages = array_values(array_unique($this->l10nFactory->findAvailableLanguages(Application::APP_ID))); + sort($languages); + return $languages; + } + + public function isAvailable(string $language): bool { + return $this->l10nFactory->languageExists(Application::APP_ID, $language); + } + + public function getLanguage(SignRequest $signRequest): ?string { + $language = ($signRequest->getMetadata() ?? [])[self::METADATA_KEY] ?? null; + if (!is_string($language) || $language === '' || !$this->isAvailable($language)) { + return null; + } + return $language; + } + + /** + * Translations for the e-mails sent to the signer, or null to keep the default. + */ + public function getL10n(SignRequest $signRequest): ?IL10N { + $language = $this->getLanguage($signRequest); + return $language === null ? null : $this->l10nFactory->get(Application::APP_ID, $language); + } + + /** + * Stores the language of a persisted sign request. An empty value clears it. + */ + public function setLanguage(SignRequest $signRequest, string $language): void { + $metadata = $signRequest->getMetadata() ?? []; + $current = $metadata[self::METADATA_KEY] ?? null; + if ($language === '') { + if ($current === null) { + return; + } + unset($metadata[self::METADATA_KEY]); + } else { + if ($current === $language) { + return; + } + $metadata[self::METADATA_KEY] = $language; + } + $signRequest->setMetadata($metadata); + $this->signRequestMapper->update($signRequest); + } +} diff --git a/lib/Service/Validation/SignerValidator.php b/lib/Service/Validation/SignerValidator.php index f945ff0f2a..dd9cd8d61b 100644 --- a/lib/Service/Validation/SignerValidator.php +++ b/lib/Service/Validation/SignerValidator.php @@ -24,6 +24,7 @@ use OCA\Libresign\Service\IdentifyMethodService; use OCA\Libresign\Service\Policy\Provider\ObserverProfile\ObserverProfilePolicyService; use OCA\Libresign\Service\SequentialSigningService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Http; use OCP\IL10N; @@ -40,6 +41,7 @@ public function __construct( private DocMdpValidator $docMdpValidator, private RuntimeRequirementValidator $runtimeRequirementValidator, private ObserverProfilePolicyService $observerProfilePolicyService, + private SignerLanguageService $signerLanguageService, ) { } @@ -61,6 +63,7 @@ public function validateIdentifySigners(array $data): void { throw new LibresignException('Display name must not be longer than 64 characters'); } $this->validateParticipantRole($signer, $data); + $this->validateLanguage($signer); foreach ($this->normalizeSignerIdentifyMethods($signer) as $method) { $this->validateIdentifyMethodForRequest($method['name'], $method['value']); } @@ -254,6 +257,20 @@ private function validateParticipantRole(array $signer, array $data): void { } } + private function validateLanguage(array $signer): void { + if (!array_key_exists('language', $signer)) { + return; + } + $language = $signer['language']; + if ($language === null || $language === '') { + return; + } + if (!is_string($language) || !$this->signerLanguageService->isAvailable($language)) { + // TRANSLATORS Validation error when the language chosen for a signer's e-mails is not available. + throw new LibresignException($this->l10n->t('Invalid language')); + } + } + private function getExistingRequestFile(array $data): ?File { $uuid = $data['uuid'] ?? null; if (!is_string($uuid) || $uuid === '') { diff --git a/openapi-full.json b/openapi-full.json index c7c79e3450..ccff750421 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -2126,6 +2126,9 @@ }, "deviceGeolocationRequired": { "type": "boolean" + }, + "language": { + "type": "string" } } }, @@ -3395,6 +3398,9 @@ }, "certificate_info": { "$ref": "#/components/schemas/SignerCertificateInfo" + }, + "language": { + "type": "string" } } }, @@ -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, language (language code for the e-mails to the signer; empty uses the default)", "items": { "$ref": "#/components/schemas/NewSigner" } diff --git a/openapi.json b/openapi.json index 6b4e635e67..abc7e979ea 100644 --- a/openapi.json +++ b/openapi.json @@ -1711,6 +1711,9 @@ }, "deviceGeolocationRequired": { "type": "boolean" + }, + "language": { + "type": "string" } } }, @@ -2921,6 +2924,9 @@ }, "certificate_info": { "$ref": "#/components/schemas/SignerCertificateInfo" + }, + "language": { + "type": "string" } } }, @@ -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, language (language code for the e-mails to the signer; empty uses the default)", "items": { "$ref": "#/components/schemas/NewSigner" } diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index a37db13462..a21c3e8283 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -1928,6 +1928,7 @@ export type components = { status?: number; participantRole?: components["schemas"]["ParticipantRole"]; deviceGeolocationRequired?: boolean; + language?: string; }; NotificationStatusResponse: { /** @enum {string} */ @@ -2290,6 +2291,7 @@ export type components = { geolocation?: components["schemas"]["SignerGeolocation"]; notify?: components["schemas"]["Notify"][]; certificate_info?: components["schemas"]["SignerCertificateInfo"]; + language?: string; }; SignerRejection: { rejectedAt: string; @@ -5962,7 +5964,7 @@ export interface operations { content: { "application/json": { /** - * @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, language (language code for the e-mails to the signer; empty uses the default) * @default [] */ signers?: components["schemas"]["NewSigner"][]; diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 9fd7aa8f47..18e262ed3d 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1488,6 +1488,7 @@ export type components = { status?: number; participantRole?: components["schemas"]["ParticipantRole"]; deviceGeolocationRequired?: boolean; + language?: string; }; NotificationStatusResponse: { /** @enum {string} */ @@ -1838,6 +1839,7 @@ export type components = { geolocation?: components["schemas"]["SignerGeolocation"]; notify?: components["schemas"]["Notify"][]; certificate_info?: components["schemas"]["SignerCertificateInfo"]; + language?: string; }; SignerRejection: { rejectedAt: string; @@ -5400,7 +5402,7 @@ export interface operations { content: { "application/json": { /** - * @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, language (language code for the e-mails to the signer; empty uses the default) * @default [] */ signers?: components["schemas"]["NewSigner"][]; diff --git a/tests/php/Integration/Controller/PageControllerTest.php b/tests/php/Integration/Controller/PageControllerTest.php index 45d0de48f3..2c60cce56b 100644 --- a/tests/php/Integration/Controller/PageControllerTest.php +++ b/tests/php/Integration/Controller/PageControllerTest.php @@ -26,6 +26,7 @@ use OCA\Libresign\Service\SessionService; use OCA\Libresign\Service\SignerElementsService; use OCA\Libresign\Service\SignFileService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCA\Libresign\Service\Validation\SigningRequestValidator; use OCA\Libresign\Tests\Integration\TestCase; use OCP\AppFramework\Http\RedirectResponse; @@ -173,6 +174,7 @@ public function setUp(): void { eventDispatcher: $this->createMock(IEventDispatcher::class), urlGenerator: $this->urlGenerator, emailSignerElementsService: $this->emailSignerElementsService, + signerLanguageService: \OCP\Server::get(SignerLanguageService::class), ); } @@ -405,6 +407,7 @@ public function testValidationFilePublicBootstrapsRequesterPoliciesWithoutUserSc eventDispatcher: $this->createMock(IEventDispatcher::class), urlGenerator: $this->urlGenerator, emailSignerElementsService: $this->createMock(EmailSignerElementsService::class), + signerLanguageService: \OCP\Server::get(SignerLanguageService::class), ); $response = $controller->validationFilePublic('validation-file-uuid'); diff --git a/tests/php/Unit/Files/TemplateLoaderTest.php b/tests/php/Unit/Files/TemplateLoaderTest.php index d3b3caf355..13f52e5814 100644 --- a/tests/php/Unit/Files/TemplateLoaderTest.php +++ b/tests/php/Unit/Files/TemplateLoaderTest.php @@ -17,6 +17,7 @@ use OCA\Libresign\Service\AccountService; use OCA\Libresign\Service\IdentifyMethodService; use OCA\Libresign\Service\Policy\PolicyService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCA\Libresign\Service\Validation\SigningRequestValidator; use OCA\Libresign\Tests\Unit\TestCase; use OCP\App\IAppManager; @@ -37,6 +38,7 @@ final class TemplateLoaderTest extends TestCase { private PolicyService&MockObject $policyService; private IAppManager&MockObject $appManager; private TemplateLoaderAssets&MockObject $assets; + private SignerLanguageService&MockObject $signerLanguageService; #[\Override] public function setUp(): void { @@ -50,9 +52,13 @@ public function setUp(): void { $this->policyService = $this->createMock(PolicyService::class); $this->appManager = $this->createMock(IAppManager::class); $this->assets = $this->createMock(TemplateLoaderAssets::class); + $this->signerLanguageService = $this->createMock(SignerLanguageService::class); } public function testHandleProvidesInitialStatePayload(): void { + $this->signerLanguageService + ->method('getAvailableLanguages') + ->willReturn(['de', 'en']); $engine = $this->createMock(IEngineHandler::class); $engine->method('isSetupOk')->willReturn(true); $this->certificateEngineFactory @@ -107,7 +113,7 @@ public function testHandleProvidesInitialStatePayload(): void { $capturedState = []; $this->initialState - ->expects($this->exactly(3)) + ->expects($this->exactly(4)) ->method('provideInitialState') ->willReturnCallback(static function (string $key, mixed $value) use (&$capturedState): void { $capturedState[$key] = $value; @@ -136,6 +142,7 @@ public function testHandleProvidesInitialStatePayload(): void { ], ], 'can_request_sign' => true, + 'signer_languages' => ['de', 'en'], ]; ksort($capturedState); ksort($expectedState); @@ -198,7 +205,7 @@ public function testHandleProvidesCannotRequestSignWhenValidationFails(): void { $capturedState = []; $this->initialState - ->expects($this->exactly(3)) + ->expects($this->exactly(4)) ->method('provideInitialState') ->willReturnCallback(static function (string $key, mixed $value) use (&$capturedState): void { $capturedState[$key] = $value; @@ -223,6 +230,7 @@ private function getLoader(): TemplateLoader { $this->policyService, $this->appManager, $this->assets, + $this->signerLanguageService, ); } diff --git a/tests/php/Unit/Service/MailServiceTest.php b/tests/php/Unit/Service/MailServiceTest.php index 8db9bc91f3..38e2cd203b 100644 --- a/tests/php/Unit/Service/MailServiceTest.php +++ b/tests/php/Unit/Service/MailServiceTest.php @@ -16,6 +16,7 @@ use OCA\Libresign\Service\Policy\Model\ResolvedPolicy; use OCA\Libresign\Service\Policy\PolicyService; use OCA\Libresign\Service\Policy\Provider\MailSenderStrategy\MailSenderStrategyPolicy; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCP\IAppConfig; use OCP\IL10N; use OCP\IURLGenerator; @@ -46,6 +47,7 @@ final class MailServiceTest extends \OCA\Libresign\Tests\Unit\TestCase { private PolicyService&MockObject $policyService; private IMailProviderManager&MockObject $mailProviderManager; private IUserManager&MockObject $userManager; + private SignerLanguageService&MockObject $signerLanguageService; private MailService $service; public function setUp(): void { @@ -62,6 +64,7 @@ public function setUp(): void { $this->policyService = $this->createMock(PolicyService::class); $this->mailProviderManager = $this->createMock(IMailProviderManager::class); $this->userManager = $this->createMock(IUserManager::class); + $this->signerLanguageService = $this->createMock(SignerLanguageService::class); $this->service = new MailService( $this->logger, $this->mailer, @@ -72,6 +75,7 @@ public function setUp(): void { $this->policyService, $this->mailProviderManager, $this->userManager, + $this->signerLanguageService, ); } @@ -449,6 +453,88 @@ public function testSendCodeToSignReportsRejectedRecipients(): void { $this->service->sendCodeToSign('recipient@example.com', 'Recipient', '123456'); } + public function testNotifyUnsignedUserKeepsDefaultLanguageWithoutSignerChoice(): void { + $this->mockRequest(); + $this->mockStrategy(MailSenderStrategyPolicy::STRATEGY_SYSTEM); + $emailTemplate = $this->createMock(IEMailTemplate::class); + $emailTemplate->expects($this->never())->method('setLanguage'); + $emailTemplate->expects($this->once()) + ->method('setSubject') + ->with('LibreSign: A document is ready for your signature'); + $this->mailer->method('createEMailTemplate')->willReturn($emailTemplate); + $this->mockSystemMessage(); + + $this->service->notifyUnsignedUser($this->mockSignRequest(), 'a@b.coop'); + } + + public function testNotifyUnsignedUserUsesSignerLanguage(): void { + $this->mockRequest(); + $this->mockStrategy(MailSenderStrategyPolicy::STRATEGY_SYSTEM); + $signRequest = $this->mockSignRequest(); + $this->mockSignerL10n($signRequest); + $emailTemplate = $this->createMock(IEMailTemplate::class); + $emailTemplate->expects($this->once())->method('setLanguage')->with('de'); + $emailTemplate->expects($this->once()) + ->method('setSubject') + ->with('[de] LibreSign: A document is ready for your signature'); + $emailTemplate->expects($this->once()) + ->method('addHeading') + ->with('[de] Document to sign', false); + $emailTemplate->expects($this->once()) + ->method('addBodyText') + ->with('[de] A document is ready for your signature. Open the link below:'); + $emailTemplate->expects($this->once()) + ->method('addBodyButton') + ->with('[de] Sign "%s"'); + $this->mailer->method('createEMailTemplate')->willReturn($emailTemplate); + $this->mockSystemMessage(); + $this->mailer->expects($this->once())->method('send'); + + $this->service->notifyUnsignedUser($signRequest, 'a@b.coop'); + } + + public function testNotifySignDataUpdatedUsesSignerLanguage(): void { + $this->mockRequest(); + $this->mockStrategy(MailSenderStrategyPolicy::STRATEGY_SYSTEM); + $signRequest = $this->mockSignRequest(); + $this->mockSignerL10n($signRequest); + $emailTemplate = $this->createMock(IEMailTemplate::class); + $emailTemplate->expects($this->once())->method('setLanguage')->with('de'); + $emailTemplate->expects($this->once()) + ->method('setSubject') + ->with('[de] LibreSign: Changes were made to a document waiting for your signature'); + $this->mailer->method('createEMailTemplate')->willReturn($emailTemplate); + $this->mockSystemMessage(); + + $this->service->notifySignDataUpdated($signRequest, 'a@b.coop'); + } + + public function testNotifyCanceledRequestUsesSignerLanguage(): void { + $this->mockRequest(); + $signRequest = $this->mockSignRequest(); + $this->mockSignerL10n($signRequest); + $emailTemplate = $this->createMock(IEMailTemplate::class); + $emailTemplate->expects($this->once())->method('setLanguage')->with('de'); + $emailTemplate->expects($this->once()) + ->method('setSubject') + ->with('[de] LibreSign: A signature request has been canceled'); + $this->mailer->method('createEMailTemplate')->willReturn($emailTemplate); + $this->mockSystemMessage(); + $this->mailer->expects($this->once())->method('send')->willReturn([]); + + $this->service->notifyCanceledRequest($signRequest, 'a@b.coop', new File()); + } + + private function mockSignerL10n(SignRequest $signRequest): void { + $l10n = $this->createMock(IL10N::class); + $l10n->method('getLanguageCode')->willReturn('de'); + $l10n->method('t')->willReturnCallback(static fn (string $text): string => '[de] ' . $text); + $this->signerLanguageService + ->method('getL10n') + ->with($signRequest) + ->willReturn($l10n); + } + private function mockSignRequest(string $displayName = 'John Doe'): SignRequest { $signRequest = new SignRequest(); $signRequest->setUuid('asdfg'); diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index 6bb87ea801..7d2aab7826 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -34,6 +34,7 @@ use OCA\Libresign\Service\SequentialSigningService; use OCA\Libresign\Service\SignerGeolocation\SignerGeolocationPolicyService; use OCA\Libresign\Service\SignerRemovalService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCA\Libresign\Service\SignRequest\SignRequestService; use OCA\Libresign\Service\SignRequest\StatusCacheService; use OCA\Libresign\Service\SignRequest\StatusService; @@ -51,6 +52,7 @@ use OCP\IL10N; use OCP\IUser; use OCP\IUserManager; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; @@ -89,6 +91,7 @@ final class RequestSignatureServiceTest extends \OCA\Libresign\Tests\Unit\TestCa private \OCP\IDBConnection&MockObject $db; private \OCA\Libresign\Service\NotificationDeliveryService&MockObject $notifications; private NativeWebhookEventPublisher&MockObject $webhooks; + private SignerLanguageService&MockObject $signerLanguageService; public function setUp(): void { parent::setUp(); @@ -130,6 +133,7 @@ public function setUp(): void { $this->db = $this->createMock(\OCP\IDBConnection::class); $this->notifications = $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class); $this->webhooks = $this->createMock(NativeWebhookEventPublisher::class); + $this->signerLanguageService = $this->createMock(SignerLanguageService::class); } private function getService(array $methods = []): RequestSignatureService|MockObject { @@ -168,6 +172,7 @@ private function getService(array $methods = []): RequestSignatureService|MockOb $this->db, $this->notifications, $this->webhooks, + $this->signerLanguageService, ]) ->onlyMethods($methods) ->getMock(); @@ -206,6 +211,7 @@ private function getService(array $methods = []): RequestSignatureService|MockOb $this->db, $this->notifications, $this->webhooks, + $this->signerLanguageService, ); } @@ -1049,6 +1055,76 @@ public function testAssociateToSignersPersistsGeolocationRequirementForEachIdent $this->assertCount(2, $actual); } + #[DataProvider('signerLanguageCases')] + public function testAssociateToSignersStoresSignerLanguageForEachIdentifyMethod(array $signerFields, ?string $expected): void { + $file = new \OCA\Libresign\Db\File(); + $file->setId(77); + $data = [ + 'status' => 9, + 'signers' => [[ + 'displayName' => 'John Doe', + 'identifyMethods' => [ + ['method' => 'email', 'value' => 'john@example.com'], + ['method' => 'account', 'value' => 'john'], + ], + ...$signerFields, + ]], + ]; + + $this->signerValidator + ->method('normalizeRequestSigners') + ->willReturnCallback(static fn (array $signers): array => $signers); + $this->signRequestMapper->method('getByFileId')->with(77)->willReturn([]); + $this->sequentialSigningService->method('determineSigningOrder')->willReturn(1); + $this->signerGeolocationPolicyService->method('getFrozenRequirement')->willReturn(null); + + $signRequestCounter = 0; + $this->signRequestService + ->method('createOrUpdateSignRequest') + ->willReturnCallback(function ( + array $identifyMethods, + string $displayName, + ?string $description, + bool $notify, + int $fileId, + int $signingOrder = 0, + ?int $fileStatus = null, + ?int $signerStatus = null, + ParticipantRole $participantRole = ParticipantRole::SIGNER, + ?callable $afterPersist = null, + ) use (&$signRequestCounter): SignRequest { + $signRequest = new SignRequest(); + $signRequest->setId(500 + ++$signRequestCounter); + if ($afterPersist !== null) { + $afterPersist($signRequest); + } + return $signRequest; + }); + + $stored = []; + $this->signerLanguageService + ->expects($expected === null ? $this->never() : $this->exactly(2)) + ->method('setLanguage') + ->willReturnCallback(static function (SignRequest $signRequest, string $language) use (&$stored): void { + $stored[$signRequest->getId()] = $language; + }); + + self::invokePrivate($this->getService(), 'associateToSigners', [$data, $file]); + + if ($expected !== null) { + $this->assertSame([501 => $expected, 502 => $expected], $stored); + } + } + + public static function signerLanguageCases(): array { + return [ + 'language chosen' => [['language' => 'de'], 'de'], + 'empty value clears the language' => [['language' => ''], ''], + 'null clears the language' => [['language' => null], ''], + 'omitted keeps the stored language' => [[], null], + ]; + } + public function testAssociateToSignersPreservesFrozenGeolocationWhenFlagOmitted(): void { $file = new \OCA\Libresign\Db\File(); $file->setId(77); @@ -1236,6 +1312,7 @@ public function testDeleteIdentifyMethodIfNotExitsKeepsMatchingIdentifyMethods() $this->createMock(\OCP\IDBConnection::class), $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class), $this->webhooks, + $this->signerLanguageService, ]) ->onlyMethods(['unassociateToUser']) ->getMock(); @@ -1315,6 +1392,7 @@ public function testDeleteIdentifyMethodIfNotExitsRemovesMissingIdentifyMethods( $this->createMock(\OCP\IDBConnection::class), $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class), $this->webhooks, + $this->signerLanguageService, ]) ->onlyMethods(['unassociateToUser']) ->getMock(); diff --git a/tests/php/Unit/Service/SignRequest/SignerLanguageServiceTest.php b/tests/php/Unit/Service/SignRequest/SignerLanguageServiceTest.php new file mode 100644 index 0000000000..e4ba2e859c --- /dev/null +++ b/tests/php/Unit/Service/SignRequest/SignerLanguageServiceTest.php @@ -0,0 +1,125 @@ +l10nFactory = $this->createMock(IFactory::class); + $this->l10nFactory + ->method('languageExists') + ->willReturnCallback(static fn (string $app, string $language): bool => $app === 'libresign' && in_array($language, ['en', 'de', 'pt_BR'], true)); + $this->signRequestMapper = $this->createMock(SignRequestMapper::class); + $this->service = new SignerLanguageService($this->l10nFactory, $this->signRequestMapper); + } + + public function testGetAvailableLanguagesListsTheAppTranslations(): void { + $this->l10nFactory + ->method('findAvailableLanguages') + ->with('libresign') + ->willReturn(['en', 'pt_BR', 'de', 'de']); + + $this->assertSame(['de', 'en', 'pt_BR'], $this->service->getAvailableLanguages()); + } + + #[DataProvider('storedLanguageCases')] + public function testGetLanguageReadsTheStoredChoice(?array $metadata, ?string $expected): void { + $signRequest = new SignRequest(); + if ($metadata !== null) { + $signRequest->setMetadata($metadata); + } + + $this->assertSame($expected, $this->service->getLanguage($signRequest)); + } + + public static function storedLanguageCases(): array { + return [ + 'no metadata' => [null, null], + 'no choice' => [['deviceGeolocationRequirement' => 'disabled'], null], + 'available language' => [['language' => 'pt_BR'], 'pt_BR'], + 'language no longer available' => [['language' => 'xx'], null], + 'empty value' => [['language' => ''], null], + 'not a string' => [['language' => ['de']], null], + ]; + } + + public function testGetL10nUsesTheStoredLanguage(): void { + $signRequest = new SignRequest(); + $signRequest->setMetadata(['language' => 'de']); + $l10n = $this->createMock(IL10N::class); + $this->l10nFactory + ->expects($this->once()) + ->method('get') + ->with('libresign', 'de') + ->willReturn($l10n); + + $this->assertSame($l10n, $this->service->getL10n($signRequest)); + } + + public function testGetL10nKeepsTheDefaultWithoutChoice(): void { + $this->l10nFactory->expects($this->never())->method('get'); + + $this->assertNull($this->service->getL10n(new SignRequest())); + } + + public function testSetLanguageStoresTheChoiceAndKeepsOtherMetadata(): void { + $signRequest = new SignRequest(); + $signRequest->setMetadata(['deviceGeolocationRequirement' => 'required']); + $this->signRequestMapper->expects($this->once())->method('update')->with($signRequest); + + $this->service->setLanguage($signRequest, 'de'); + + $this->assertSame( + ['deviceGeolocationRequirement' => 'required', 'language' => 'de'], + $signRequest->getMetadata(), + ); + } + + public function testSetLanguageWithEmptyValueClearsTheChoice(): void { + $signRequest = new SignRequest(); + $signRequest->setMetadata(['language' => 'de', 'deviceGeolocationRequirement' => 'required']); + $this->signRequestMapper->expects($this->once())->method('update')->with($signRequest); + + $this->service->setLanguage($signRequest, ''); + + $this->assertSame(['deviceGeolocationRequirement' => 'required'], $signRequest->getMetadata()); + } + + #[DataProvider('unchangedLanguageCases')] + public function testSetLanguageSkipsTheWriteWhenNothingChanges(?array $metadata, string $language): void { + $signRequest = new SignRequest(); + if ($metadata !== null) { + $signRequest->setMetadata($metadata); + } + $this->signRequestMapper->expects($this->never())->method('update'); + + $this->service->setLanguage($signRequest, $language); + } + + public static function unchangedLanguageCases(): array { + return [ + 'same language' => [['language' => 'de'], 'de'], + 'clear without choice' => [null, ''], + ]; + } +} diff --git a/tests/php/Unit/Service/Validation/SignerValidatorTest.php b/tests/php/Unit/Service/Validation/SignerValidatorTest.php index ffa35eef70..e4079a2731 100644 --- a/tests/php/Unit/Service/Validation/SignerValidatorTest.php +++ b/tests/php/Unit/Service/Validation/SignerValidatorTest.php @@ -28,6 +28,7 @@ use OCA\Libresign\Service\Policy\Provider\ObserverProfile\ObserverProfilePolicy; use OCA\Libresign\Service\Policy\Provider\ObserverProfile\ObserverProfilePolicyService; use OCA\Libresign\Service\SequentialSigningService; +use OCA\Libresign\Service\SignRequest\SignerLanguageService; use OCA\Libresign\Service\Validation\SignerValidator; use OCP\AppFramework\Db\DoesNotExistException; use OCP\IL10N; @@ -43,6 +44,7 @@ final class SignerValidatorTest extends \OCA\Libresign\Tests\Unit\TestCase { private DocMdpValidator $docMdpValidator; private PolicyService&MockObject $policyService; private ObserverProfilePolicyService $observerProfilePolicyService; + private SignerLanguageService&MockObject $signerLanguageService; private SignerValidator $validator; #[\Override] @@ -61,6 +63,7 @@ public function setUp(): void { ->setEffectiveValue(true); $this->policyService->method('resolve')->with(ObserverProfilePolicy::KEY)->willReturn($resolvedPolicy); $this->observerProfilePolicyService = new ObserverProfilePolicyService($this->policyService); + $this->signerLanguageService = $this->createMock(SignerLanguageService::class); $this->validator = new SignerValidator( $l10n, $this->signRequestMapper, @@ -71,6 +74,7 @@ public function setUp(): void { $this->docMdpValidator, $this->createMock(RuntimeRequirementValidator::class), $this->observerProfilePolicyService, + $this->signerLanguageService, ); } @@ -133,6 +137,42 @@ public function testRejectsDisplayNameLongerThan64Characters(): void { ]); } + #[DataProvider('signerLanguageCases')] + public function testValidateIdentifySignersChecksSignerLanguage(mixed $language, bool $valid): void { + $identifyMethod = $this->createMock(IIdentifyMethod::class); + $identifyMethod->method('getSignatureMethods')->willReturn([$this->createMock(ISignatureMethod::class)]); + $this->identifyMethodService->method('getInstanceOfIdentifyMethod')->willReturn($identifyMethod); + $this->signerLanguageService + ->method('isAvailable') + ->willReturnCallback(static fn (string $code): bool => in_array($code, ['de', 'pt_BR'], true)); + + if (!$valid) { + $this->expectException(LibresignException::class); + $this->expectExceptionMessage('Invalid language'); + } + $this->validator->validateIdentifySigners([ + 'signers' => [[ + 'language' => $language, + 'identifyMethods' => [['method' => 'email', 'value' => 'alice@example.com']], + ]], + ]); + if ($valid) { + $this->addToAssertionCount(1); + } + } + + public static function signerLanguageCases(): array { + return [ + 'available language' => ['de', true], + 'available regional language' => ['pt_BR', true], + 'empty value clears the choice' => ['', true], + 'null clears the choice' => [null, true], + 'unknown language' => ['xx', false], + 'not a string' => [['de'], false], + 'number' => [1, false], + ]; + } + public function testIdentifySignerChecksDocMdpAndIdentifyMethod(): void { $file = new File(); $this->fileMapper->method('getByUuid')->with('file-uuid')->willReturn($file); @@ -394,6 +434,7 @@ private function rebuildValidator(): void { $this->docMdpValidator, $this->createMock(RuntimeRequirementValidator::class), $this->observerProfilePolicyService, + $this->signerLanguageService, ); } From ad7ce7e669c6f2aacf1f66c5ac8d9edda9f066d6 Mon Sep 17 00:00:00 2001 From: no84by <50858621+no84by@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:45:41 +0000 Subject: [PATCH 2/2] feat(request): choose the e-mail language for each signer Add an "E-mail language" select to the signer editor on the request page. It lists the languages LibreSign ships translations for, named in the language of the requester, with "Default language" first. The select is shown only when the participant receives e-mails and more than one language is available. The chosen value is sent as the signer `language` field and restored from the signer metadata when editing. Signed-off-by: no84by <50858621+no84by@users.noreply.github.com> --- src/components/Request/IdentifySigner.vue | 58 +++++++++- .../RightSidebar/RequestSignatureTab.vue | 12 ++- src/store/files.js | 3 + .../components/Request/IdentifySigner.spec.ts | 101 ++++++++++++++++++ src/tests/store/files.spec.ts | 30 ++++++ 5 files changed, 201 insertions(+), 3 deletions(-) diff --git a/src/components/Request/IdentifySigner.vue b/src/components/Request/IdentifySigner.vue index 461325c665..4d0dfb597b 100644 --- a/src/components/Request/IdentifySigner.vue +++ b/src/components/Request/IdentifySigner.vue @@ -49,6 +49,16 @@ resize="none" /> +
+ +
+
@@ -74,7 +84,8 @@