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

LibreSign / libresign / 20660742393

02 Jan 2026 03:15PM UTC coverage: 44.876%. First build
20660742393

Pull #6302

github

web-flow
Merge 928956222 into cfd974a7d
Pull Request #6302: feat: envelope custom path

77 of 126 new or added lines in 6 files covered. (61.11%)

6660 of 14841 relevant lines covered (44.88%)

5.07 hits per line

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

48.48
/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\Exception\LibresignException;
21
use OCA\Libresign\Handler\DocMdpHandler;
22
use OCA\Libresign\Helper\FileUploadHelper;
23
use OCA\Libresign\Helper\ValidateHelper;
24
use OCA\Libresign\Service\Envelope\EnvelopeFileRelocator;
25
use OCA\Libresign\Service\Envelope\EnvelopeService;
26
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
27
use OCP\EventDispatcher\IEventDispatcher;
28
use OCP\Files\IMimeTypeDetector;
29
use OCP\Files\Node;
30
use OCP\Http\Client\IClientService;
31
use OCP\IAppConfig;
32
use OCP\IL10N;
33
use OCP\IUser;
34
use OCP\IUserManager;
35
use Psr\Log\LoggerInterface;
36
use Sabre\DAV\UUIDUtil;
37

38
class RequestSignatureService {
39

40
        public function __construct(
41
                protected FileService $fileService,
42
                protected IL10N $l10n,
43
                protected IdentifyMethodService $identifyMethod,
44
                protected SignRequestMapper $signRequestMapper,
45
                protected IUserManager $userManager,
46
                protected FileMapper $fileMapper,
47
                protected IdentifyMethodMapper $identifyMethodMapper,
48
                protected PdfParserService $pdfParserService,
49
                protected FileElementService $fileElementService,
50
                protected FileElementMapper $fileElementMapper,
51
                protected FolderService $folderService,
52
                protected IMimeTypeDetector $mimeTypeDetector,
53
                protected ValidateHelper $validateHelper,
54
                protected IClientService $client,
55
                protected DocMdpHandler $docMdpHandler,
56
                protected LoggerInterface $logger,
57
                protected SequentialSigningService $sequentialSigningService,
58
                protected IAppConfig $appConfig,
59
                protected IEventDispatcher $eventDispatcher,
60
                protected FileStatusService $fileStatusService,
61
                protected DocMdpConfigService $docMdpConfigService,
62
                protected EnvelopeService $envelopeService,
63
                protected EnvelopeFileRelocator $envelopeFileRelocator,
64
                protected FileUploadHelper $uploadHelper,
65
                protected SignRequestService $signRequestService,
66
        ) {
67
        }
52✔
68

69
        /**
70
         * Save files - creates single file or envelope based on files count
71
         *
72
         * @param array{files: array, name: string, settings: array, userManager: IUser} $data
73
         * @return array{file: FileEntity, children: FileEntity[]}
74
         */
75
        public function saveFiles(array $data): array {
76
                if (empty($data['files'])) {
1✔
77
                        throw new LibresignException('Files parameter is required');
×
78
                }
79

80
                if (count($data['files']) === 1) {
1✔
81
                        $fileData = $data['files'][0];
1✔
82

83
                        $saveData = [
1✔
84
                                'name' => $data['name'] ?? $fileData['name'] ?? '',
1✔
85
                                'userManager' => $data['userManager'],
1✔
86
                                'status' => FileEntity::STATUS_DRAFT,
1✔
87
                                'settings' => $data['settings'],
1✔
88
                        ];
1✔
89

90
                        if (isset($fileData['uploadedFile'])) {
1✔
91
                                $saveData['uploadedFile'] = $fileData['uploadedFile'];
×
92
                        } elseif (isset($fileData['fileNode'])) {
1✔
93
                                $saveData['file'] = ['fileNode' => $fileData['fileNode']];
×
94
                        } else {
95
                                $saveData['file'] = $fileData;
1✔
96
                        }
97

98
                        $savedFile = $this->save($saveData);
1✔
99

100
                        return [
1✔
101
                                'file' => $savedFile,
1✔
102
                                'children' => [$savedFile],
1✔
103
                        ];
1✔
104
                }
105

106
                $result = $this->saveEnvelope([
×
107
                        'files' => $data['files'],
×
108
                        'name' => $data['name'],
×
109
                        'userManager' => $data['userManager'],
×
110
                        'settings' => $data['settings'],
×
111
                ]);
×
112

113
                return [
×
114
                        'file' => $result['envelope'],
×
115
                        'children' => $result['files'],
×
116
                ];
×
117
        }
118

119
        public function save(array $data): FileEntity {
120
                $file = $this->saveFile($data);
14✔
121
                if (!isset($data['status'])) {
14✔
122
                        $data['status'] = $file->getStatus();
12✔
123
                }
124
                $this->sequentialSigningService->setFile($file);
14✔
125
                $this->associateToSigners($data, $file);
14✔
126
                $this->propagateSignersToChildren($file, $data);
14✔
127
                $this->saveVisibleElements($data, $file);
14✔
128

129
                return $file;
14✔
130
        }
131

132
        private function propagateSignersToChildren(FileEntity $envelope, array $data): void {
133
                if ($envelope->getNodeType() !== 'envelope' || empty($data['users'])) {
14✔
134
                        return;
14✔
135
                }
136

137
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
138

139
                $dataWithoutNotification = $data;
×
140
                foreach ($dataWithoutNotification['users'] as &$user) {
×
141
                        $user['notify'] = 0;
×
142
                }
143

144
                foreach ($children as $child) {
×
145
                        $this->identifyMethod->clearCache();
×
146
                        $this->sequentialSigningService->setFile($child);
×
147
                        $this->associateToSigners($dataWithoutNotification, $child);
×
148
                }
149

150
                if ($envelope->getStatus() > FileEntity::STATUS_DRAFT) {
×
151
                        $this->fileStatusService->propagateStatusToChildren($envelope->getId(), $envelope->getStatus());
×
152
                }
153
        }
154

155
        public function saveEnvelope(array $data): array {
156
                $this->envelopeService->validateEnvelopeConstraints(count($data['files']));
×
157

158
                $envelopeName = $data['name'] ?: $this->l10n->t('Envelope %s', [date('Y-m-d H:i:s')]);
×
159
                $userManager = $data['userManager'] ?? null;
×
160
                $userId = $userManager instanceof IUser ? $userManager->getUID() : null;
×
161
                $filesCount = count($data['files']);
×
162

163
                $envelope = null;
×
164
                $files = [];
×
165
                $createdNodes = [];
×
166

167
                try {
NEW
168
                        $envelopePath = $data['settings']['path'] ?? null;
×
NEW
169
                        $envelope = $this->envelopeService->createEnvelope($envelopeName, $userId, $filesCount, $envelopePath);
×
170

171
                        $envelopeFolder = $this->envelopeService->getEnvelopeFolder($envelope);
×
172
                        $envelopeSettings = array_merge($data['settings'] ?? [], [
×
173
                                'envelopeFolderId' => $envelopeFolder->getId(),
×
174
                        ]);
×
175

176
                        foreach ($data['files'] as $fileData) {
×
177
                                $node = $this->processFileData($fileData, $userManager, $envelopeSettings);
×
178
                                $createdNodes[] = $node;
×
179

180
                                $fileData['node'] = $node;
×
181
                                $fileEntity = $this->createFileForEnvelope($fileData, $userManager, $envelopeSettings);
×
182
                                $this->envelopeService->addFileToEnvelope($envelope->getId(), $fileEntity);
×
183
                                $files[] = $fileEntity;
×
184
                        }
185

186
                        return [
×
187
                                'envelope' => $envelope,
×
188
                                'files' => $files,
×
189
                        ];
×
190
                } catch (\Throwable $e) {
×
191
                        $this->rollbackEnvelopeCreation($envelope, $files, $createdNodes);
×
192
                        throw $e;
×
193
                }
194
        }
195

196
        private function processFileData(array $fileData, ?IUser $userManager, array $settings): Node {
197
                if (isset($fileData['uploadedFile'])) {
×
NEW
198
                        $sourceNode = $this->fileService->getNodeFromData([
×
199
                                'userManager' => $userManager,
×
200
                                'name' => $fileData['name'] ?? '',
×
201
                                'uploadedFile' => $fileData['uploadedFile'],
×
202
                                'settings' => $settings,
×
203
                        ]);
×
204
                } else {
NEW
205
                        $sourceNode = $this->fileService->getNodeFromData([
×
NEW
206
                                'userManager' => $userManager,
×
NEW
207
                                'name' => $fileData['name'] ?? '',
×
NEW
208
                                'file' => $fileData,
×
NEW
209
                                'settings' => $settings,
×
NEW
210
                        ]);
×
211
                }
212

NEW
213
                if (isset($settings['envelopeFolderId'])) {
×
NEW
214
                        return $this->envelopeFileRelocator->ensureFileInEnvelopeFolder(
×
NEW
215
                                $sourceNode,
×
NEW
216
                                $settings['envelopeFolderId'],
×
NEW
217
                                $userManager,
×
NEW
218
                        );
×
219
                }
220

NEW
221
                return $sourceNode;
×
222
        }
223

224
        private function rollbackEnvelopeCreation(?FileEntity $envelope, array $files, array $createdNodes): void {
225
                $this->rollbackCreatedNodes($createdNodes);
×
226
                $this->rollbackCreatedFiles($files);
×
227
                $this->rollbackEnvelope($envelope);
×
228
        }
229

230
        private function rollbackCreatedNodes(array $nodes): void {
231
                foreach ($nodes as $node) {
×
232
                        try {
233
                                $node->delete();
×
234
                        } catch (\Throwable $deleteError) {
×
235
                                $this->logger->error('Failed to rollback created node in envelope', [
×
236
                                        'nodeId' => $node->getId(),
×
237
                                        'error' => $deleteError->getMessage(),
×
238
                                ]);
×
239
                        }
240
                }
241
        }
242

243
        private function rollbackCreatedFiles(array $files): void {
244
                foreach ($files as $file) {
×
245
                        try {
246
                                $this->fileMapper->delete($file);
×
247
                        } catch (\Throwable $deleteError) {
×
248
                                $this->logger->error('Failed to rollback created file entity in envelope', [
×
249
                                        'fileId' => $file->getId(),
×
250
                                        'error' => $deleteError->getMessage(),
×
251
                                ]);
×
252
                        }
253
                }
254
        }
255

256
        private function rollbackEnvelope(?FileEntity $envelope): void {
257
                if ($envelope === null) {
×
258
                        return;
×
259
                }
260

261
                try {
262
                        $this->fileMapper->delete($envelope);
×
263
                } catch (\Throwable $deleteError) {
×
264
                        $this->logger->error('Failed to rollback created envelope', [
×
265
                                'envelopeId' => $envelope->getId(),
×
266
                                'error' => $deleteError->getMessage(),
×
267
                        ]);
×
268
                }
269
        }
270

271
        private function createFileForEnvelope(array $fileData, ?IUser $userManager, array $settings): FileEntity {
272
                if (!isset($fileData['node'])) {
×
273
                        throw new \InvalidArgumentException('Node not provided in file data');
×
274
                }
275

276
                $node = $fileData['node'];
×
277
                $fileName = $fileData['name'] ?? $node->getName();
×
278

279
                return $this->saveFile([
×
280
                        'file' => ['fileNode' => $node],
×
281
                        'name' => $fileName,
×
282
                        'userManager' => $userManager,
×
283
                        'status' => FileEntity::STATUS_DRAFT,
×
284
                        'settings' => $settings,
×
285
                ]);
×
286
        }
287

288
        /**
289
         * Save file data
290
         *
291
         * @param array{?userManager: IUser, ?signRequest: SignRequest, name: string, callback: string, uuid?: ?string, status: int, file?: array{fileId?: int, fileNode?: Node}} $data
292
         */
293
        public function saveFile(array $data): FileEntity {
294
                if (!empty($data['uuid'])) {
15✔
295
                        $file = $this->fileMapper->getByUuid($data['uuid']);
1✔
296
                        $this->updateSignatureFlowIfAllowed($file, $data);
1✔
297
                        if (!empty($data['name'])) {
1✔
298
                                $file->setName($data['name']);
×
299
                                $this->fileMapper->update($file);
×
300
                        }
301
                        return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
1✔
302
                }
303
                $fileId = null;
15✔
304
                if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
15✔
305
                        $fileId = $data['file']['fileNode']->getId();
×
306
                } elseif (!empty($data['file']['fileId'])) {
15✔
307
                        $fileId = $data['file']['fileId'];
×
308
                }
309
                if (!is_null($fileId)) {
15✔
310
                        try {
311
                                $file = $this->fileMapper->getByNodeId($fileId);
×
312
                                $this->updateSignatureFlowIfAllowed($file, $data);
×
313
                                return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
×
314
                        } catch (\Throwable) {
×
315
                        }
316
                }
317

318
                $node = $this->fileService->getNodeFromData($data);
15✔
319

320
                $file = new FileEntity();
15✔
321
                $file->setNodeId($node->getId());
15✔
322
                if ($data['userManager'] instanceof IUser) {
15✔
323
                        $file->setUserId($data['userManager']->getUID());
15✔
324
                } elseif ($data['signRequest'] instanceof SignRequestEntity) {
×
325
                        $file->setSignRequestId($data['signRequest']->getId());
×
326
                }
327
                $file->setUuid(UUIDUtil::getUUID());
15✔
328
                $file->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
15✔
329
                $metadata = $this->getFileMetadata($node);
15✔
330
                $name = trim((string)($data['name'] ?? ''));
15✔
331
                if ($name === '') {
15✔
332
                        $name = $node->getName();
×
333
                }
334
                $file->setName($this->removeExtensionFromName($name, $metadata));
15✔
335
                $file->setMetadata($metadata);
15✔
336
                if (!empty($data['callback'])) {
15✔
337
                        $file->setCallback($data['callback']);
×
338
                }
339
                if (isset($data['status'])) {
15✔
340
                        $file->setStatus($data['status']);
2✔
341
                } else {
342
                        $file->setStatus(FileEntity::STATUS_ABLE_TO_SIGN);
13✔
343
                }
344

345
                if (isset($data['parentFileId'])) {
15✔
346
                        $file->setParentFileId($data['parentFileId']);
×
347
                }
348

349
                $this->setSignatureFlow($file, $data);
15✔
350
                $this->setDocMdpLevelFromGlobalConfig($file);
15✔
351

352
                $this->fileMapper->insert($file);
15✔
353
                return $file;
15✔
354
        }
