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

LibreSign / libresign / 21498844095

29 Jan 2026 11:44PM UTC coverage: 46.59%. First build
21498844095

Pull #6641

github

web-flow
Merge e7322a308 into f39fc2360
Pull Request #6641: refactor: centralize file status management

66 of 89 new or added lines in 12 files covered. (74.16%)

7897 of 16950 relevant lines covered (46.59%)

5.11 hits per line

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

46.95
/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\FileStatus;
19
use OCA\Libresign\Enum\SignatureFlow;
20
use OCA\Libresign\Events\SignRequestCanceledEvent;
21
use OCA\Libresign\Exception\LibresignException;
22
use OCA\Libresign\Handler\DocMdpHandler;
23
use OCA\Libresign\Helper\FileUploadHelper;
24
use OCA\Libresign\Helper\ValidateHelper;
25
use OCA\Libresign\Service\Envelope\EnvelopeFileRelocator;
26
use OCA\Libresign\Service\Envelope\EnvelopeService;
27
use OCA\Libresign\Service\File\Pdf\PdfMetadataExtractor;
28
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
29
use OCA\Libresign\Service\SignRequest\SignRequestService;
30
use OCP\EventDispatcher\IEventDispatcher;
31
use OCP\Files\IMimeTypeDetector;
32
use OCP\Files\Node;
33
use OCP\Http\Client\IClientService;
34
use OCP\IAppConfig;
35
use OCP\IL10N;
36
use OCP\IUser;
37
use OCP\IUserManager;
38
use Psr\Log\LoggerInterface;
39
use Sabre\DAV\UUIDUtil;
40

