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

LibreSign / libresign / 20735558944

06 Jan 2026 02:09AM UTC coverage: 44.781%. First build
20735558944

Pull #6335

github

web-flow
Merge 893de2caf into 7e27d60b2
Pull Request #6335: feat: refactor file list service

160 of 243 new or added lines in 5 files covered. (65.84%)

6692 of 14944 relevant lines covered (44.78%)

5.05 hits per line

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

47.43
/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'],
×
NEW
111
                        'users' => $data['users'] ?? [],
×
NEW
112
                        'status' => $data['status'] ?? FileEntity::STATUS_DRAFT,
×
NEW
113
                        'visibleElements' => $data['visibleElements'] ?? [],
×
NEW
114
                        'signatureFlow' => $data['signatureFlow'] ?? null,
×
115
                ]);
×
116

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

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

133
                return $file;
14✔
134
        }
135

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

141
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
142

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

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

154
                if ($envelope->getStatus() > FileEntity::STATUS_DRAFT) {
×
155
                        $this->fileStatusService->propagateStatusToChildren($envelope->getId(), $envelope->getStatus());
×
156
                }
157
        }
158

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

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

167
                $envelope = null;
×
168
                $files = [];
×
169
                $createdNodes = [];
×
170

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

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

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

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

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

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

206
        private function processFileData(array $fileData, ?IUser $userManager, array $settings): Node {
207
                if (isset($fileData['uploadedFile'])) {
×
208
                        $sourceNode = $this->fileService->getNodeFromData([
×
209
                                'userManager' => $userManager,
×
210
                                'name' => $fileData['name'] ?? '',
×
211
                                'uploadedFile' => $fileData['uploadedFile'],
×
212
                                'settings' => $settings,
×
213
                        ]);
×
214
                } else {
215
                        $sourceNode = $this->fileService->getNodeFromData([
×
216
                                'userManager' => $userManager,
×
217
                                'name' => $fileData['name'] ?? '',
×
218
                                'file' => $fileData,
×
219
                                'settings' => $settings,
×
220
                        ]);
×
221
                }
222

223
                if (isset($settings['envelopeFolderId'])) {
×
224
                        return $this->envelopeFileRelocator->ensureFileInEnvelopeFolder(
×
225
                                $sourceNode,
×
226
                                $settings['envelopeFolderId'],
×
227
                                $userManager,
×
228
                        );
×
229
                }
230

231
                return $sourceNode;
×
232
        }
233

234
        private function rollbackEnvelopeCreation(?FileEntity $envelope, array $files, array $createdNodes): void {
235
                $this->rollbackCreatedNodes($createdNodes);
×
236
                $this->rollbackCreatedFiles($files);
×
237
                $this->rollbackEnvelope($envelope);
×
238
        }
239

240
        private function rollbackCreatedNodes(array $nodes): void {
241
                foreach ($nodes as $node) {
×
242
                        try {
243
                                $node->delete();
×
244
                        } catch (\Throwable $deleteError) {
×
245
                                $this->logger->error('Failed to rollback created node in envelope', [
×
246
                                        'nodeId' => $node->getId(),
×
247
                                        'error' => $deleteError->getMessage(),
×
248
                                ]);
×
249
                        }
250
                }
251
        }
252

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

266
        private function rollbackEnvelope(?FileEntity $envelope): void {
267
                if ($envelope === null) {
×
268
                        return;
×
269
                }
270

271
                try {
272
                        $this->fileMapper->delete($envelope);
×
273
                } catch (\Throwable $deleteError) {
×
274
                        $this->logger->error('Failed to rollback created envelope', [
×
275
                                'envelopeId' => $envelope->getId(),
×
276
                                'error' => $deleteError->getMessage(),
×
277
                        ]);
×
278
                }
279
        }
280

281
        private function createFileForEnvelope(array $fileData, ?IUser $userManager, array $settings): FileEntity {
282
                if (!isset($fileData['node'])) {
×
283
                        throw new \InvalidArgumentException('Node not provided in file data');
×
284
                }
285

286
                $node = $fileData['node'];
×
287
                $fileName = $fileData['name'] ?? $node->getName();
×
288

289
                return $this->saveFile([
×
290
                        'file' => ['fileNode' => $node],
×
291
                        'name' => $fileName,
×
292
                        'userManager' => $userManager,
×
293
                        'status' => FileEntity::STATUS_DRAFT,
×
294
                        'settings' => $settings,
×
295
                ]);
×
296
        }
297

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

328
                $node = $this->fileService->getNodeFromData($data);
15✔
329

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

355
                if (isset($data['parentFileId'])) {
15✔
356
                        $file->setParentFileId($data['parentFileId']);
×
357
                }
