• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

LibreSign / libresign / 20211219725

14 Dec 2025 05:00PM UTC coverage: 44.205%. First build
20211219725

Pull #6184

github

web-flow
Merge 3d9652487 into e784c39bc
Pull Request #6184: refactor: extract status services

38 of 40 new or added lines in 3 files covered. (95.0%)

5950 of 13460 relevant lines covered (44.21%)

5.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.77
/lib/Service/RequestSignatureService.php
1
<?php
2

3
declare(strict_types=1);
4
/**
5
 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6
 * SPDX-License-Identifier: AGPL-3.0-or-later
7
 */
8

9
namespace OCA\Libresign\Service;
10

11
use OCA\Libresign\AppInfo\Application;
12
use OCA\Libresign\Db\File as FileEntity;
13
use OCA\Libresign\Db\FileElementMapper;
14
use OCA\Libresign\Db\FileMapper;
15
use OCA\Libresign\Db\IdentifyMethodMapper;
16
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
17
use OCA\Libresign\Db\SignRequestMapper;
18
use OCA\Libresign\Enum\SignatureFlow;
19
use OCA\Libresign\Events\SignRequestCanceledEvent;
20
use OCA\Libresign\Handler\DocMdpHandler;
21
use OCA\Libresign\Helper\ValidateHelper;
22
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
23
use OCP\AppFramework\Db\DoesNotExistException;
24
use OCP\EventDispatcher\IEventDispatcher;
25
use OCP\Files\IMimeTypeDetector;
26
use OCP\Files\Node;
27
use OCP\Http\Client\IClientService;
28
use OCP\IAppConfig;
29
use OCP\IL10N;
30
use OCP\IUser;
31
use OCP\IUserManager;
32
use Psr\Log\LoggerInterface;
33
use Sabre\DAV\UUIDUtil;
34

35
class RequestSignatureService {
36
        use TFile;
37

38
        public function __construct(
39
                protected IL10N $l10n,
40
                protected IdentifyMethodService $identifyMethod,
41
                protected SignRequestMapper $signRequestMapper,
42
                protected IUserManager $userManager,
43
                protected FileMapper $fileMapper,
44
                protected IdentifyMethodMapper $identifyMethodMapper,
45
                protected PdfParserService $pdfParserService,
46
                protected FileElementService $fileElementService,
47
                protected FileElementMapper $fileElementMapper,
48
                protected FolderService $folderService,
49
                protected IMimeTypeDetector $mimeTypeDetector,
50
                protected ValidateHelper $validateHelper,
51
                protected IClientService $client,
52
                protected DocMdpHandler $docMdpHandler,
53
                protected LoggerInterface $logger,
54
                protected SequentialSigningService $sequentialSigningService,
55
                protected IAppConfig $appConfig,
56
                protected IEventDispatcher $eventDispatcher,
57
                protected FileStatusService $fileStatusService,
58
                protected SignRequestStatusService $signRequestStatusService,
59
        ) {
60
        }
54✔
61

62
        public function save(array $data): FileEntity {
63
                $file = $this->saveFile($data);
14✔
64
                $this->saveVisibleElements($data, $file);
14✔
65
                if (!isset($data['status'])) {
14✔
66
                        $data['status'] = $file->getStatus();
12✔
67
                }
68
                $this->sequentialSigningService->setFile($file);
14✔
69
                $this->associateToSigners($data, $file->getId());
14✔
70
                return $file;
14✔
71
        }
72

73
        /**
74
         * Save file data
75
         *
76
         * @param array{?userManager: IUser, ?signRequest: SignRequest, name: string, callback: string, uuid?: ?string, status: int, file?: array{fileId?: int, fileNode?: Node}} $data
77
         */
78
        public function saveFile(array $data): FileEntity {
79
                if (!empty($data['uuid'])) {
15✔
80
                        $file = $this->fileMapper->getByUuid($data['uuid']);
1✔
81
                        return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
1✔
82
                }
83
                $fileId = null;
15✔
84
                if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
15✔
85
                        $fileId = $data['file']['fileNode']->getId();
1✔
86
                } elseif (!empty($data['file']['fileId'])) {
14✔
87
                        $fileId = $data['file']['fileId'];
×
88
                }
89
                if (!is_null($fileId)) {
15✔
90
                        try {
91
                                $file = $this->fileMapper->getByFileId($fileId);
1✔
NEW
92
                                return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
×
93
                        } catch (\Throwable) {
1✔
94
                        }
95
                }
96

97
                $node = $this->getNodeFromData($data);
15✔
98

99
                $file = new FileEntity();
15✔
100
                $file->setNodeId($node->getId());
15✔
101
                if ($data['userManager'] instanceof IUser) {
15✔
102
                        $file->setUserId($data['userManager']->getUID());
15✔
103
                } elseif ($data['signRequest'] instanceof SignRequestEntity) {
×
104
                        $file->setSignRequestId($data['signRequest']->getId());
×
105
                }
106
                $file->setUuid(UUIDUtil::getUUID());
15✔
107
                $file->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
15✔
108
                $metadata = $this->getFileMetadata($node);
15✔
109
                $file->setName($this->removeExtensionFromName($data['name'], $metadata));
15✔
110
                $file->setMetadata($metadata);
15✔
111
                if (!empty($data['callback'])) {
15✔
112
                        $file->setCallback($data['callback']);
×
113
                }
114
                if (isset($data['status'])) {
15✔
115
                        $file->setStatus($data['status']);
2✔
116
                } else {
117
                        $file->setStatus(FileEntity::STATUS_ABLE_TO_SIGN);
13✔
118
                }
119

120
                if (isset($data['signatureFlow']) && is_string($data['signatureFlow'])) {
15✔
121
                        try {
122
                                $signatureFlow = \OCA\Libresign\Enum\SignatureFlow::from($data['signatureFlow']);
×
123
                                $file->setSignatureFlowEnum($signatureFlow);
×
124
                        } catch (\ValueError) {
×
125
                                $this->setSignatureFlowFromGlobalConfig($file);
×
126
                        }
127
                } else {
128
                        $this->setSignatureFlowFromGlobalConfig($file);
15✔
129
                }
130

131
                $this->fileMapper->insert($file);
15✔
132
                return $file;
15✔
133
        }