41
class RequestSignatureService {
42

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

72
        /**
73
         * Save files - creates single file or envelope based on files count
74
         *
75
         * @return array{file: FileEntity, children: list<FileEntity>}
76
         */
77
        public function saveFiles(array $data): array {
78
                if (empty($data['files'])) {
1✔
79
                        throw new LibresignException('Files parameter is required');
×
80
                }
81

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

85
                        $saveData = [
1✔
86
                                'name' => $data['name'] ?? $fileData['name'] ?? '',
1✔
87
                                'userManager' => $data['userManager'],
1✔
88
                                'status' => FileStatus::DRAFT->value,
1✔
89
                                'settings' => $data['settings'],
1✔
90
                        ];
1✔
91

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

100
                        $savedFile = $this->save($saveData);
1✔
101

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

108
                $result = $this->saveEnvelope([
×
109
                        'files' => $data['files'],
×
110
                        'name' => $data['name'],
×
111
                        'userManager' => $data['userManager'],
×
112
                        'settings' => $data['settings'],
×
113
                        'users' => $data['users'] ?? [],
×
114
                        'status' => $data['status'] ?? FileStatus::DRAFT->value,
×
115
                        'visibleElements' => $data['visibleElements'] ?? [],
×
116
                        'signatureFlow' => $data['signatureFlow'] ?? null,
×
117
                ]);
×
118

119
                return [
×
120
                        'file' => $result['envelope'],
×
121
                        'children' => $result['files'],
×
122
                ];
×
123
        }
124

125
        public function save(array $data): FileEntity {
126
                $file = $this->saveFile($data);
14✔
127
                if (!isset($data['status'])) {
14✔
128
                        $data['status'] = $file->getStatus();
12✔
129
                }
130
                $this->sequentialSigningService->setFile($file);
14✔
131
                $this->associateToSigners($data, $file);
14✔
132
                $this->propagateSignersToChildren($file, $data);
14✔
133
                $this->saveVisibleElements($data, $file);
14✔
134

135
                return $file;
14✔
136
        }
137

138
        private function propagateSignersToChildren(FileEntity $envelope, array $data): void {
139
                if ($envelope->getNodeType() !== 'envelope' || empty($data['users'])) {
14✔
140
                        return;
14✔
141
                }
142

143
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
144

145
                $dataWithoutNotification = $data;
×
146
                foreach ($dataWithoutNotification['users'] as &$user) {
×
147
                        $user['notify'] = 0;
×
148
                }
149

150
                foreach ($children as $child) {
×
151
                        $this->identifyMethod->clearCache();
×
152
                        $this->sequentialSigningService->setFile($child);
×
153
                        $this->associateToSigners($dataWithoutNotification, $child);
×
154
                }
155

156
                if ($envelope->getStatus() > FileStatus::DRAFT->value) {
×
157
                        $this->fileStatusService->propagateStatusToChildren($envelope->getId(), $envelope->getStatus());
×
158
                }
159
        }
160

161
        public function saveEnvelope(array $data): array {
162
                $this->envelopeService->validateEnvelopeConstraints(count($data['files']));
×
163

164
                $envelopeName = $data['name'] ?: $this->l10n->t('Envelope %s', [date('Y-m-d H:i:s')]);
×
165
                $userManager = $data['userManager'] ?? null;
×
166
                $userId = $userManager instanceof IUser ? $userManager->getUID() : null;
×
167
                $filesCount = count($data['files']);
×
168

169
                $envelope = null;
×
170
                $files = [];
×
171
                $createdNodes = [];
×
172

173
                try {
174
                        $envelopePath = $data['settings']['path'] ?? null;
×
175
                        $envelope = $this->envelopeService->createEnvelope($envelopeName, $userId, $filesCount, $envelopePath);
×
176

177
                        $envelopeFolder = $this->envelopeService->getEnvelopeFolder($envelope);
×
178
                        $envelopeSettings = array_merge($data['settings'] ?? [], [
×
179
                                'envelopeFolderId' => $envelopeFolder->getId(),
×
180
                        ]);
×
181

182
                        foreach ($data['files'] as $fileData) {
×
183
                                $node = $this->processFileData($fileData, $userManager, $envelopeSettings);
×
184
                                $createdNodes[] = $node;
×
185

186
                                $fileData['node'] = $node;
×
187
                                $fileEntity = $this->createFileForEnvelope($fileData, $userManager, $envelopeSettings);
×
188
                                $this->envelopeService->addFileToEnvelope($envelope->getId(), $fileEntity);
×
189
                                $files[] = $fileEntity;
×
190
                        }
191

192
                        if (!empty($data['users'])) {
×
193
                                $this->sequentialSigningService->setFile($envelope);
×
194
                                $this->associateToSigners($data, $envelope);
×
195
                                $this->propagateSignersToChildren($envelope, $data);
×
196
                        }
197

198
                        return [
×
199
                                'envelope' => $envelope,
×
200
                                'files' => $files,
×
201
                        ];
×
202
                } catch (\Throwable $e) {
×
203
                        $this->rollbackEnvelopeCreation($envelope, $files, $createdNodes);
×
204
                        throw $e;
×
205
                }
206
        }
207

208
        private function processFileData(array $fileData, ?IUser $userManager, array $settings): Node {
209
                $name = $this->requireFileName($fileData);
×
210

211
                if (isset($fileData['uploadedFile'])) {
×
212
                        $sourceNode = $this->fileService->getNodeFromData([
×
213
                                'userManager' => $userManager,
×
214
                                'name' => $name,
×
215
                                'uploadedFile' => $fileData['uploadedFile'],
×
216
                                'settings' => $settings,
×
217
                        ]);
×
218
                } else {
219
                        $sourceNode = $this->fileService->getNodeFromData([
×
220
                                'userManager' => $userManager,
×
221
                                'name' => $name,
×
222
                                'file' => $fileData,
×
223
                                'settings' => $settings,
×
224
                        ]);
×
225
                }
226

227
                if (isset($settings['envelopeFolderId'])) {
×
228
                        return $this->envelopeFileRelocator->ensureFileInEnvelopeFolder(
×
229
                                $sourceNode,
×
230
                                $settings['envelopeFolderId'],
×
231
                                $userManager,
×
232
                        );
×
233
                }
234

235
                return $sourceNode;
×
236
        }
237

238
        private function requireFileName(array $fileData): string {
239
                $name = trim((string)($fileData['name'] ?? ''));
×
240
                if ($name === '') {
×
241
                        throw new LibresignException($this->l10n->t('File name is required'));
×
242
                }
243
                return $name;
×
244
        }
245

246
        private function rollbackEnvelopeCreation(?FileEntity $envelope, array $files, array $createdNodes): void {
247
                $this->rollbackCreatedNodes($createdNodes);
×
248
                $this->rollbackCreatedFiles($files);
×
249
                $this->rollbackEnvelope($envelope);
×
250
        }
251

252
        private function rollbackCreatedNodes(array $nodes): void {
253
                foreach ($nodes as $node) {
×
254
                        try {
255
                                $node->delete();
×
256
                        } catch (\Throwable $deleteError) {
×
257
                                $this->logger->error('Failed to rollback created node in envelope', [
×
258
                                        'nodeId' => $node->getId(),
×
259
                                        'error' => $deleteError->getMessage(),
×
260
                                ]);
×
261
                        }
262
                }
263
        }
264

265
        private function rollbackCreatedFiles(array $files): void {
266
                foreach ($files as $file) {
×
267
                        try {
268
                                $this->fileMapper->delete($file);
×
269
                        } catch (\Throwable $deleteError) {
×
270
                                $this->logger->error('Failed to rollback created file entity in envelope', [
×
271
                                        'fileId' => $file->getId(),
×
272
                                        'error' => $deleteError->getMessage(),
×
273
                                ]);
×
274
                        }
275
                }
276
        }
277

278
        private function rollbackEnvelope(?FileEntity $envelope): void {
279
                if ($envelope === null) {
×
280
                        return;
×
281
                }
282

283
                try {
284
                        $this->fileMapper->delete($envelope);
×
285
                } catch (\Throwable $deleteError) {
×
286
                        $this->logger->error('Failed to rollback created envelope', [
×
287
                                'envelopeId' => $envelope->getId(),
×
288
                                'error' => $deleteError->getMessage(),
×
289
                        ]);
×
290
                }
291
        }
292

293
        private function createFileForEnvelope(array $fileData, ?IUser $userManager, array $settings): FileEntity {
294
                if (!isset($fileData['node'])) {
×
295
                        throw new \InvalidArgumentException('Node not provided in file data');
×
296
                }
297

298
                $node = $fileData['node'];
×
299
                $fileName = $fileData['name'] ?? $node->getName();
×
300

301
                return $this->saveFile([
×
302
                        'file' => ['fileNode' => $node],
×
303
                        'name' => $fileName,
×
304
                        'userManager' => $userManager,
×
305
                        'status' => FileStatus::DRAFT->value,
×
306
                        'settings' => $settings,
×
307
                ]);
×
308
        }
309

310
        /**
311
         * Save file data
312
         *
313
         * @param array{?userManager: IUser, ?signRequest: SignRequest, name: string, callback: string, uuid?: ?string, status: int, file?: array{fileId?: int, fileNode?: Node}} $data
314
         */
315
        public function saveFile(array $data): FileEntity {
316
                if (!empty($data['uuid'])) {
15✔
317
                        $file = $this->fileMapper->getByUuid($data['uuid']);
1✔
318
                        $this->updateSignatureFlowIfAllowed($file, $data);
1✔
319
                        if (!empty($data['name'])) {
1✔
320
                                $file->setName($data['name']);
×
NEW
321
                                $this->fileService->update($file);
×
322
                        }
323
                        return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
1✔
324
                }
325
                $fileId = null;
15✔
326
                if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
15✔
327
                        $fileId = $data['file']['fileNode']->getId();
×
328
                } elseif (!empty($data['file']['fileId'])) {
15✔
329
                        $fileId = $data['file']['fileId'];
×
330
                }
331
                if (!is_null($fileId)) {
15✔
332
                        try {
333
                                $file = $this->fileMapper->getByNodeId($fileId);
×
334
                                $this->updateSignatureFlowIfAllowed($file, $data);
×
335
                                return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
×
336
                        } catch (\Throwable) {
×
337
                        }
338
                }
339

340
                $node = $this->fileService->getNodeFromData($data);
15✔
341

342
                $file = new FileEntity();
15✔
343
                $file->setNodeId($node->getId());
15✔
344
                if ($data['userManager'] instanceof IUser) {
15✔
345
                        $file->setUserId($data['userManager']->getUID());
15✔
346
                } elseif ($data['signRequest'] instanceof SignRequestEntity) {
×
347
                        $file->setSignRequestId($data['signRequest']->getId());
×
348
                }
349
                $file->setUuid(UUIDUtil::getUUID());
15✔
350
                $file->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
15✔
351
                $metadata = $this->getFileMetadata($node);
15✔
352
                $name = trim((string)($data['name'] ?? ''));
15✔
353
                if ($name === '') {
15✔
354
                        $name = $node->getName();
×
355
                }
356
                $file->setName($this->removeExtensionFromName($name, $metadata));
15✔
357
                $file->setMetadata($metadata);
15✔
358
                if (!empty($data['callback'])) {
15✔
359
                        $file->setCallback($data['callback']);
×
360
                }
361
                if (isset($data['status'])) {
15✔
362
                        $file->setStatus($data['status']);
2✔
363
                } else {
364
                        $file->setStatus(FileStatus::ABLE_TO_SIGN->value);
13✔
365
                }
366

367
                if (isset($data['parentFileId'])) {
15✔
368
                        $file->setParentFileId($data['parentFileId']);
×
369
                }
370

371
                $this->setSignatureFlow($file, $data);
15✔
372
                $this->setDocMdpLevelFromGlobalConfig($file);
15✔
373

374
                $this->fileMapper->insert($file);
15✔
375
                return $file;
15✔
376
        }