355

356
        private function updateSignatureFlowIfAllowed(FileEntity $file, array $data): void {
357
                $adminFlow = $this->appConfig->getValueString(Application::APP_ID, 'signature_flow', SignatureFlow::NONE->value);
1✔
358
                $adminForcedConfig = $adminFlow !== SignatureFlow::NONE->value;
1✔
359

360
                if ($adminForcedConfig) {
1✔
361
                        $adminFlowEnum = SignatureFlow::from($adminFlow);
×
362
                        if ($file->getSignatureFlowEnum() !== $adminFlowEnum) {
×
363
                                $file->setSignatureFlowEnum($adminFlowEnum);
×
364
                                $this->fileMapper->update($file);
×
365
                        }
366
                        return;
×
367
                }
368

369
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
1✔
370
                        $newFlow = SignatureFlow::from($data['signatureFlow']);
×
371
                        if ($file->getSignatureFlowEnum() !== $newFlow) {
×
372
                                $file->setSignatureFlowEnum($newFlow);
×
373
                                $this->fileMapper->update($file);
×
374
                        }
375
                }
376
        }
377

378
        private function setSignatureFlow(FileEntity $file, array $data): void {
379
                $adminFlow = $this->appConfig->getValueString(Application::APP_ID, 'signature_flow', SignatureFlow::NONE->value);
15✔
380

381
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
15✔
382
                        $file->setSignatureFlowEnum(SignatureFlow::from($data['signatureFlow']));
×
383
                } elseif ($adminFlow !== SignatureFlow::NONE->value) {
15✔
384
                        $file->setSignatureFlowEnum(SignatureFlow::from($adminFlow));
×
385
                } else {
386
                        $file->setSignatureFlowEnum(SignatureFlow::NONE);
15✔
387
                }
