FastParapheurController.php 20.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

/**
 * Copyright Maarch since 2008 under licence GPLv3.
 * See LICENCE.txt file at the root folder for more details.
 * This file is part of Maarch software.
 *
 */

/**
 * @brief fastParapheur Controller
 * @author nathan.cheval@edissyum.com
 * @author dev@maarch.org
 */

namespace ExternalSignatoryBook\controllers;

use Attachment\models\AttachmentModel;
19
use Attachment\models\AttachmentTypeModel;
20
use Convert\controllers\ConvertPdfController;
21
use Docserver\models\DocserverModel;
22
use Docserver\models\DocserverTypeModel;
23
use Entity\models\ListInstanceModel;
24
use Resource\controllers\StoreController;
25
26
27
28
use Resource\models\ResModel;
use SrcCore\models\CoreConfigModel;
use SrcCore\models\CurlModel;
use SrcCore\models\DatabaseModel;
29
use User\models\UserModel;
30

31
32
33
/**
    * @codeCoverageIgnore
*/
34
35
36
37
class FastParapheurController
{
    public static function retrieveSignedMails($aArgs)
    {
38
39
        $version = $aArgs['version'];
        foreach ($aArgs['idsToRetrieve'][$version] as $resId => $value) {
40
41
42
43
            if (empty(trim($value['external_id']))) {
                $aArgs['idsToRetrieve'][$version][$resId]['status'] = 'waiting';
                continue;
            }
44
45
46
47
48
49
50
51
52
            $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sei="http://sei.ws.fast.cdc.com/">
                <soapenv:Header/>
                    <soapenv:Body>
                        <sei:history>
                            <documentId>' .  $value['external_id'] . '</documentId>
                        </sei:history>
                    </soapenv:Body>
            </soapenv:Envelope>';
53

54
55
56
57
58
59
60
61
62
            $curlReturn = CurlModel::execSOAP([
                'xmlPostString' => $xmlPostString,
                'url'           => $aArgs['config']['data']['url'],
                'options'       => [
                    CURLOPT_SSLCERT         => $aArgs['config']['data']['certPath'],
                    CURLOPT_SSLCERTPASSWD   => $aArgs['config']['data']['certPass'],
                    CURLOPT_SSLCERTTYPE     => $aArgs['config']['data']['certType']
                ]
            ]);
63

64
65
66
            if ($curlReturn['infos']['http_code'] == 404) {
                return ['error' => 'Erreur 404 : ' . $curlReturn['raw']];
            }
67

68
69
70
71
72
73
74
75
            $isError = $curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body;
            if (!empty($isError ->Fault[0]) && !empty($value['res_id_master'])) {
                echo 'PJ n° ' . $resId . ' et document original n° ' . $value['res_id_master'] . ' : ' . (string)$curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0]->children()->faultstring . PHP_EOL;
                continue;
            } elseif (!empty($isError->Fault[0])) {
                echo 'Document principal n° ' . $resId . ' : ' . (string)$curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0]->children()->faultstring . PHP_EOL;
                continue;
            }
76

77
78
79
80
81
82
83
84
85
            $response = $curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://sei.ws.fast.cdc.com/')->historyResponse->children();