377

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

382
                if ($adminForcedConfig) {
1✔
383
                        $adminFlowEnum = SignatureFlow::from($adminFlow);
×
384
                        if ($file->getSignatureFlowEnum() !== $adminFlowEnum) {
×
385
                                $file->setSignatureFlowEnum($adminFlowEnum);
×
NEW
386
                                $this->fileService->update($file);
×
387
                        }
388
                        return;
×
389
                }
390

391
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
1✔
392
                        $newFlow = SignatureFlow::from($data['signatureFlow']);
×
393
                        if ($file->getSignatureFlowEnum() !== $newFlow) {
×
394
                                $file->setSignatureFlowEnum($newFlow);
×
NEW
395
                                $this->fileService->update($file);
×
396
                        }
397
                }
398
        }
399

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

403
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
15✔
404
                        $file->setSignatureFlowEnum(SignatureFlow::from($data['signatureFlow']));
×
405
                } elseif ($adminFlow !== SignatureFlow::NONE->value) {
15✔
406
                        $file->setSignatureFlowEnum(SignatureFlow::from($adminFlow));
×
407
                } else {
408
                        $file->setSignatureFlowEnum(SignatureFlow::NONE);
15✔
409
                }
410
        }
411

412
        private function setDocMdpLevelFromGlobalConfig(FileEntity $file): void {
413
                if ($this->docMdpConfigService->isEnabled()) {
15✔
414
                        $docmdpLevel = $this->docMdpConfigService->getLevel();
×
415
                        $file->setDocmdpLevelEnum($docmdpLevel);
×
416
                }
417
        }