388
        }
389

390
        private function setDocMdpLevelFromGlobalConfig(FileEntity $file): void {
391
                if ($this->docMdpConfigService->isEnabled()) {
15✔
392
                        $docmdpLevel = $this->docMdpConfigService->getLevel();
×
393
                        $file->setDocmdpLevelEnum($docmdpLevel);
×
394
                }
395
        }
396

397
        private function getFileMetadata(\OCP\Files\Node $node): array {
398
                $metadata = [];
18✔
399
                if ($extension = strtolower($node->getExtension())) {
18✔
400
                        $metadata = [
17✔
401
                                'extension' => $extension,
17✔
402
                        ];
17✔
403
                        if ($metadata['extension'] === 'pdf') {
17✔
404
                                $pdfParser = $this->pdfParserService->setFile($node);
16✔
405
                                $metadata = array_merge(
16✔
406
                                        $metadata,
16✔
407
                                        $pdfParser->getPageDimensions()
16✔
408
                                );
16✔
409
                                $metadata['pdfVersion'] = $pdfParser->getPdfVersion();
16✔
410
                        }
411
                }
412
                return $metadata;
18✔
413
        }
414

415
        private function removeExtensionFromName(string $name, array $metadata): string {
416
                if (!isset($metadata['extension'])) {
15✔
417
                        return $name;
×
418
                }
419
                $extensionPattern = '/\.' . preg_quote($metadata['extension'], '/') . '$/i';
15✔
420
                $result = preg_replace($extensionPattern, '', $name);
15✔
421
                return $result ?? $name;
15✔
422
        }