            foreach ($response->return as $res) {    // Loop on all steps of the documents (prepared, send to signature, signed etc...)
                $state      = (string) $res->stateName;
                if ($state == $aArgs['config']['data']['validatedState']) {
                    $response = FastParapheurController::download(['config' => $aArgs['config'], 'documentId' => $value['external_id']]);
                    $aArgs['idsToRetrieve'][$version][$resId]['status'] = 'validated';
                    $aArgs['idsToRetrieve'][$version][$resId]['format'] = 'pdf';
                    $aArgs['idsToRetrieve'][$version][$resId]['encodedFile'] = $response['b64FileContent'];
86
87
                    $signatoryInfo = FastParapheurController::getSignatoryUserInfo(['resId' => $aArgs['idsToRetrieve'][$version][$resId]['res_id_master']]);
                    $aArgs['idsToRetrieve'][$version][$resId]['signatory_user_serial_id'] = $signatoryInfo['id'];
88
                    FastParapheurController::processVisaWorkflow(['res_id_master' => $value['res_id_master'], 'res_id' => $value['res_id'], 'processSignatory' => true]);
89
90
                    break;
                } elseif ($state == $aArgs['config']['data']['refusedState']) {
91
                    $signatoryInfo = FastParapheurController::getSignatoryUserInfo(['resId' => $aArgs['idsToRetrieve'][$version][$resId]['res_id_master']]);
92
93
                    $response = FastParapheurController::getRefusalMessage(['config' => $aArgs['config'], 'documentId' => $value['external_id']]);
                    $aArgs['idsToRetrieve'][$version][$resId]['status'] = 'refused';
94
                    $aArgs['idsToRetrieve'][$version][$resId]['notes'][] = ['content' => $signatoryInfo['lastname'] . ' ' . $signatoryInfo['firstname'] . ' : ' . $response];
95
96
97
98
99
100
101
102
103
104
                    break;
                } else {
                    $aArgs['idsToRetrieve'][$version][$resId]['status'] = 'waiting';
                }
            }
        }
        
        return $aArgs['idsToRetrieve'];
    }

105
106
107
108
109
110
111
112
113
114
115
116
117
    public static function getSignatoryUserInfo($args = [])
    {
        $res = DatabaseModel::select([
            'select'    => ['firstname', 'lastname', 'users.id'],
            'table'     => ['listinstance', 'users'],
            'left_join' => ['listinstance.item_id = users.id'],
            'where'     => ['res_id = ?', 'process_date is null', 'difflist_type = ?'],
            'data'      => [$args['resId'], 'VISA_CIRCUIT']
        ])[0];

        return $res;
    }