134

135
        private function setSignatureFlowFromGlobalConfig(FileEntity $file): void {
136
                $globalFlowValue = $this->appConfig->getValueString(Application::APP_ID, 'signature_flow', SignatureFlow::PARALLEL->value);
15✔
137
                $globalFlow = SignatureFlow::from($globalFlowValue);
15✔
138
                $file->setSignatureFlowEnum($globalFlow);
15✔
139
        }
140

141
        private function getFileMetadata(\OCP\Files\Node $node): array {
142
                $metadata = [];
18✔
143
                if ($extension = strtolower($node->getExtension())) {
18✔
144
                        $metadata = [
17✔
145
                                'extension' => $extension,
17✔
146
                        ];
17✔
147
                        if ($metadata['extension'] === 'pdf') {
17✔
148
                                $metadata = array_merge(
16✔
149
                                        $metadata,
16✔
150
                                        $this->pdfParserService
16✔
151
                                                ->setFile($node)
16✔
152
                                                ->getPageDimensions()
16✔
153
                                );
16✔
154
                        }
155
                }
156
                return $metadata;
18✔
157
        }
158

159
        private function removeExtensionFromName(string $name, array $metadata): string {
160
                if (!isset($metadata['extension'])) {
15✔
161
                        return $name;
×
162
                }
163
                $extensionPattern = '/\.' . preg_quote($metadata['extension'], '/') . '$/i';
15✔
164
                $result = preg_replace($extensionPattern, '', $name);
15✔
165
                return $result ?? $name;
15✔
166
        }
167

168
        private function deleteIdentifyMethodIfNotExits(array $users, int $fileId): void {
169
                $file = $this->fileMapper->getById($fileId);
13✔
170
                $signRequests = $this->signRequestMapper->getByFileId($fileId);
13✔
171
                foreach ($signRequests as $key => $signRequest) {
13✔
172
                        $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequest->getId());
1✔
173
                        if (empty($identifyMethods)) {
1✔
174
                                $this->unassociateToUser($file->getNodeId(), $signRequest->getId());
×
175
                                continue;
×
176
                        }
177
                        foreach ($identifyMethods as $methodName => $list) {
1✔
178
                                foreach ($list as $method) {
1✔
179
                                        $exists[$key]['identify'][$methodName] = $method->getEntity()->getIdentifierValue();
1✔
180
                                        if (!$this->identifyMethodExists($users, $method)) {
1✔
181
                                                $this->unassociateToUser($file->getNodeId(), $signRequest->getId());
1✔
182
                                                continue 3;
1✔
183
                                        }
184
                                }
185
                        }
186
                }