423

424
        private function deleteIdentifyMethodIfNotExits(array $users, FileEntity $file): void {
425
                $signRequests = $this->signRequestMapper->getByFileId($file->getId());
13✔
426
                foreach ($signRequests as $key => $signRequest) {
13✔
427
                        $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequest->getId());
1✔
428
                        if (empty($identifyMethods)) {
1✔
429
                                $this->unassociateToUser($file->getId(), $signRequest->getId());
×
430
                                continue;
×
431
                        }
432
                        foreach ($identifyMethods as $methodName => $list) {
1✔
433
                                foreach ($list as $method) {
1✔
434
                                        $exists[$key]['identify'][$methodName] = $method->getEntity()->getIdentifierValue();
1✔
435
                                        if (!$this->identifyMethodExists($users, $method)) {
1✔
436
                                                $this->unassociateToUser($file->getId(), $signRequest->getId());
1✔
437
                                                continue 3;
1✔
438
                                        }
439
                                }
440
                        }
441
                }
442
        }
443

444
        private function identifyMethodExists(array $users, IIdentifyMethod $identifyMethod): bool {
445
                foreach ($users as $user) {
1✔
446
                        if (!empty($user['identifyMethods'])) {
1✔
447
                                foreach ($user['identifyMethods'] as $data) {
×
448
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $data['method']) {
×
449
                                                continue;
×
450
                                        }
451
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $data['value']) {
×
452
                                                return true;
×
453
                                        }
454
                                }
455
                        } else {
456
                                foreach ($user['identify'] as $method => $value) {
1✔
457
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $method) {
1✔
458
                                                continue;
×
459
                                        }
460
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $value) {
1✔
461
                                                return true;
×
462
                                        }