418

419
        private function getFileMetadata(\OCP\Files\Node $node): array {
420
                $metadata = [];
18✔
421
                if ($extension = strtolower($node->getExtension())) {
18✔
422
                        $metadata = [
17✔
423
                                'extension' => $extension,
17✔
424
                        ];
17✔
425
                        if ($metadata['extension'] === 'pdf') {
17✔
426
                                $this->pdfMetadataExtractor->setFile($node);
16✔
427
                                $metadata = array_merge(
16✔
428
                                        $metadata,
16✔
429
                                        $this->pdfMetadataExtractor->getPageDimensions()
16✔
430
                                );
16✔
431
                                $metadata['pdfVersion'] = $this->pdfMetadataExtractor->getPdfVersion();
16✔
432
                        }
433
                }
434
                return $metadata;
18✔
435
        }
436

437
        private function removeExtensionFromName(string $name, array $metadata): string {
438
                if (!isset($metadata['extension'])) {
15✔
439
                        return $name;
×
440
                }
441
                $extensionPattern = '/\.' . preg_quote($metadata['extension'], '/') . '$/i';
15✔
442
                $result = preg_replace($extensionPattern, '', $name);
15✔
443
                return $result ?? $name;
15✔
444
        }
445

446
        private function deleteIdentifyMethodIfNotExits(array $users, FileEntity $file): void {
447
                $signRequests = $this->signRequestMapper->getByFileId($file->getId());
13✔
448
                foreach ($signRequests as $key => $signRequest) {
13✔
449
                        $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequest->getId());
1✔
450
                        if (empty($identifyMethods)) {
1✔
451
                                $this->unassociateToUser($file->getId(), $signRequest->getId());
×
452
                                continue;
×
453
                        }
454
                        foreach ($identifyMethods as $methodName => $list) {
1✔
455
                                foreach ($list as $method) {
1✔
456
                                        $exists[$key]['identify'][$methodName] = $method->getEntity()->getIdentifierValue();
1✔
457
                                        if (!$this->identifyMethodExists($users, $method)) {
1✔
458
                                                $this->unassociateToUser($file->getId(), $signRequest->getId());
1✔
459
                                                continue 3;
1✔
460
                                        }
461
                                }
462
                        }
463
                }