358

359
                $this->setSignatureFlow($file, $data);
15✔
360
                $this->setDocMdpLevelFromGlobalConfig($file);
15✔
361

362
                $this->fileMapper->insert($file);
15✔
363
                return $file;
15✔
364
        }
365

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

370
                if ($adminForcedConfig) {
1✔
371
                        $adminFlowEnum = SignatureFlow::from($adminFlow);
×
372
                        if ($file->getSignatureFlowEnum() !== $adminFlowEnum) {
×
373
                                $file->setSignatureFlowEnum($adminFlowEnum);
×
374
                                $this->fileMapper->update($file);
×
375
                        }
376
                        return;
×
377
                }
378

379
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
1✔
380
                        $newFlow = SignatureFlow::from($data['signatureFlow']);
×
381
                        if ($file->getSignatureFlowEnum() !== $newFlow) {
×
382
                                $file->setSignatureFlowEnum($newFlow);
×
383
                                $this->fileMapper->update($file);
×
384
                        }
385
                }
386
        }
387

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

391
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
15✔
392
                        $file->setSignatureFlowEnum(SignatureFlow::from($data['signatureFlow']));
×
393
                } elseif ($adminFlow !== SignatureFlow::NONE->value) {
15✔
394
                        $file->setSignatureFlowEnum(SignatureFlow::from($adminFlow));
×
395
                } else {
396
                        $file->setSignatureFlowEnum(SignatureFlow::NONE);
15✔
397
                }
398
        }
399

400
        private function setDocMdpLevelFromGlobalConfig(FileEntity $file): void {
401
                if ($this->docMdpConfigService->isEnabled()) {
15✔
402
                        $docmdpLevel = $this->docMdpConfigService->getLevel();
×
403
                        $file->setDocmdpLevelEnum($docmdpLevel);
×
404
                }
405
        }
406

407
        private function getFileMetadata(\OCP\Files\Node $node): array {
408
                $metadata = [];
18✔
409
                if ($extension = strtolower($node->getExtension())) {
18✔
410
                        $metadata = [
17✔
411
                                'extension' => $extension,
17✔
412
                        ];
17✔
413
                        if ($metadata['extension'] === 'pdf') {
17✔
414
                                $pdfParser = $this->pdfParserService->setFile($node);
16✔
415
                                $metadata = array_merge(
16✔
416
                                        $metadata,
16✔
417
                                        $pdfParser->getPageDimensions()
16✔
418
                                );
16✔
419
                                $metadata['pdfVersion'] = $pdfParser->getPdfVersion();
16✔
420
                        }
421
                }
422
                return $metadata;
18✔
423
        }
424

425
        private function removeExtensionFromName(string $name, array $metadata): string {
426
                if (!isset($metadata['extension'])) {
15✔
427
                        return $name;
×
428
                }
429
                $extensionPattern = '/\.' . preg_quote($metadata['extension'], '/') . '$/i';
15✔
430
                $result = preg_replace($extensionPattern, '', $name);
15✔
431
                return $result ?? $name;
15✔
432
        }
433

434
        private function deleteIdentifyMethodIfNotExits(array $users, FileEntity $file): void {
435
                $signRequests = $this->signRequestMapper->getByFileId($file->getId());
13✔
436
                foreach ($signRequests as $key => $signRequest) {
13✔
437
                        $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequest->getId());
1✔
438
                        if (empty($identifyMethods)) {
1✔
439
                                $this->unassociateToUser($file->getId(), $signRequest->getId());
×
440
                                continue;
×
441
                        }
442
                        foreach ($identifyMethods as $methodName => $list) {
1✔
443
                                foreach ($list as $method) {
1✔
444
                                        $exists[$key]['identify'][$methodName] = $method->getEntity()->getIdentifierValue();
1✔
445
                                        if (!$this->identifyMethodExists($users, $method)) {
1✔
446
                                                $this->unassociateToUser($file->getId(), $signRequest->getId());
1✔
447
                                                continue 3;
1✔
448
                                        }
449
                                }
450
                        }
451
                }
452
        }
453

454
        private function identifyMethodExists(array $users, IIdentifyMethod $identifyMethod): bool {
455
                foreach ($users as $user) {
1✔
456
                        if (!empty($user['identifyMethods'])) {
1✔
457
                                foreach ($user['identifyMethods'] as $data) {
×
458
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $data['method']) {
×
459
                                                continue;
×
460
                                        }
461
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $data['value']) {
×
462
                                                return true;
×
463
                                        }
464
                                }
465
                        } else {
466
                                foreach ($user['identify'] as $method => $value) {
1✔
467
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $method) {
1✔
468
                                                continue;
×
469
                                        }
470
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $value) {
1✔
471
                                                return true;
×
472
                                        }