463
                                }
464
                        }
465
                }
466
                return false;
1✔
467
        }
468

469
        /**
470
         * @return SignRequestEntity[]
471
         *
472
         * @psalm-return list<SignRequestEntity>
473
         */
474
        private function associateToSigners(array $data, FileEntity $file): array {
475
                $return = [];
14✔
476
                if (!empty($data['users'])) {
14✔
477
                        $this->deleteIdentifyMethodIfNotExits($data['users'], $file);
13✔
478

479
                        $this->sequentialSigningService->resetOrderCounter();
13✔
480
                        $fileStatus = $data['status'] ?? null;
13✔
481

482
                        foreach ($data['users'] as $user) {
13✔
483
                                $userProvidedOrder = isset($user['signingOrder']) ? (int)$user['signingOrder'] : null;
13✔
484
                                $signingOrder = $this->sequentialSigningService->determineSigningOrder($userProvidedOrder);
13✔
485
                                $signerStatus = $user['status'] ?? null;
13✔
486
                                $shouldNotify = !isset($user['notify']) || $user['notify'] !== 0;
13✔
487

488
                                if (isset($user['identifyMethods'])) {
13✔
489
                                        foreach ($user['identifyMethods'] as $identifyMethod) {
×
490
                                                $return[] = $this->signRequestService->createOrUpdateSignRequest(
×
491
                                                        identifyMethods: [
×
492
                                                                $identifyMethod['method'] => $identifyMethod['value'],
×
493
                                                        ],
×
494
                                                        displayName: $user['displayName'] ?? '',
×
495
                                                        description: $user['description'] ?? '',
×
496
                                                        notify: $shouldNotify,
×
497
                                                        fileId: $file->getId(),
×
498
                                                        signingOrder: $signingOrder,
×
499
                                                        fileStatus: $fileStatus,
×
500
                                                        signerStatus: $signerStatus,
×
501
                                                );
×
502
                                        }
503
                                } else {
504
                                        $return[] = $this->signRequestService->createOrUpdateSignRequest(
13✔
505
                                                identifyMethods: $user['identify'],
13✔
506
                                                displayName: $user['displayName'] ?? '',
13✔
507
                                                description: $user['description'] ?? '',
13✔
508
                                                notify: $shouldNotify,
13✔
509
                                                fileId: $file->getId(),
13✔
510
                                                signingOrder: $signingOrder,
13✔
511
                                                fileStatus: $fileStatus,
13✔
512
                                                signerStatus: $signerStatus,
13✔
513
                                        );
13✔
514
                                }
515
                        }
516
                }
517
                return $return;
14✔
518
        }