187
        }
188

189
        private function identifyMethodExists(array $users, IIdentifyMethod $identifyMethod): bool {
190
                foreach ($users as $user) {
1✔
191
                        if (!empty($user['identifyMethods'])) {
1✔
192
                                foreach ($user['identifyMethods'] as $data) {
×
193
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $data['method']) {
×
194
                                                continue;
×
195
                                        }
196
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $data['value']) {
×
197
                                                return true;
×
198
                                        }
199
                                }
200
                        } else {
201
                                foreach ($user['identify'] as $method => $value) {
1✔
202
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $method) {
1✔
203
                                                continue;
×
204
                                        }
205
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $value) {
1✔
206
                                                return true;
×
207
                                        }
208
                                }
209
                        }
210
                }
211
                return false;
1✔
212
        }
213

214
        /**
215
         * @return SignRequestEntity[]
216
         *
217
         * @psalm-return list<SignRequestEntity>
218
         */
219
        private function associateToSigners(array $data, int $fileId): array {
220
                $return = [];
14✔
221
                if (!empty($data['users'])) {
14✔
222
                        $this->deleteIdentifyMethodIfNotExits($data['users'], $fileId);
13✔
223

224
                        $this->sequentialSigningService->resetOrderCounter();
13✔
225
                        $fileStatus = $data['status'] ?? null;
13✔
226

227
                        foreach ($data['users'] as $user) {
13✔
228
                                $userProvidedOrder = isset($user['signingOrder']) ? (int)$user['signingOrder'] : null;
13✔
229
                                $signingOrder = $this->sequentialSigningService->determineSigningOrder($userProvidedOrder);
13✔
230
                                $signerStatus = $user['status'] ?? null;
13✔
231

232
                                if (isset($user['identifyMethods'])) {
13✔
233
                                        foreach ($user['identifyMethods'] as $identifyMethod) {
×
234
                                                $return[] = $this->associateToSigner(
×
235
                                                        identifyMethods: [
×
236
                                                                $identifyMethod['method'] => $identifyMethod['value'],
×
237
                                                        ],
×
238
                                                        displayName: $user['displayName'] ?? '',
×
239
                                                        description: $user['description'] ?? '',
×
NEW
240
                                                        notify: empty($user['notify']),
×
241
                                                        fileId: $fileId,
×
242
                                                        signingOrder: $signingOrder,
×
243
                                                        fileStatus: $fileStatus,
×
244
                                                        signerStatus: $signerStatus,
×
245
                                                );
×
246
                                        }
247
                                } else {
248
                                        $return[] = $this->associateToSigner(
13✔
249
                                                identifyMethods: $user['identify'],
13✔
250
                                                displayName: $user['displayName'] ?? '',
13✔
251
                                                description: $user['description'] ?? '',
13✔
252
                                                notify: empty($user['notify']),
13✔
253
                                                fileId: $fileId,
13✔
254
                                                signingOrder: $signingOrder,
13✔
255
                                                fileStatus: $fileStatus,
13✔
256
                                                signerStatus: $signerStatus,
13✔
257
                                        );
13✔
258
                                }
259
                        }
260
                }
261
                return $return;
14✔
262
        }
263