473
                                }
474
                        }
475
                }
476
                return false;
1✔
477
        }
478

479
        /**
480
         * @return SignRequestEntity[]
481
         *
482
         * @psalm-return list<SignRequestEntity>
483
         */
484
        private function associateToSigners(array $data, FileEntity $file): array {
485
                $return = [];
14✔
486
                if (!empty($data['users'])) {
14✔
487
                        $this->deleteIdentifyMethodIfNotExits($data['users'], $file);
13✔
488

489
                        $this->sequentialSigningService->resetOrderCounter();
13✔
490
                        $fileStatus = $data['status'] ?? null;
13✔
491

492
                        foreach ($data['users'] as $user) {
13✔
493
                                $userProvidedOrder = isset($user['signingOrder']) ? (int)$user['signingOrder'] : null;
13✔
494
                                $signingOrder = $this->sequentialSigningService->determineSigningOrder($userProvidedOrder);
13✔
495
                                $signerStatus = $user['status'] ?? null;
13✔
496
                                $shouldNotify = !isset($user['notify']) || $user['notify'] !== 0;
13✔
497

498
                                if (isset($user['identifyMethods'])) {
13✔
499
                                        foreach ($user['identifyMethods'] as $identifyMethod) {
×
500
                                                $return[] = $this->signRequestService->createOrUpdateSignRequest(
×
501
                                                        identifyMethods: [
×
502
                                                                $identifyMethod['method'] => $identifyMethod['value'],
×
503
                                                        ],
×
504
                                                        displayName: $user['displayName'] ?? '',
×
505
                                                        description: $user['description'] ?? '',
×
506
                                                        notify: $shouldNotify,
×
507
                                                        fileId: $file->getId(),
×
508
                                                        signingOrder: $signingOrder,
×
509
                                                        fileStatus: $fileStatus,
×
510
                                                        signerStatus: $signerStatus,
×
511
                                                );
×
512
                                        }
513
                                } else {
514
                                        $return[] = $this->signRequestService->createOrUpdateSignRequest(
13✔
515
                                                identifyMethods: $user['identify'],
13✔
516
                                                displayName: $user['displayName'] ?? '',
13✔
517
                                                description: $user['description'] ?? '',
13✔
518
                                                notify: $shouldNotify,
13✔
519
                                                fileId: $file->getId(),
13✔
520
                                                signingOrder: $signingOrder,
13✔
521
                                                fileStatus: $fileStatus,
13✔
522
                                                signerStatus: $signerStatus,
13✔
523
                                        );
13✔
524
                                }
525
                        }
526
                }
527
                return $return;
14✔
528
        }
529

530

531

532
        private function saveVisibleElements(array $data, FileEntity $file): array {
533
                if (empty($data['visibleElements'])) {
17✔
534
                        return [];
15✔
535
                }
536
                $persisted = [];
2✔
537
                foreach ($data['visibleElements'] as $element) {
2✔
538
                        if ($file->isEnvelope() && !empty($element['signRequestId'])) {
2✔
539
                                $envelopeSignRequest = $this->signRequestMapper->getById((int)$element['signRequestId']);
×
540
                                // Only translate if the provided SR belongs to the envelope itself
541
                                if ($envelopeSignRequest && $envelopeSignRequest->getFileId() === $file->getId()) {
×
542
                                        $childrenSrs = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod($file->getId(), (int)$element['signRequestId']);
×
543
                                        foreach ($childrenSrs as $childSr) {
×
544
                                                if ($childSr->getFileId() === (int)$element['fileId']) {
×
545
                                                        $element['signRequestId'] = $childSr->getId();
×
546
                                                        break;
×
547
                                                }
548
                                        }
549
                                }
550
                        }
551

552
                        $persisted[] = $this->fileElementService->saveVisibleElement($element);
2✔
553
                }
554
                return $persisted;
2✔
555
        }
556

557

558
        public function validateNewRequestToFile(array $data): void {
559
                $this->validateNewFile($data);
7✔
560
                $this->validateUsers($data);
6✔
561
                $this->validateHelper->validateFileStatus($data);
2✔
562
        }
563

564
        public function validateNewFile(array $data): void {
565
                if (empty($data['name'])) {
7✔
566
                        throw new \Exception($this->l10n->t('Name is mandatory'));
1✔
567
                }
568
                $this->validateHelper->validateNewFile($data);
6✔
569
        }
570