464
        }
465

466
        private function identifyMethodExists(array $users, IIdentifyMethod $identifyMethod): bool {
467
                foreach ($users as $user) {
1✔
468
                        if (!empty($user['identifyMethods'])) {
1✔
469
                                foreach ($user['identifyMethods'] as $data) {
×
470
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $data['method']) {
×
471
                                                continue;
×
472
                                        }
473
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $data['value']) {
×
474
                                                return true;
×
475
                                        }
476
                                }
477
                        } else {
478
                                foreach ($user['identify'] as $method => $value) {
1✔
479
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $method) {
1✔
480
                                                continue;
×
481
                                        }
482
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $value) {
1✔
483
                                                return true;
×
484
                                        }
485
                                }
486
                        }
487
                }
488
                return false;
1✔
489
        }
490

491
        /**
492
         * @return SignRequestEntity[]
493
         *
494
         * @psalm-return list<SignRequestEntity>
495
         */
496
        private function associateToSigners(array $data, FileEntity $file): array {
497
                $return = [];
14✔
498
                if (!empty($data['users'])) {
14✔
499
                        $this->deleteIdentifyMethodIfNotExits($data['users'], $file);
13✔
500
                        $this->identifyMethod->clearCache();
13✔
501

502
                        $this->sequentialSigningService->resetOrderCounter();
13✔
503
                        $fileStatus = $data['status'] ?? null;
13✔
504

505
                        foreach ($data['users'] as $user) {
13✔
506
                                $userProvidedOrder = isset($user['signingOrder']) ? (int)$user['signingOrder'] : null;
13✔
507
                                $signingOrder = $this->sequentialSigningService->determineSigningOrder($userProvidedOrder);
13✔
508
                                $signerStatus = $user['status'] ?? null;
13✔
509
                                $shouldNotify = !isset($user['notify']) || $user['notify'] !== 0;
13✔
510

511
                                if (isset($user['identifyMethods'])) {
13✔
512
                                        foreach ($user['identifyMethods'] as $identifyMethod) {
×
513
                                                $return[] = $this->signRequestService->createOrUpdateSignRequest(
×
514
                                                        identifyMethods: [
×
515
                                                                $identifyMethod['method'] => $identifyMethod['value'],
×
516
                                                        ],
×
517
                                                        displayName: $user['displayName'] ?? '',
×
518
                                                        description: $user['description'] ?? '',
×
519
                                                        notify: $shouldNotify,
×
520
                                                        fileId: $file->getId(),
×
521
                                                        signingOrder: $signingOrder,
×
522
                                                        fileStatus: $fileStatus,
×
523
                                                        signerStatus: $signerStatus,
×
524
                                                );
×
525
                                        }
526
                                } else {
527
                                        $return[] = $this->signRequestService->createOrUpdateSignRequest(
13✔
528
                                                identifyMethods: $user['identify'],
13✔
529
                                                displayName: $user['displayName'] ?? '',
13✔
530
                                                description: $user['description'] ?? '',
13✔
531
                                                notify: $shouldNotify,
13✔
532
                                                fileId: $file->getId(),
13✔
533
                                                signingOrder: $signingOrder,
13✔
534
                                                fileStatus: $fileStatus,
13✔
535
                                                signerStatus: $signerStatus,
13✔
536
                                        );
13✔
537
                                }
538
                        }
539
                }
540
                return $return;
14✔
541
        }