519

520

521

522
        private function saveVisibleElements(array $data, FileEntity $file): array {
523
                if (empty($data['visibleElements'])) {
17✔
524
                        return [];
15✔
525
                }
526
                $persisted = [];
2✔
527
                foreach ($data['visibleElements'] as $element) {
2✔
528
                        if ($file->isEnvelope() && !empty($element['signRequestId'])) {
2✔
529
                                $envelopeSignRequest = $this->signRequestMapper->getById((int)$element['signRequestId']);
×
530
                                // Only translate if the provided SR belongs to the envelope itself
531
                                if ($envelopeSignRequest && $envelopeSignRequest->getFileId() === $file->getId()) {
×
532
                                        $childrenSrs = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod($file->getId(), (int)$element['signRequestId']);
×
533
                                        foreach ($childrenSrs as $childSr) {
×
534
                                                if ($childSr->getFileId() === (int)$element['fileId']) {
×
535
                                                        $element['signRequestId'] = $childSr->getId();
×
536
                                                        break;
×
537
                                                }
538
                                        }
539
                                }
540
                        }
541

542
                        $persisted[] = $this->fileElementService->saveVisibleElement($element);
2✔
543
                }
544
                return $persisted;
2✔
545
        }
546

547

548
        public function validateNewRequestToFile(array $data): void {
549
                $this->validateNewFile($data);
7✔
550
                $this->validateUsers($data);
6✔
551
                $this->validateHelper->validateFileStatus($data);
2✔
552
        }
553

554
        public function validateNewFile(array $data): void {
555
                if (empty($data['name'])) {
7✔
556
                        throw new \Exception($this->l10n->t('Name is mandatory'));
1✔
557
                }
558
                $this->validateHelper->validateNewFile($data);
6✔
559
        }
560

561
        public function validateUsers(array $data): void {
562
                if (empty($data['users'])) {
6✔
563
                        throw new \Exception($this->l10n->t('Empty users list'));
3✔
564
                }
565
                if (!is_array($data['users'])) {
3✔
566
                        // TRANSLATION This message will be displayed when the request to API with the key users has a value that is not an array
567
                        throw new \Exception($this->l10n->t('User list needs to be an array'));
1✔
568
                }
569
                foreach ($data['users'] as $user) {
2✔
570
                        if (!array_key_exists('identify', $user)) {
2✔
571
                                throw new \Exception('Identify key not found');
×
572
                        }
573
                        $this->identifyMethod->setAllEntityData($user);
2✔
574
                }
575
        }