571
        public function validateUsers(array $data): void {
572
                if (empty($data['users'])) {
6✔
573
                        throw new \Exception($this->l10n->t('Empty users list'));
3✔
574
                }
575
                if (!is_array($data['users'])) {
3✔
576
                        // TRANSLATION This message will be displayed when the request to API with the key users has a value that is not an array
577
                        throw new \Exception($this->l10n->t('User list needs to be an array'));
1✔
578
                }
579
                foreach ($data['users'] as $user) {
2✔
580
                        if (!array_key_exists('identify', $user)) {
2✔
581
                                throw new \Exception('Identify key not found');
×
582
                        }
583
                        $this->identifyMethod->setAllEntityData($user);
2✔
584
                }
585
        }
586

587

588

589
        public function unassociateToUser(int $fileId, int $signRequestId): void {
590
                $file = $this->fileMapper->getById($fileId);
2✔
591
                $signRequest = $this->signRequestMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
592
                $deletedOrder = $signRequest->getSigningOrder();
2✔
593
                $groupedIdentifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
594

595
                $this->dispatchCancellationEventIfNeeded($signRequest, $file, $groupedIdentifyMethods);
2✔
596

597
                try {
598
                        $this->signRequestMapper->delete($signRequest);
2✔
599
                        $this->identifyMethod->deleteBySignRequestId($signRequestId);
2✔
600
                        $visibleElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
601
                        foreach ($visibleElements as $visibleElement) {
2✔
602
                                $this->fileElementMapper->delete($visibleElement);
×
603
                        }
604

605
                        $this->sequentialSigningService
2✔
606
                                ->setFile($file)
2✔
607
                                ->reorderAfterDeletion($file->getId(), $deletedOrder);
2✔
608

609
                        $this->propagateSignerDeletionToChildren($file, $signRequest);
2✔
610
                } catch (\Throwable) {
×
611
                }
612
        }
613

614
        private function propagateSignerDeletionToChildren(FileEntity $envelope, SignRequestEntity $deletedSignRequest): void {
615
                if ($envelope->getNodeType() !== 'envelope') {
2✔
616
                        return;
2✔
617
                }
618

619
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
620

621
                $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($deletedSignRequest->getId());
×
622
                if (empty($identifyMethods)) {
×
623
                        return;
×
624
                }
625

626
                foreach ($children as $child) {
×
627
                        try {
628
                                $this->identifyMethod->clearCache();
×
629
                                $childSignRequest = $this->signRequestService->getSignRequestByIdentifyMethod(
×
630
                                        current(reset($identifyMethods)),
×
631
                                        $child->getId()
×
632
                                );
×
633

634
                                if ($childSignRequest->getId()) {
×
635
                                        $this->unassociateToUser($child->getId(), $childSignRequest->getId());
×
636
                                }
637
                        } catch (\Throwable $e) {
×
638
                                continue;
×
639
                        }
640
                }
641
        }
642

643
        private function dispatchCancellationEventIfNeeded(
644
                SignRequestEntity $signRequest,
645
                FileEntity $file,
646
                array $groupedIdentifyMethods,
647
        ): void {
648
                if ($signRequest->getStatus() !== \OCA\Libresign\Enum\SignRequestStatus::ABLE_TO_SIGN->value) {
2✔
649
                        return;
×
650
                }
651

652
                try {
653
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
654
                                foreach ($identifyMethods as $identifyMethod) {
2✔
655
                                        $event = new SignRequestCanceledEvent(
2✔
656
                                                $signRequest,
2✔
657
                                                $file,
2✔
658
                                                $identifyMethod,
2✔
659
                                        );
2✔
660
                                        $this->eventDispatcher->dispatchTyped($event);
2✔
661
                                }
662
                        }
663
                } catch (\Throwable $e) {
×
664
                        $this->logger->error('Error dispatching SignRequestCanceledEvent: ' . $e->getMessage(), ['exception' => $e]);
×
665
                }
666
        }
667

668
        public function deleteRequestSignature(array $data): void {
669
                if (!empty($data['uuid'])) {
2✔
670
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
×
671
                        $fileData = $this->fileMapper->getByUuid($data['uuid']);
×
672
                } elseif (!empty($data['file']['fileId'])) {
2✔
673
                        $fileData = $this->fileMapper->getById($data['file']['fileId']);
2✔
674
                        $signatures = $this->signRequestMapper->getByFileId($fileData->getId());
2✔
675
                } else {
676
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
677
                }
678
                foreach ($signatures as $signRequest) {
2✔
679
                        $this->identifyMethod->deleteBySignRequestId($signRequest->getId());
2✔
680
                        $this->signRequestMapper->delete($signRequest);
2✔
681
                }
682
                $this->fileMapper->delete($fileData);
2✔
683
                $this->fileElementService->deleteVisibleElements($fileData->getId());
2✔
684
        }
685
}
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