118
119
120
121
122
    public static function processVisaWorkflow($aArgs = [])
    {
        $resIdMaster = $aArgs['res_id_master'] ?? $aArgs['res_id'];

        $attachments = AttachmentModel::get(['select' => ['count(1)'], 'where' => ['res_id_master = ?', 'status = ?'], 'data' => [$resIdMaster, 'FRZ']]);
123
        if ((count($attachments) < 2 && $aArgs['processSignatory']) || !$aArgs['processSignatory']) {
124
125
126
127
128
129
130
131
132
133
            $visaWorkflow = ListInstanceModel::get([
                'select'  => ['listinstance_id', 'requested_signature'],
                'where'   => ['res_id = ?', 'difflist_type = ?', 'process_date IS NULL'],
                'data'    => [$resIdMaster, 'VISA_CIRCUIT'],
                'orderBY' => ['ORDER BY listinstance_id ASC']
            ]);
    
            if (!empty($visaWorkflow)) {
                foreach ($visaWorkflow as $listInstance) {
                    if ($listInstance['requested_signature']) {
134
135
136
137
                        // Stop to the first signatory user
                        if ($aArgs['processSignatory']) {
                            ListInstanceModel::update(['set' => ['signatory' => 'true', 'process_date' => 'CURRENT_TIMESTAMP'], 'where' => ['listinstance_id = ?'], 'data' => [$listInstance['listinstance_id']]]);
                        }
138
139
                        break;
                    }
140
                    ListInstanceModel::update(['set' => ['process_date' => 'CURRENT_TIMESTAMP'], 'where' => ['listinstance_id = ?'], 'data' => [$listInstance['listinstance_id']]]);
141
142
143
144
145
146
147
148
149
150
151
152
153
154
                }
            }
        }
    }

    public static function upload($aArgs)
    {
        $circuitId    = $aArgs['circuitId'];
        $label        = $aArgs['label'];
        $subscriberId = $aArgs['businessId'];

        // Retrieve the annexes of the attachemnt to sign (other attachment and the original document)
        $annexes = [];
        $annexes['letterbox'] = ResModel::get([
155
            'select' => ['res_id', 'path', 'filename', 'docserver_id', 'format', 'category_id', 'external_id', 'integrations'],
156
157
158
159
            'where'  => ['res_id = ?'],
            'data'   => [$aArgs['resIdMaster']]
        ]);

160
        if (!empty($annexes['letterbox'][0]['docserver_id'])) {
161
162
163
            $adrMainInfo = ConvertPdfController::getConvertedPdfById(['resId' => $aArgs['resIdMaster'], 'collId' => 'letterbox_coll']);
            $letterboxPath = DocserverModel::getByDocserverId(['docserverId' => $adrMainInfo['docserver_id'], 'select' => ['path_template']]);
            $annexes['letterbox'][0]['filePath'] = $letterboxPath['path_template'] . str_replace('#', '/', $adrMainInfo['path']) . $adrMainInfo['filename'];
164
        }
165
166
167

        $attachments = AttachmentModel::get([
            'select'    => [
168
                'res_id', 'docserver_id', 'path', 'filename', 'format', 'attachment_type', 'fingerprint'
169
170
            ],
            'where'     => ["res_id_master = ?", "attachment_type not in (?)", "status not in ('DEL', 'OBS', 'FRZ', 'TMP', 'SEND_MASS')", "in_signature_book = 'true'"],
171
            'data'      => [$aArgs['resIdMaster'], ['signed_response']]
172
173
        ]);

174
175
        $attachmentTypes = AttachmentTypeModel::get(['select' => ['type_id', 'signable']]);
        $attachmentTypes = array_column($attachmentTypes, 'signable', 'type_id');
176
        foreach ($attachments as $key => $value) {
177
            if (!$attachmentTypes[$value['attachment_type']]) {
178
                $annexeAttachmentPath = DocserverModel::getByDocserverId(['docserverId' => $value['docserver_id'], 'select' => ['path_template', 'docserver_type_id']]);
179
                $value['filePath']    = $annexeAttachmentPath['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $value['path']) . $value['filename'];
180
181
182
183
184
185
186

                $docserverType = DocserverTypeModel::getById(['id' => $annexeAttachmentPath['docserver_type_id'], 'select' => ['fingerprint_mode']]);
                $fingerprint = StoreController::getFingerPrint(['filePath' => $value['filePath'], 'mode' => $docserverType['fingerprint_mode']]);
                if ($value['fingerprint'] != $fingerprint) {
                    return ['error' => 'Fingerprints do not match'];
                }

187
188
189
190
191
192
193
194
195
196
197
                unset($attachments[$key]);
                $annexes['attachments'][] = $value;
            }
        }
        // END annexes

        $attachmentToFreeze = [];
        foreach ($attachments as $attachment) {
            $resId  = $attachment['res_id'];
            $collId = 'attachments_coll';
            
198
            $response = FastParapheurController::uploadFile([
199
200
201
202
203
204
205
206
207
208
                'resId'        => $resId,
                'collId'       => $collId,
                'resIdMaster'  => $aArgs['resIdMaster'],
                'annexes'      => $annexes,
                'circuitId'    => $circuitId,
                'label'        => $label,
                'subscriberId' => $subscriberId,
                'config'       => $aArgs['config']
            ]);

209
210
            if (!empty($response['error'])) {
                return $response;
211
            } else {
212
                $attachmentToFreeze[$collId][$resId] = $response['success'];
213
214
215
216
            }
        }

        // Send main document if in signature book
217
218
219
220
221
222
223
224
        if (!empty($annexes['letterbox'][0])) {
            $mainDocumentIntegration = json_decode($annexes['letterbox'][0]['integrations'], true);
            $externalId              = json_decode($annexes['letterbox'][0]['external_id'], true);
            if ($mainDocumentIntegration['inSignatureBook'] && empty($externalId['signatureBookId'])) {
                $resId  = $annexes['letterbox'][0]['res_id'];
                $collId = 'letterbox_coll';
                unset($annexes['letterbox']);
    
225
                $response = FastParapheurController::uploadFile([
226
227
228
229
230
231
232
233
234
                    'resId'        => $resId,
                    'collId'       => $collId,
                    'resIdMaster'  => $aArgs['resIdMaster'],
                    'annexes'      => $annexes,
                    'circuitId'    => $circuitId,
                    'label'        => $label,
                    'subscriberId' => $subscriberId,
                    'config'       => $aArgs['config']
                ]);
235
236
237

                if (!empty($response['error'])) {
                    return $response;
238
                } else {
239
                    $attachmentToFreeze[$collId][$resId] = $response['success'];
240
                }
241
242
243
244
245
246
247
248
            }
        }

        return ['sended' => $attachmentToFreeze];
    }

    public static function uploadFile($aArgs)
    {
249
250
251
252
        $adrInfo = ConvertPdfController::getConvertedPdfById(['resId' => $aArgs['resId'], 'collId' => $aArgs['collId']]);
        if (empty($adrInfo['docserver_id']) || strtolower(pathinfo($adrInfo['filename'], PATHINFO_EXTENSION)) != 'pdf') {
            return ['error' => 'Document ' . $aArgs['resIdMaster'] . ' is not converted in pdf'];
        }
253
        $attachmentPath     =  DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id'], 'select' => ['path_template']]);
254
        $attachmentFilePath = $attachmentPath['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
255
256
257
258
259
260
261
262
        $attachmentFileName = 'projet_courrier_' . $aArgs['resIdMaster'] . '_' . rand(0001, 9999) . '.pdf';

        $zip         = new \ZipArchive();
        $tmpPath     = CoreConfigModel::getTmpPath();
        $zipFilePath = $tmpPath . DIRECTORY_SEPARATOR
            . $attachmentFileName . '.zip';  // The zip file need to have the same name as the attachment we want to sign

        if ($zip->open($zipFilePath, \ZipArchive::CREATE)!==true) {
263
            return ['error' => "Can not open file : <$zipFilePath>\n"];
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
        }
        $zip->addFile($attachmentFilePath, $attachmentFileName);

        if (!empty($aArgs['annexes']['letterbox'])) {
            $zip->addFile($aArgs['annexes']['letterbox'][0]['filePath'], 'document_principal.' . $aArgs['annexes']['letterbox'][0]['format']);
        }

        if (isset($aArgs['annexes']['attachments'])) {
            for ($j = 0; $j < count($aArgs['annexes']['attachments']); $j++) {
                $zip->addFile(
                    $aArgs['annexes']['attachments'][$j]['filePath'],
                    'PJ_' . ($j + 1) . '.' . $aArgs['annexes']['attachments'][$j]['format']
                );
            }
        }

        $zip->close();

        $b64Attachment = base64_encode(file_get_contents($zipFilePath));
        $fileName      = $attachmentFileName . '.zip';
284
        $circuitId     = str_replace('.', '-', $aArgs['circuitId']);
285
286
287
288
289
290
291
292
293

        $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sei="http://sei.ws.fast.cdc.com/">
                <soapenv:Header/>
                    <soapenv:Body>
                        <sei:upload>
                            <label>' . $aArgs['label'] . '</label>
                            <comment></comment>
                            <subscriberId>' . $aArgs['subscriberId'] . '</subscriberId>
294
                            <circuitId>' . $circuitId . '</circuitId>
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
                            <dataFileVO>
                                <dataHandler>' . $b64Attachment . '</dataHandler>
                                <filename>' . $fileName . '</filename>
                            </dataFileVO>
                        </sei:upload>
                    </soapenv:Body>
            </soapenv:Envelope>';

        $curlReturn = CurlModel::execSOAP([
            'xmlPostString' => $xmlPostString,
            'url'           => $aArgs['config']['data']['url'],
            'options'       => [
                CURLOPT_SSLCERT       => $aArgs['config']['data']['certPath'],
                CURLOPT_SSLCERTPASSWD => $aArgs['config']['data']['certPass'],
                CURLOPT_SSLCERTTYPE   => $aArgs['config']['data']['certType']
            ]
        ]);

313
314
315
316
317
318
319
320
321
        if ($curlReturn['infos']['http_code'] == 404) {
            return ['error' => 'Erreur 404 : ' . $curlReturn['raw']];
        } elseif (!empty($curlReturn['error'])) {
            return ['error' => $curlReturn['error']];
        } elseif (!empty($curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0])) {
            $error = (string)$curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0]->children()->faultstring . PHP_EOL;
            return ['error' => $error];
        }

322
        FastParapheurController::processVisaWorkflow(['res_id_master' => $aArgs['resIdMaster'], 'processSignatory' => false]);
323
324
        $documentId = $curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://sei.ws.fast.cdc.com/')->uploadResponse->children();
        return ['success' => (string)$documentId];
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    }

    public static function download($aArgs)
    {
        $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sei="http://sei.ws.fast.cdc.com/">
                <soapenv:Header/>
                <soapenv:Body>
                    <sei:download>
                        <documentId>' . $aArgs['documentId'] . '</documentId>
                    </sei:download>
                </soapenv:Body>
            </soapenv:Envelope>';

        $curlReturn = CurlModel::execSOAP([
            'xmlPostString' => $xmlPostString,
            'url'           => $aArgs['config']['data']['url'],
            'options'       => [
                CURLOPT_SSLCERT       => $aArgs['config']['data']['certPath'],
                CURLOPT_SSLCERTPASSWD => $aArgs['config']['data']['certPass'],
                CURLOPT_SSLCERTTYPE   => $aArgs['config']['data']['certType']
            ]
        ]);

        $isError = $curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body;
        if (!empty($isError ->Fault[0])) {
            echo (string)$curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0]->children()->faultstring . PHP_EOL;
            return false;
        } else {
            $response = $curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://sei.ws.fast.cdc.com/')->downloadResponse->children()->return;
            $returnedDocumentId = (string) $response->documentId;
            if ($aArgs['documentId'] !== $returnedDocumentId) {
                return false;
            } else {
                $b64FileContent = $response->content;
                return ['b64FileContent' => (string)$b64FileContent, 'documentId' => $returnedDocumentId];
            }
        }
    }

    public static function sendDatas($aArgs)
    {
        $config = $aArgs['config'];
        // We need the SIRET field and the user_id of the signatory user's primary entity
        $signatory = DatabaseModel::select([
370
            'select'    => ['user_id', 'external_id', 'entities.entity_label'],
371
372
            'table'     => ['listinstance', 'users_entities', 'entities'],
            'left_join' => ['item_id = user_id', 'users_entities.entity_id = entities.entity_id'],
373
            'where'     => ['res_id = ?', 'item_mode = ?', 'process_date is null'],
374
375
376
377
378
379
380
381
382
383
            'data'      => [$aArgs['resIdMaster'], 'sign']
        ])[0];
        $redactor = DatabaseModel::select([
            'select'    => ['short_label'],
            'table'     => ['res_view_letterbox', 'users_entities', 'entities'],
            'left_join' => ['dest_user = user_id', 'users_entities.entity_id = entities.entity_id'],
            'where'     => ['res_id = ?'],
            'data'      => [$aArgs['resIdMaster']]
        ])[0];

384
        $signatory['business_id'] = json_decode($signatory['external_id'], true)['fastParapheurSubscriberId'];
385
386
387
388
        if (empty($signatory['business_id']) || substr($signatory['business_id'], 0, 3) == 'org') {
            $signatory['business_id'] = $config['data']['subscriberId'];
        }

389
390
391
392
393
        if (!empty($signatory['user_id'])) {
            $user = UserModel::getById(['id' => $signatory['user_id'], 'select' => ['user_id']]);
        }

        return FastParapheurController::upload(['config' => $config, 'resIdMaster' => $aArgs['resIdMaster'], 'businessId' => $signatory['business_id'], 'circuitId' => $user['user_id'], 'label' => $redactor['short_label']]);
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
    }

    public static function getRefusalMessage($aArgs)
    {
        $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sei="http://sei.ws.fast.cdc.com/">
            <soapenv:Header/>
                <soapenv:Body>
                    <sei:getRefusalMessage>
                        <nodeRefId>' .  $aArgs['documentId'] . '</nodeRefId>
                    </sei:getRefusalMessage>
                </soapenv:Body>
         </soapenv:Envelope>';

        $curlReturn = CurlModel::execSOAP([
            'xmlPostString' => $xmlPostString,
            'url'           => $aArgs['config']['data']['url'],
            'options'       => [
                CURLOPT_SSLCERT       => $aArgs['config']['data']['certPath'],
                CURLOPT_SSLCERTPASSWD => $aArgs['config']['data']['certPass'],
                CURLOPT_SSLCERTTYPE   => $aArgs['config']['data']['certType']
            ]
        ]);

        $response = $curlReturn['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://sei.ws.fast.cdc.com/')->getRefusalMessageResponse->children()->return;

        return $response;
    }
}