576

577

578

579
        public function unassociateToUser(int $fileId, int $signRequestId): void {
580
                $file = $this->fileMapper->getById($fileId);
2✔
581
                $signRequest = $this->signRequestMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
582
                $deletedOrder = $signRequest->getSigningOrder();
2✔
583
                $groupedIdentifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
584

585
                $this->dispatchCancellationEventIfNeeded($signRequest, $file, $groupedIdentifyMethods);
2✔
586

587
                try {
588
                        $this->signRequestMapper->delete($signRequest);
2✔
589
                        $this->identifyMethod->deleteBySignRequestId($signRequestId);
2✔
590
                        $visibleElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
591
                        foreach ($visibleElements as $visibleElement) {
2✔
592
                                $this->fileElementMapper->delete($visibleElement);
×
593
                        }
594

595
                        $this->sequentialSigningService
2✔
596
                                ->setFile($file)
2✔
597
                                ->reorderAfterDeletion($file->getId(), $deletedOrder);
2✔
598

599
                        $this->propagateSignerDeletionToChildren($file, $signRequest);
2✔
600
                } catch (\Throwable) {
×
601
                }
602
        }
603

604
        private function propagateSignerDeletionToChildren(FileEntity $envelope, SignRequestEntity $deletedSignRequest): void {
605
                if ($envelope->getNodeType() !== 'envelope') {
2✔
606
                        return;
2✔
607
                }
608

609
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
610

611
                $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($deletedSignRequest->getId());
×
612
                if (empty($identifyMethods)) {
×
613
                        return;
×
614
                }
615

616
                foreach ($children as $child) {
×
617
                        try {
618
                                $this->identifyMethod->clearCache();
×
619
                                $childSignRequest = $this->signRequestService->getSignRequestByIdentifyMethod(
×
620
                                        current(reset($identifyMethods)),
×
621
                                        $child->getId()
×
622
                                );
×
623

624
                                if ($childSignRequest->getId()) {
×
625
                                        $this->unassociateToUser($child->getId(), $childSignRequest->getId());
×
626
                                }
627
                        } catch (\Throwable $e) {
×
628
                                continue;
×
629
                        }
630
                }
631
        }
632

633
        private function dispatchCancellationEventIfNeeded(
634
                SignRequestEntity $signRequest,
635
                FileEntity $file,
636
                array $groupedIdentifyMethods,
637
        ): void {
638
                if ($signRequest->getStatus() !== \OCA\Libresign\Enum\SignRequestStatus::ABLE_TO_SIGN->value) {
2✔
639
                        return;
×
640
                }
641

642
                try {
643
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
644
                                foreach ($identifyMethods as $identifyMethod) {
2✔
645
                                        $event = new SignRequestCanceledEvent(
2✔
646
                                                $signRequest,
2✔
647
                                                $file,
2✔
648
                                                $identifyMethod,
2✔
649
                                        );
2✔
650
                                        $this->eventDispatcher->dispatchTyped($event);
2✔
651
                                }
652
                        }
653
                } catch (\Throwable $e) {
×
654
                        $this->logger->error('Error dispatching SignRequestCanceledEvent: ' . $e->getMessage(), ['exception' => $e]);
×
655
                }
656
        }
657

658
        public function deleteRequestSignature(array $data): void {
659
                if (!empty($data['uuid'])) {
2✔
660
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
×
661
                        $fileData = $this->fileMapper->getByUuid($data['uuid']);
×
662
                } elseif (!empty($data['file']['fileId'])) {
2✔
663
                        $fileData = $this->fileMapper->getById($data['file']['fileId']);
2✔
664
                        $signatures = $this->signRequestMapper->getByFileId($fileData->getId());
2✔
665
                } else {
666
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
667
                }
668
                foreach ($signatures as $signRequest) {
2✔
669
                        $this->identifyMethod->deleteBySignRequestId($signRequest->getId());
2✔
670
                        $this->signRequestMapper->delete($signRequest);
2✔
671
                }
672
                $this->fileMapper->delete($fileData);
2✔
673
                $this->fileElementService->deleteVisibleElements($fileData->getId());
2✔
674
        }
675
}
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