542

543

544

545
        private function saveVisibleElements(array $data, FileEntity $file): array {
546
                if (empty($data['visibleElements'])) {
17✔
547
                        return [];
15✔
548
                }
549
                $persisted = [];
2✔
550
                foreach ($data['visibleElements'] as $element) {
2✔
551
                        if ($file->isEnvelope() && !empty($element['signRequestId'])) {
2✔
552
                                $envelopeSignRequest = $this->signRequestMapper->getById((int)$element['signRequestId']);
×
553
                                // Only translate if the provided SR belongs to the envelope itself
554
                                if ($envelopeSignRequest && $envelopeSignRequest->getFileId() === $file->getId()) {
×
555
                                        $childrenSrs = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod($file->getId(), (int)$element['signRequestId']);
×
556
                                        foreach ($childrenSrs as $childSr) {
×
557
                                                if ($childSr->getFileId() === (int)$element['fileId']) {
×
558
                                                        $element['signRequestId'] = $childSr->getId();
×
559
                                                        break;
×
560
                                                }
561
                                        }
562
                                }
563
                        }
564

565
                        $persisted[] = $this->fileElementService->saveVisibleElement($element);
2✔
566
                }
567
                return $persisted;
2✔
568
        }
569

570

571
        public function validateNewRequestToFile(array $data): void {
572
                $this->validateNewFile($data);
7✔
573
                $this->validateUsers($data);
6✔
574
                $this->validateHelper->validateFileStatus($data);
2✔
575
        }
576

577
        public function validateNewFile(array $data): void {
578
                if (empty($data['name'])) {
7✔
579
                        throw new \Exception($this->l10n->t('File name is required'));
1✔
580
                }
581
                $this->validateHelper->validateNewFile($data);
6✔
582
        }
583

584
        public function validateUsers(array $data): void {
585
                if (empty($data['users'])) {
6✔
586
                        if (($data['status'] ?? FileStatus::ABLE_TO_SIGN->value) === FileStatus::DRAFT->value) {
3✔
587
                                return;
×
588
                        }
589
                        throw new \Exception($this->l10n->t('Empty users list'));
3✔
590
                }
591
                if (!is_array($data['users'])) {
3✔
592
                        // TRANSLATION This message will be displayed when the request to API with the key users has a value that is not an array
593
                        throw new \Exception($this->l10n->t('User list needs to be an array'));
1✔
594
                }
595
                foreach ($data['users'] as $user) {
2✔
596
                        if (!array_key_exists('identify', $user)) {
2✔
597
                                throw new \Exception('Identify key not found');
×
598
                        }
599
                        $this->identifyMethod->setAllEntityData($user);
2✔
600
                }
601
        }
602

603

604