264
        private function associateToSigner(
265
                array $identifyMethods,
266
                string $displayName,
267
                string $description,
268
                bool $notify,
269
                int $fileId,
270
                int $signingOrder = 0,
271
                ?int $fileStatus = null,
272
                ?int $signerStatus = null,
273
        ): SignRequestEntity {
274
                $identifyMethodsIncances = $this->identifyMethod->getByUserData($identifyMethods);
13✔
275
                if (empty($identifyMethodsIncances)) {
13✔
276
                        throw new \Exception($this->l10n->t('Invalid identification method'));
×
277
                }
278
                $signRequest = $this->getSignRequestByIdentifyMethod(
13✔
279
                        current($identifyMethodsIncances),
13✔
280
                        $fileId
13✔
281
                );
13✔
282
                $displayName = $this->getDisplayNameFromIdentifyMethodIfEmpty($identifyMethodsIncances, $displayName);
13✔
283
                $this->setDataToUser($signRequest, $displayName, $description, $fileId);
13✔
284

285
                $signRequest->setSigningOrder($signingOrder);
13✔
286

287
                $isNewSignRequest = !$signRequest->getId();
13✔
288
                $currentStatus = $signRequest->getStatusEnum();
13✔
289

290
                if ($isNewSignRequest || $currentStatus === \OCA\Libresign\Enum\SignRequestStatus::DRAFT) {
13✔
291
                        $desiredStatus = $this->signRequestStatusService->determineInitialStatus($signingOrder, $fileId, $fileStatus, $signerStatus, $currentStatus);
13✔
292
                        $this->signRequestStatusService->updateStatusIfAllowed($signRequest, $currentStatus, $desiredStatus, $isNewSignRequest);
13✔
293
                }
294

295
                $this->saveSignRequest($signRequest);
13✔
296

297
                $shouldNotify = $notify && $this->signRequestStatusService->shouldNotifySignRequest(
13✔
298
                        $signRequest->getStatusEnum(),
13✔
299
                        $fileStatus
13✔
300
                );
13✔
301

302
                foreach ($identifyMethodsIncances as $identifyMethod) {
13✔
303
                        $identifyMethod->getEntity()->setSignRequestId($signRequest->getId());
13✔
304
                        $identifyMethod->willNotifyUser($shouldNotify);
13✔
305
                        $identifyMethod->save();
13✔
306
                }
307
                return $signRequest;
13✔
308
        }
309

310
        /**
311
         * @param IIdentifyMethod[] $identifyMethodsIncances
312
         * @param string $displayName
313
         * @return string
314
         */
315
        private function getDisplayNameFromIdentifyMethodIfEmpty(array $identifyMethodsIncances, string $displayName): string {
316
                if (!empty($displayName)) {
13✔
317
                        return $displayName;
×
318
                }
319
                foreach ($identifyMethodsIncances as $identifyMethod) {
13✔
320
                        if ($identifyMethod->getName() === 'account') {
13✔
321
                                return $this->userManager->get($identifyMethod->getEntity()->getIdentifierValue())->getDisplayName();
2✔
322
                        }
323
                }
324
                foreach ($identifyMethodsIncances as $identifyMethod) {
11✔
325
                        if ($identifyMethod->getName() !== 'account') {
11✔
326
                                return $identifyMethod->getEntity()->getIdentifierValue();
11✔
327
                        }
328
                }
329
                return '';
×
330
        }
331

332
        private function saveVisibleElements(array $data, FileEntity $file): array {
333
                if (empty($data['visibleElements'])) {
17✔
334
                        return [];
15✔
335
                }
336
                $elements = $data['visibleElements'];
2✔
337
                foreach ($elements as $key => $element) {
2✔
338
                        $element['fileId'] = $file->getId();
2✔
339
                        $elements[$key] = $this->fileElementService->saveVisibleElement($element);
2✔
340
                }
341
                return $elements;
2✔
342
        }
343

344
        public function validateNewRequestToFile(array $data): void {
345
                $this->validateNewFile($data);
7✔
346
                $this->validateUsers($data);
6✔
347
                $this->validateHelper->validateFileStatus($data);
2✔
348
        }
349

350
        public function validateNewFile(array $data): void {
351
                if (empty($data['name'])) {
7✔
352
                        throw new \Exception($this->l10n->t('Name is mandatory'));
1✔
353
                }
354
                $this->validateHelper->validateNewFile($data);
6✔
355
        }
356

357
        public function validateUsers(array $data): void {
358
                if (empty($data['users'])) {
6✔
359
                        throw new \Exception($this->l10n->t('Empty users list'));
3✔
360
                }
361
                if (!is_array($data['users'])) {
3✔
362
                        // TRANSLATION This message will be displayed when the request to API with the key users has a value that is not an array
363
                        throw new \Exception($this->l10n->t('User list needs to be an array'));
1✔
364
                }
365
                foreach ($data['users'] as $user) {
2✔
366
                        if (!array_key_exists('identify', $user)) {
2✔
367
                                throw new \Exception('Identify key not found');
×
368
                        }
369
                        $this->identifyMethod->setAllEntityData($user);
2✔
370
                }
371
        }
372

373
        public function saveSignRequest(SignRequestEntity $signRequest): void {
374
                if ($signRequest->getId()) {
15✔
375
                        $this->signRequestMapper->update($signRequest);
1✔
376
                } else {
377
                        $this->signRequestMapper->insert($signRequest);
14✔
378
                }
379
        }