605
        public function unassociateToUser(int $fileId, int $signRequestId): void {
606
                $file = $this->fileMapper->getById($fileId);
2✔
607
                $signRequest = $this->signRequestMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
608
                $deletedOrder = $signRequest->getSigningOrder();
2✔
609
                $groupedIdentifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
610

611
                $this->dispatchCancellationEventIfNeeded($signRequest, $file, $groupedIdentifyMethods);
2✔
612

613
                try {
614
                        $this->signRequestMapper->delete($signRequest);
2✔
615
                        $this->identifyMethod->deleteBySignRequestId($signRequestId);
2✔
616
                        $visibleElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
617
                        foreach ($visibleElements as $visibleElement) {
2✔
618
                                $this->fileElementMapper->delete($visibleElement);
×
619
                        }
620

621
                        $this->sequentialSigningService
2✔
622
                                ->setFile($file)
2✔
623
                                ->reorderAfterDeletion($file->getId(), $deletedOrder);
2✔
624

625
                        $this->propagateSignerDeletionToChildren($file, $signRequest);
2✔
626
                } catch (\Throwable) {
×
627
                }
628
        }
629

630
        private function propagateSignerDeletionToChildren(FileEntity $envelope, SignRequestEntity $deletedSignRequest): void {
631
                if ($envelope->getNodeType() !== 'envelope') {
2✔
632
                        return;
2✔
633
                }
634

635
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
636

637
                $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($deletedSignRequest->getId());
×
638
                if (empty($identifyMethods)) {
×
639
                        return;
×
640
                }
641

642
                foreach ($children as $child) {
×
643
                        try {
644
                                $this->identifyMethod->clearCache();
×
645
                                $childSignRequest = $this->signRequestService->getSignRequestByIdentifyMethod(
×
646
                                        current(reset($identifyMethods)),
×
647
                                        $child->getId()
×
648
                                );
×
649

650
                                if ($childSignRequest->getId()) {
×
651
                                        $this->unassociateToUser($child->getId(), $childSignRequest->getId());
×
652
                                }
653
                        } catch (\Throwable $e) {
×
654
                                continue;
×
655
                        }
656
                }
657
        }
658

659
        private function dispatchCancellationEventIfNeeded(
660
                SignRequestEntity $signRequest,
661
                FileEntity $file,
662
                array $groupedIdentifyMethods,
663
        ): void {
664
                if ($signRequest->getStatus() !== \OCA\Libresign\Enum\SignRequestStatus::ABLE_TO_SIGN->value) {
2✔
665
                        return;
×
666
                }
667

668
                try {
669
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
670
                                foreach ($identifyMethods as $identifyMethod) {
2✔
671
                                        $event = new SignRequestCanceledEvent(
2✔
672
                                                $signRequest,
2✔
673
                                                $file,
2✔
674
                                                $identifyMethod,
2✔
675
                                        );
2✔
676
                                        $this->eventDispatcher->dispatchTyped($event);
2✔
677
                                }
678
                        }
679
                } catch (\Throwable $e) {
×
680
                        $this->logger->error('Error dispatching SignRequestCanceledEvent: ' . $e->getMessage(), ['exception' => $e]);
×
681
                }
682
        }
683

684
        public function deleteRequestSignature(array $data): void {
685
                if (!empty($data['uuid'])) {
1✔
686
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
×
687
                        $fileData = $this->fileMapper->getByUuid($data['uuid']);
×
688
                } elseif (!empty($data['file']['fileId'])) {
1✔
689
                        $fileData = $this->fileMapper->getById($data['file']['fileId']);
1✔
690
                        $signatures = $this->signRequestMapper->getByFileId($fileData->getId());
1✔
691
                } else {
692
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
693
                }
694
                foreach ($signatures as $signRequest) {
1✔
695
                        $this->identifyMethod->deleteBySignRequestId($signRequest->getId());
1✔
696
                        $this->signRequestMapper->delete($signRequest);
1✔
697
                }
698
                $this->fileMapper->delete($fileData);
1✔
699
                $this->fileElementService->deleteVisibleElements($fileData->getId());
1✔
700
        }
701
}
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