380

381
        /**
382
         * @psalm-suppress MixedMethodCall
383
         */
384
        private function setDataToUser(SignRequestEntity $signRequest, string $displayName, string $description, int $fileId): void {
385
                $signRequest->setFileId($fileId);
13✔
386
                if (!$signRequest->getUuid()) {
13✔
387
                        $signRequest->setUuid(UUIDUtil::getUUID());
13✔
388
                }
389
                if (!empty($displayName)) {
13✔
390
                        $signRequest->setDisplayName($displayName);
13✔
391
                }
392
                if (!empty($description)) {
13✔
393
                        $signRequest->setDescription($description);
×
394
                }
395
                if (!$signRequest->getId()) {
13✔
396
                        $signRequest->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
13✔
397
                }
398
        }
399

400
        private function getSignRequestByIdentifyMethod(IIdentifyMethod $identifyMethod, int $fileId): SignRequestEntity {
401
                try {
402
                        $signRequest = $this->signRequestMapper->getByIdentifyMethodAndFileId($identifyMethod, $fileId);
13✔
403
                } catch (DoesNotExistException) {
13✔
404
                        $signRequest = new SignRequestEntity();
13✔
405
                }
406
                return $signRequest;
13✔
407
        }
408

409
        public function unassociateToUser(int $fileId, int $signRequestId): void {
410
                $signRequest = $this->signRequestMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
411
                $deletedOrder = $signRequest->getSigningOrder();
2✔
412
                $groupedIdentifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
413

414
                $this->dispatchCancellationEventIfNeeded($signRequest, $fileId, $groupedIdentifyMethods);
2✔
415

416
                try {
417
                        $this->signRequestMapper->delete($signRequest);
2✔
418
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
419
                                foreach ($identifyMethods as $identifyMethod) {
2✔
420
                                        $identifyMethod->delete();
2✔
421
                                }
422
                        }
423
                        $visibleElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
424
                        foreach ($visibleElements as $visibleElement) {
2✔
425
                                $this->fileElementMapper->delete($visibleElement);
×
426
                        }
427

428
                        $this->sequentialSigningService->reorderAfterDeletion($fileId, $deletedOrder);
2✔
429
                } catch (\Throwable) {
×
430
                }
431
        }
432

433
        private function dispatchCancellationEventIfNeeded(
434
                SignRequestEntity $signRequest,
435
                int $fileId,
436
                array $groupedIdentifyMethods,
437
        ): void {
438
                if ($signRequest->getStatus() !== \OCA\Libresign\Enum\SignRequestStatus::ABLE_TO_SIGN->value) {
2✔
439
                        return;
×
440
                }
441

442
                try {
443
                        $libreSignFile = $this->fileMapper->getByFileId($fileId);
2✔
444
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
445
                                foreach ($identifyMethods as $identifyMethod) {
2✔
446
                                        $event = new SignRequestCanceledEvent(
2✔
447
                                                $signRequest,
2✔
448
                                                $libreSignFile,
2✔
449
                                                $identifyMethod,
2✔
450
                                        );
2✔
451
                                        $this->eventDispatcher->dispatchTyped($event);
2✔
452
                                }
453
                        }
454
                } catch (\Throwable $e) {
×
455
                        $this->logger->error('Error dispatching SignRequestCanceledEvent: ' . $e->getMessage(), ['exception' => $e]);
×
456
                }
457
        }
458

459
        public function deleteRequestSignature(array $data): void {
460
                if (!empty($data['uuid'])) {
2✔
461
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
×
462
                        $fileData = $this->fileMapper->getByUuid($data['uuid']);
×
463
                } elseif (!empty($data['file']['fileId'])) {
2✔
464
                        $signatures = $this->signRequestMapper->getByNodeId($data['file']['fileId']);
2✔
465
                        $fileData = $this->fileMapper->getByFileId($data['file']['fileId']);
2✔
466
                } else {
467
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
468
                }
469
                foreach ($signatures as $signRequest) {
2✔
470
                        $this->signRequestMapper->delete($signRequest);
2✔
471
                }
472
                $this->fileMapper->delete($fileData);
2✔
473
                $this->fileElementService->deleteVisibleElements($fileData->getId());
2✔
474
        }
475
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc