ActionMethodController.php 48.5 KB
Newer Older
Damien's avatar
Damien committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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   ActionController
* @author  dev <dev@maarch.org>
* @ingroup core
*/

namespace Action\controllers;

15
16
17
18
use AcknowledgementReceipt\models\AcknowledgementReceiptModel;
use Action\models\ActionModel;
use Action\models\BasketPersistenceModel;
use Action\models\ResMarkAsReadModel;
19
use Alfresco\controllers\AlfrescoController;
Damien's avatar
Damien committed
20
use Attachment\models\AttachmentModel;
21
use Attachment\models\AttachmentTypeModel;
22
use Basket\models\BasketModel;
23
24
25
26
use Convert\controllers\ConvertPdfController;
use Convert\models\AdrModel;
use Docserver\controllers\DocserverController;
use Docserver\models\DocserverModel;
Damien's avatar
Damien committed
27
use Entity\controllers\ListInstanceController;
28
use Entity\models\EntityModel;
29
use Entity\models\ListInstanceHistoryModel;
30
use Entity\models\ListInstanceModel;
31
use Entity\models\ListTemplateModel;
32
use ExternalSignatoryBook\controllers\MaarchParapheurController;
33
use Folder\models\ResourceFolderModel;
Damien's avatar
Damien committed
34
use History\controllers\HistoryController;
35
use MessageExchange\controllers\MessageExchangeReviewController;
36
use Note\models\NoteEntityModel;
37
use Note\models\NoteModel;
38
use Parameter\models\ParameterModel;
39
use RegisteredMail\controllers\RegisteredMailTrait;
40
use ExportSeda\controllers\ExportSEDATrait;
41
use Resource\controllers\ResController;
42
use Resource\controllers\StoreController;
Damien's avatar
Damien committed
43
use Resource\models\ResModel;
44
use Resource\models\ResourceContactModel;
Florian Azizian's avatar
Florian Azizian committed
45
use Respect\Validation\Validator;
46
use SrcCore\controllers\LogsController;
47
use SrcCore\models\CoreConfigModel;
48
use SrcCore\models\DatabaseModel;
49
use SrcCore\models\ValidatorModel;
50
use Tag\models\ResourceTagModel;
Damien's avatar
Damien committed
51
use User\models\UserModel;
Damien's avatar
Damien committed
52
53
54

class ActionMethodController
{
Damien's avatar
Damien committed
55
    use AcknowledgementReceiptTrait;
56
    use RegisteredMailTrait;
Damien's avatar
Damien committed
57
    use ShippingTrait;
58
    use ExternalSignatoryBookTrait;
59
    use ExportSEDATrait;
Damien's avatar
Damien committed
60

Damien's avatar
Damien committed
61
    const COMPONENTS_ACTIONS = [
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        'confirmAction'                             => null,
        'closeMailAction'                           => 'closeMailAction',
        'closeMailWithAttachmentsOrNotesAction'     => 'closeMailWithAttachmentsOrNotesAction',
        'redirectAction'                            => 'redirect',
        'closeAndIndexAction'                       => 'closeMailAction',
        'updateDepartureDateAction'                 => 'updateDepartureDateAction',
        'enabledBasketPersistenceAction'            => 'enabledBasketPersistenceAction',
        'disabledBasketPersistenceAction'           => 'disabledBasketPersistenceAction',
        'resMarkAsReadAction'                       => 'resMarkAsReadAction',
        'sendExternalSignatoryBookAction'           => 'sendExternalSignatoryBookAction',
        'sendExternalNoteBookAction'                => 'sendExternalNoteBookAction',
        'createAcknowledgementReceiptsAction'       => 'createAcknowledgementReceipts',
        'updateAcknowledgementSendDateAction'       => 'updateAcknowledgementSendDateAction',
        'sendShippingAction'                        => 'createMailevaShippings',
        'sendSignatureBookAction'                   => 'sendSignatureBook',
        'continueVisaCircuitAction'                 => 'continueVisaCircuit',
        'redirectInitiatorEntityAction'             => 'redirectInitiatorEntityAction',
        'rejectVisaBackToPreviousAction'            => 'rejectVisaBackToPrevious',
        'resetVisaAction'                           => 'resetVisa',
        'interruptVisaAction'                       => 'interruptVisa',
        'sendToParallelOpinion'                     => 'sendToParallelOpinion',
        'sendToOpinionCircuitAction'                => 'sendToOpinionCircuit',
        'continueOpinionCircuitAction'              => 'continueOpinionCircuit',
        'giveOpinionParallelAction'                 => 'giveOpinionParallel',
        'validateParallelOpinionDiffusionAction'    => 'validateParallelOpinionDiffusion',
        'reconcileAction'                           => 'reconcile',
88
        'sendAlfrescoAction'                        => 'sendResourceAlfresco',
89
        'saveRegisteredMailAction'                  => 'saveAndPrintRegisteredMail',
90
        'saveAndPrintRegisteredMailAction'          => 'saveAndPrintRegisteredMail',
91
        'saveAndIndexRegisteredMailAction'          => 'saveAndPrintRegisteredMail',
92
        'printRegisteredMailAction'                 => 'printRegisteredMail',
93
        'printDepositListAction'                    => 'printDepositList',
94
95
96
        'sendToRecordManagementAction'              => 'sendToRecordManagement',
        'checkAcknowledgmentRecordManagementAction' => 'checkAcknowledgmentRecordManagement',
        'checkReplyRecordManagementAction'          => 'checkReplyRecordManagement',
97
        'resetRecordManagementAction'               => 'checkReplyRecordManagement',
98
        'noConfirmAction'                           => null
Damien's avatar
Damien committed
99
100
    ];

101
    public static function terminateAction(array $args)
Damien's avatar
Damien committed
102
    {
103
104
105
106
        ValidatorModel::notEmpty($args, ['id', 'resources']);
        ValidatorModel::intVal($args, ['id']);
        ValidatorModel::arrayType($args, ['resources', 'note']);
        ValidatorModel::stringType($args, ['basketName', 'history']);
Damien's avatar
Damien committed
107
108
109

        $set = ['locker_user_id' => null, 'locker_time' => null, 'modification_date' => 'CURRENT_TIMESTAMP'];

110
111
112
113
114
115
116
117
118
119
120
121
        $action = ActionModel::getById(['id' => $args['id'], 'select' => ['label_action', 'id_status', 'history', 'parameters']]);
        $action['parameters'] = json_decode($action['parameters'], true);

        if (empty($args['finishInScript'])) {
            $status = !empty($action['parameters']['successStatus']) ? $action['parameters']['successStatus'] : $action['id_status'];
            if (!empty($status) && $status != '_NOSTATUS_') {
                $set['status'] = $status;
            }
        } else {
            if (!empty($action['id_status']) && $action['id_status'] != '_NOSTATUS_') {
                $set['status'] = $action['id_status'];
            }
Damien's avatar
Damien committed
122
123
124
125
        }

        ResModel::update([
            'set'   => $set,
126
            'where' => ['res_id in (?)'],
127
            'data'  => [$args['resources']]
Damien's avatar
Damien committed
128
129
        ]);

130
131
132
133
134
135
136
        $resLetterboxData = ResModel::get([
            'select' => ['external_id', 'destination', 'res_id'],
            'where'  => ['res_id in (?)'],
            'data'   => [$args['resources']]
        ]);
        $resLetterboxData = array_column($resLetterboxData, null, 'res_id');

137
138
139
        foreach ($args['resources'] as $resource) {
            if (!empty(trim($args['note']['content']))) {
                $noteId = NoteModel::create([
140
                    'resId'     => $resource,
141
                    'user_id'   => $GLOBALS['id'],
142
                    'note_text' => $args['note']['content']
143
                ]);
144
145
146
147
148
149

                if (!empty($noteId) && !empty($args['note']['entities'])) {
                    foreach ($args['note']['entities'] as $entity) {
                        NoteEntityModel::create(['item_id' => $entity, 'note_id' => $noteId]);
                    }
                }
150
151
152
153
154
155
156
157
158
159

                if (!empty($noteId)) {
                    HistoryController::add([
                        'tableName' => "notes",
                        'recordId'  => $noteId,
                        'eventType' => "ADD",
                        'info'      => _NOTE_ADDED . " (" . $noteId . ")",
                        'moduleId'  => 'notes',
                        'eventId'   => 'noteadd'
                    ]);
160
161
162
163
164
165
166
167
168

                    HistoryController::add([
                        'tableName' => 'res_letterbox',
                        'recordId'  => $resource,
                        'eventType' => 'ADD',
                        'info'      => _NOTE_ADDED,
                        'moduleId'  => 'resource',
                        'eventId'   => 'resourceModification'
                    ]);
169
                }
170
171
            }

172
            if ($action['history'] == 'Y') {
173
174
                $info = "{$action['label_action']}{$args['history']}";
                $info = empty($args['basketName']) ? $info : "{$args['basketName']} : {$info}";
175
                HistoryController::add([
176
                    'tableName' => 'res_letterbox',
177
                    'recordId'  => $resource,
178
                    'eventType' => 'ACTION#' . $args['id'],
179
                    'info'      => $info,
Damien's avatar
Damien committed
180
                    'moduleId'  => 'resource',
181
                    'eventId'   => $args['id']
182
183
                ]);

184
                MessageExchangeReviewController::sendMessageExchangeReview(['resource' => $resLetterboxData[$resource], 'action_id' => $args['id'], 'userId' => $GLOBALS['login']]);
185
            }
Damien's avatar
Damien committed
186
187
188
189
        }

        return true;
    }
190
191
192

    public static function closeMailAction(array $aArgs)
    {
193
194
        ValidatorModel::notEmpty($aArgs, ['resId']);
        ValidatorModel::intVal($aArgs, ['resId']);
195

196
        ResModel::update(['set' => ['closing_date' => 'CURRENT_TIMESTAMP'], 'where' => ['res_id = ?', 'closing_date is null'], 'data' => [$aArgs['resId']]]);
197
198
199

        return true;
    }
200

201
202
203
204
    public static function closeMailWithAttachmentsOrNotesAction(array $aArgs)
    {
        ValidatorModel::notEmpty($aArgs, ['resId']);
        ValidatorModel::intVal($aArgs, ['resId']);
205
        ValidatorModel::arrayType($aArgs, ['note']);
206
207
208
209
210
211
212
213
214

        $attachments = AttachmentModel::get([
            'select' => [1],
            'where'  => ['res_id_master = ?', 'status != ?'],
            'data'   => [$aArgs['resId'], 'DEL'],
        ]);

        $notes = NoteModel::getByUserIdForResource(['select' => ['user_id', 'id'], 'resId' => $aArgs['resId'], 'userId' => $GLOBALS['id']]);

215
        if (empty($attachments) && empty($notes) && empty($aArgs['note']['content'])) {
216
217
218
            return ['errors' => ['No attachments or notes']];
        }

219
        return ActionMethodController::closeMailAction($aArgs);
220
221
    }

222
    public static function updateAcknowledgementSendDateAction(array $aArgs)
223
224
225
226
227
228
229
230
231
    {
        ValidatorModel::notEmpty($aArgs, ['resId', 'data']);
        ValidatorModel::intVal($aArgs, ['resId']);

        AcknowledgementReceiptModel::updateSendDate(['send_date' => date('Y-m-d H:i:s', $aArgs['data']['send_date']), 'res_id' => $aArgs['resId']]);

        return true;
    }

232
233
234
235
236
    public static function updateDepartureDateAction(array $aArgs)
    {
        ValidatorModel::notEmpty($aArgs, ['resId']);
        ValidatorModel::intVal($aArgs, ['resId']);

237
        ResModel::update(['set' => ['departure_date' => 'CURRENT_TIMESTAMP'], 'where' => ['res_id = ?', 'departure_date is null'], 'data' => [$aArgs['resId']]]);
238
239
240

        return true;
    }
241
242
243
244
245
246
247
248

    public static function disabledBasketPersistenceAction(array $aArgs)
    {
        ValidatorModel::notEmpty($aArgs, ['resId']);
        ValidatorModel::intVal($aArgs, ['resId']);

        BasketPersistenceModel::delete([
            'where' => ['res_id = ?',  'user_id = ?'],
249
            'data'  => [$aArgs['resId'], $GLOBALS['id']]
250
251
252
253
        ]);

        BasketPersistenceModel::create([
            'res_id'        => $aArgs['resId'],
254
            'user_id'       => $GLOBALS['id'],
255
256
257
258
259
260
261
262
263
264
265
266
267
            'is_persistent' => 'N'
        ]);

        return true;
    }

    public static function enabledBasketPersistenceAction(array $aArgs)
    {
        ValidatorModel::notEmpty($aArgs, ['resId']);
        ValidatorModel::intVal($aArgs, ['resId']);

        BasketPersistenceModel::delete([
            'where' => ['res_id = ?', 'user_id = ?'],
268
            'data'  => [$aArgs['resId'], $GLOBALS['id']]
269
270
271
272
        ]);

        BasketPersistenceModel::create([
            'res_id'        => $aArgs['resId'],
273
            'user_id'       => $GLOBALS['id'],
274
275
276
277
278
279
            'is_persistent' => 'Y'
        ]);

        return true;
    }

280
    public static function resMarkAsReadAction(array $args)
281
    {
282
283
        ValidatorModel::notEmpty($args, ['resId', 'data']);
        ValidatorModel::intVal($args, ['resId']);
284

285
286
287
288
289
        $basket['basket_id'] = 0;
        if (is_numeric($args['data']['basketId'])) {
            $basket = BasketModel::getById(['id' => $args['data']['basketId'], 'select' => ['basket_id']]);
        }
        
290
        ResMarkAsReadModel::delete([
291
292
            'where' => ['res_id = ?', 'user_id = ?', '(basket_id = ? OR basket_id = ?)'],
            'data'  => [$args['resId'], $GLOBALS['id'], $args['data']['basketId'], $basket['basket_id']]
293
294
        ]);

295
296
297
298
        if (empty($basket['basket_id'])) {
            $basket['basket_id'] = $args['data']['basketId'];
        }

299
        ResMarkAsReadModel::create([
300
            'res_id'    => $args['resId'],
301
            'user_id'   => $GLOBALS['id'],
302
            'basket_id' => $basket['basket_id']
303
304
        ]);

Damien's avatar
Damien committed
305
306
307
        return true;
    }

Damien's avatar
Damien committed
308
309
310
311
312
313
    public static function redirect(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId', 'data']);
        ValidatorModel::intVal($args, ['resId']);
        ValidatorModel::arrayType($args, ['data']);

314
315
        $listInstances = [];
        if (!empty($args['data']['onlyRedirectDest'])) {
Damien's avatar
Damien committed
316
317
            if (count($args['data']['listInstances']) == 1) {
                $listInstances = ListInstanceModel::get(['select' => ['*'], 'where' => ['res_id = ?', 'difflist_type = ?', 'item_mode != ?'], 'data' => [$args['resId'], 'entity_id', 'dest']]);
Damien's avatar
Damien committed
318
            }
319
320
321
        }

        $listInstances = array_merge($listInstances, $args['data']['listInstances']);
322
323
324
325
326
        $controller = ListInstanceController::updateListInstance([
            'data'      => [['resId' => $args['resId'], 'listInstances' => $listInstances, 'destination' => $args['data']['destination']]],
            'userId'    => $GLOBALS['id'],
            'fullRight' => true
        ]);
Damien's avatar
Damien committed
327
        if (!empty($controller['errors'])) {
Damien's avatar
Damien committed
328
            return ['errors' => [$controller['errors']]];
Damien's avatar
Damien committed
329
330
        }

331
332
        return true;
    }
333

334
335
336
337
338
339
340
341
342
343
    public static function redirectInitiatorEntityAction(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);
        ValidatorModel::arrayType($args, ['data']);

        $resource = ResModel::getById(['select' => ['initiator'], 'resId' => $args['resId']]);
        if (!empty($resource)) {
            $entityInfo = EntityModel::getByEntityId(['entityId' => $resource['initiator'], 'select' => ['id']]);
            if (!empty($entityInfo)) {
344
                $destUser = ListTemplateModel::getWithItems(['where' => ['entity_id = ?', 'item_mode = ?', 'type = ?'], 'data' => [$entityInfo['id'], 'dest', 'diffusionList']]);
345
346
347
                if (!empty($destUser)) {
                    ListInstanceModel::update([
                        'set' => [
348
                            'item_mode' => 'cc'
349
                        ],
350
                        'where' => ['item_mode = ?', 'res_id = ?'],
351
                        'data'  => ['dest', $args['resId']]
352
                    ]);
353
                    ListInstanceModel::create([
354
355
                        'res_id'          => $args['resId'],
                        'sequence'        => 0,
356
                        'item_id'         => $destUser[0]['item_id'],
357
358
                        'item_type'       => 'user_id',
                        'item_mode'       => 'dest',
359
                        'added_by_user'   => $GLOBALS['id'],
360
361
                        'viewed'          => 0,
                        'difflist_type'   => 'entity_id'
362
                    ]);
363
                    $destUser = $destUser[0]['item_id'];
364
                } else {
365
                    $destUser = null;
366
                }
367

368
369
370
371
372
                ResModel::update([
                    'set'   => ['destination' => $resource['initiator'], 'dest_user' => $destUser],
                    'where' => ['res_id = ?'],
                    'data'  => [$args['resId']]
                ]);
373
374
375
376
377
378
            }
        }

        return true;
    }

379
    public static function sendSignatureBook(array $args)
Damien's avatar
Damien committed
380
381
382
383
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

Damien's avatar
Damien committed
384
        $circuit = ListInstanceModel::get([
385
            'select'    => ['requested_signature', 'item_mode'],
Damien's avatar
Damien committed
386
387
            'where'     => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'      => [$args['resId'], 'VISA_CIRCUIT'],
388
            'orderBy'   => ['listinstance_id']
Damien's avatar
Damien committed
389
        ]);
390
391
392
393
        if (empty($circuit)) {
            return ['errors' => ['No available circuit']];
        }

394
395
        $minimumVisaRole = ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'minimumVisaRole']);
        $maximumSignRole = ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'maximumSignRole']);
396
        $workflowEndBySignatory = ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'workflowEndBySignatory']);
397
398
399

        $minimumVisaRole = !empty($minimumVisaRole['param_value_int']) ? $minimumVisaRole['param_value_int'] : 0;
        $maximumSignRole = !empty($maximumSignRole['param_value_int']) ? $maximumSignRole['param_value_int'] : 0;
400
        $workflowEndBySignatory = !empty($workflowEndBySignatory['param_value_int']);
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417

        $nbVisaRole = 0;
        $nbSignRole = 0;
        foreach ($circuit as $listInstance) {
            if ($listInstance['item_mode'] == 'visa') {
                $nbVisaRole++;
            } elseif ($listInstance['item_mode'] == 'sign') {
                $nbSignRole++;
            }
        }
        if ($minimumVisaRole != 0 && $nbVisaRole < $minimumVisaRole) {
            return ['errors' => ['Circuit does not have enough visa users']];
        }
        if ($maximumSignRole != 0 && $nbSignRole > $maximumSignRole) {
            return ['errors' => ['Circuit have too many sign users']];
        }

418
419
420
421
422
423
424
        if ($workflowEndBySignatory) {
            $last = count($circuit) - 1;
            if ($circuit[$last]['requested_signature'] == false) {
                return ['errors' => 'Circuit last user is not a signatory'];
            }
        }

Damien's avatar
Damien committed
425
426
427
428
        $resource       = ResModel::getById(['select' => ['integrations'], 'resId' => $args['resId']]);
        $integrations   = json_decode($resource['integrations'], true);
        $resourceIn     = !empty($integrations['inSignatureBook']);

Damien's avatar
Damien committed
429
        $signableAttachmentsTypes = [];
430
431
432
433
        $attachmentsTypes = AttachmentTypeModel::get(['select' => ['type_id', 'signable']]);
        foreach ($attachmentsTypes as $type) {
            if ($type['signable']) {
                $signableAttachmentsTypes[] = $type['type_id'];
Damien's avatar
Damien committed
434
435
436
437
            }
        }

        $attachments = AttachmentModel::get([
Damien's avatar
Damien committed
438
            'select'  => ['res_id', 'status'],
439
440
            'where'   => ['res_id_master = ?', 'attachment_type in (?)', 'in_signature_book = ?', 'status not in (?)'],
            'data'    => [$args['resId'], $signableAttachmentsTypes, true, ['OBS', 'DEL', 'FRZ']]
Damien's avatar
Damien committed
441
        ]);
Damien's avatar
Damien committed
442
        if (empty($attachments) && !$resourceIn) {
Damien's avatar
Damien committed
443
444
445
            return ['errors' => ['No available attachments']];
        }

Damien's avatar
Damien committed
446
        if ($circuit[0]['requested_signature'] == true) {
447
448
449
450
451
452
453
454
455
456
457
            $attachmentsStatus = array_column($attachments, 'status');
            if (in_array('SEND_MASS', $attachmentsStatus)) {
                static $massData;
                if ($massData === null) {
                    $customId = CoreConfigModel::getCustomId();
                    $massData = [
                        'resources'     => [],
                        'successStatus' => $args['action']['parameters']['successStatus'],
                        'errorStatus'   => $args['action']['parameters']['errorStatus'],
                        'userId'        => $GLOBALS['id'],
                        'customId'      => $customId,
458
                        'action'        => 'generateMailing'
459
                    ];
Damien's avatar
Damien committed
460
                }
461
462
463

                $massData['resources'][] = ['resId' => $args['resId'], 'data' => $args['data'], 'note' => $args['note'], 'inSignatureBook' => true];

464
                return ['postscript' => 'src/app/action/scripts/MailingScript.php', 'args' => $massData];
Damien's avatar
Damien committed
465
466
467
            }
        }

Damien's avatar
Damien committed
468
469
470
        return true;
    }

471
    public static function continueVisaCircuit(array $args)
472
473
474
475
476
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

        $listInstance = ListInstanceModel::get([
477
            'select'    => ['listinstance_id', 'item_id'],
478
479
480
481
482
483
484
485
486
            'where'     => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'      => [$args['resId'], 'VISA_CIRCUIT'],
            'orderBy'   => ['listinstance_id'],
            'limit'     => 1
        ]);
        if (empty($listInstance[0])) {
            return ['errors' => ['No available circuit']];
        }

487
488
489
490
491
        $set = ['process_date' => 'CURRENT_TIMESTAMP'];
        if ($listInstance[0]['item_id'] != $GLOBALS['id']) {
            $set['delegate'] = $GLOBALS['id'];
        }

492
        ListInstanceModel::update([
493
            'set'   => $set,
494
495
496
497
            'where' => ['listinstance_id = ?'],
            'data'  => [$listInstance[0]['listinstance_id']]
        ]);

Damien's avatar
Damien committed
498
        $circuit = ListInstanceModel::get([
499
            'select'    => ['requested_signature', 'item_id', 'listinstance_id'],
Damien's avatar
Damien committed
500
501
            'where'     => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'      => [$args['resId'], 'VISA_CIRCUIT'],
502
            'orderBy'   => ['listinstance_id']
Damien's avatar
Damien committed
503
504
        ]);

505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
        $skipList = [];
        $nextValid = null;
        foreach ($circuit as $item) {
            $user = UserModel::getById(['id' => $item['item_id'], 'select' => ['status']]);
            $isValid = !empty($user) && !in_array($user['status'], ['SPD', 'DEL']);
            if (!$isValid) {
                $skipList[] = $item['listinstance_id'];
            } else {
                $nextValid = $item;
                break;
            }
        }

        if (!empty($skipList)) {
            ListInstanceModel::update([
                'set'   => [
                    'process_date' => 'CURRENT_TIMESTAMP',
                    'process_comment' => _USER_SKIPPED
                ],
                'where' => ['listinstance_id in (?)'],
                'data'  => [$skipList]
            ]);
        }

        if (empty($nextValid)) {
            return true;
        }

        if ($nextValid['requested_signature'] == true) {
Damien's avatar
Damien committed
534
535
536
537
538
            $attachments = AttachmentModel::get([
                'select'  => ['res_id'],
                'where'   => ['res_id_master = ?', 'in_signature_book = ?', 'status = ?'],
                'data'    => [$args['resId'], true, 'SEND_MASS']
            ]);
539
540
541
542
543
544
545
546
547
548
            if (!empty($attachments)) {
                static $massData;
                if ($massData === null) {
                    $customId = CoreConfigModel::getCustomId();
                    $massData = [
                        'resources'     => [],
                        'successStatus' => $args['action']['parameters']['successStatus'],
                        'errorStatus'   => $args['action']['parameters']['errorStatus'],
                        'userId'        => $GLOBALS['id'],
                        'customId'      => $customId,
549
                        'action'        => 'generateMailing'
550
                    ];
Damien's avatar
Damien committed
551
                }
552
553
554

                $massData['resources'][] = ['resId' => $args['resId'], 'data' => $args['data'], 'note' => $args['note'], 'inSignatureBook' => true];

555
                return ['postscript' => 'src/app/action/scripts/MailingScript.php', 'args' => $massData];
Damien's avatar
Damien committed
556
557
558
            }
        }

559
560
561
        return true;
    }

562
563
564
565
    public static function sendExternalNoteBookAction(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);
566
        ValidatorModel::arrayType($args, ['note']);
567
568
569
570

        $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'modules/visa/xml/remoteSignatoryBooks.xml']);
        $config = [];

571
        $historyInfo = '';
572
573
574
575
576
577
578
579
580
581
        if (!empty($loadedXml)) {
            $config['id'] = 'maarchParapheur';
            foreach ($loadedXml->signatoryBook as $value) {
                if ($value->id == $config['id']) {
                    $config['data'] = (array)$value;
                    break;
                }
            }

            $processingUserInfo = MaarchParapheurController::getUserById(['config' => $config, 'id' => $args['data']['processingUser']]);
582
            $sentInfo = MaarchParapheurController::sendDatas([
583
584
585
586
                'config'          => $config,
                'resIdMaster'     => $args['resId'],
                'processingUser'  => $args['data']['processingUser'],
                'objectSent'      => 'mail',
587
                'userId'          => $GLOBALS['login'],
588
                'note'            => $args['note']['content'] ?? null
589
            ]);
590
591
            if (!empty($sentInfo['error'])) {
                return ['errors' => [$sentInfo['error']]];
592
            } else {
593
                $attachmentToFreeze = $sentInfo['sended'];
594
595
596
597
598
599
600
            }

            $historyInfo = ' (à ' . $processingUserInfo['firstname'] . ' ' . $processingUserInfo['lastname'] . ')';
        }

        if (!empty($attachmentToFreeze)) {
            ResModel::update([
601
602
603
                'postSet' => ['external_id' => "jsonb_set(external_id, '{signatureBookId}', '{$attachmentToFreeze['letterbox_coll'][$args['resId']]}'::text::jsonb)"],
                'where'   => ['res_id = ?'],
                'data'    => [$args['resId']]
604
605
606
607
608
            ]);
        }

        return ['history' => $historyInfo];
    }
609
610
611
612
613
614
615

    public static function rejectVisaBackToPrevious(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

        $listInstances = ListInstanceModel::get([
616
617
618
619
620
            'select'  => ['listinstance_id'],
            'where'   => ['res_id = ?', 'difflist_type = ?', 'process_date is not null'],
            'data'    => [$args['resId'], 'VISA_CIRCUIT'],
            'orderBy' => ['listinstance_id desc'],
            'limit'   => 1
621
622
        ]);

623
        $listInstancesIdsToReset = [];
624
625
626
627
628
629
630
631
632
        if (empty($listInstances[0])) {
            $hasCircuit = ListInstanceModel::get(['select' => [1], 'where' => ['res_id = ?', 'difflist_type = ?'], 'data' => [$args['resId'], 'VISA_CIRCUIT']]);
            if (!empty($hasCircuit)) {
                return ['errors' => ['Workflow has ended']];
            } else {
                return ['errors' => ['No workflow defined']];
            }
        } else {
            $hasPrevious = ListInstanceModel::get([
633
                'select'  => ['listinstance_id', 'item_id'],
634
635
                'where'   => ['res_id = ?', 'difflist_type = ?', 'process_date is not null'],
                'data'    => [$args['resId'], 'VISA_CIRCUIT'],
636
                'orderBy' => ['listinstance_id desc'],
637
            ]);
638
            if (empty($hasPrevious)) {
639
640
                return ['errors' => ['Workflow not yet started']];
            }
641
642
643
644
645
646
647
648
649
650
651
652
            $validFound = false;
            foreach ($hasPrevious as $previous) {
                $user = UserModel::getById(['id' => $previous['item_id'], 'select' => ['status']]);
                $listInstancesIdsToReset[] = $previous['listinstance_id'];
                if (!empty($user) && !in_array($user['status'], ['SPD', 'DEL'])) {
                    $validFound = true;
                    break;
                }
            }
            if (!$validFound) {
                return ['errors' => ['No available previous user to return to']];
            }
653
654
        }

655
656
        if (!empty($listInstancesIdsToReset)) {
            ListInstanceModel::update([
657
                'set'   => ['process_date' => null, 'process_comment' => null, 'delegate' => null],
658
659
660
661
                'where' => ['listinstance_id in (?)'],
                'data'  => [$listInstancesIdsToReset]
            ]);
        }
662
663
664

        return true;
    }
665

666
    public static function resetVisa(array $args)
667
668
669
670
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
        $inCircuit = ListInstanceModel::get([
            'select'  => [1],
            'where'   => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'    => [$args['resId'], 'VISA_CIRCUIT'],
            'orderBy' => ['listinstance_id'],
            'limit'   => 1
        ]);
        if (empty($inCircuit[0])) {
            $hasCircuit = ListInstanceModel::get(['select' => [1], 'where' => ['res_id = ?', 'difflist_type = ?'], 'data' => [$args['resId'], 'VISA_CIRCUIT']]);
            if (!empty($hasCircuit)) {
                return ['errors' => ['Workflow has ended']];
            } else {
                return ['errors' => ['No workflow defined']];
            }
        }

687
        ListInstanceModel::update([
688
            'set'   => ['process_date' => null, 'process_comment' => null],
689
690
691
692
693
694
            'where' => ['res_id = ?', 'difflist_type = ?'],
            'data'  => [$args['resId'], 'VISA_CIRCUIT']
        ]);

        return true;
    }
695
696
697
698
699
700
701
702

    public static function interruptVisa(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);


        $listInstances = ListInstanceModel::get([
703
            'select'   => ['listinstance_id', 'item_id'],
704
705
706
707
708
709
            'where'    => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'     => [$args['resId'], 'VISA_CIRCUIT'],
            'orderBy' => ['listinstance_id'],
            'limit'    => 1
        ]);

710
        if (!empty($listInstances[0])) {
711
712
            $listInstances = $listInstances[0];

713
            $set = ['process_date' => 'CURRENT_TIMESTAMP', 'process_comment' => _HAS_INTERRUPTED_WORKFLOW . ' (' . _VIA_ACTION . ' "' . $args['action']['label_action'] . '")'];
714
715
716
            if ($listInstances['item_id'] != $GLOBALS['id']) {
                $set['delegate'] = $GLOBALS['id'];
            }
717
            ListInstanceModel::update([
718
                'set'   => $set,
719
720
721
                'where' => ['listinstance_id = ?'],
                'data'  => [$listInstances['listinstance_id']]
            ]);
722
723
724
725
726
727
728
        } else {
            $hasCircuit = ListInstanceModel::get(['select' => [1], 'where' => ['res_id = ?', 'difflist_type = ?'], 'data' => [$args['resId'], 'VISA_CIRCUIT']]);
            if (!empty($hasCircuit)) {
                return ['errors' => ['Workflow has ended']];
            } else {
                return ['errors' => ['No workflow defined']];
            }
729
730
731
732
733
        }

        ListInstanceModel::update([
            'set'   => [
                'process_date' => 'CURRENT_TIMESTAMP',
734
                'process_comment' => _INTERRUPTED_WORKFLOW
735
736
737
738
739
740
741
            ],
            'where' => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'  => [$args['resId'], 'VISA_CIRCUIT']
        ]);

        return true;
    }
742

743
    public static function sendToOpinionCircuit(array $args)
744
745
746
747
748
749
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

        $listinstances = ListInstanceModel::get([
            'select' => [1],
750
751
            'where'  => ['res_id = ?', 'difflist_type = ?'],
            'data'   => [$args['resId'], 'AVIS_CIRCUIT']
752
753
754
755
756
757
        ]);

        if (empty($listinstances)) {
            return ['errors' => ['No available opinion workflow']];
        }

758
759
760
761
        if (empty($args['data']['opinionLimitDate'])) {
            return ["errors" => ["Opinion limit date is missing"]];
        }

762
763
764
        $opinionLimitDate = new \DateTime($args['data']['opinionLimitDate']);
        $today = new \DateTime('today');
        if ($opinionLimitDate < $today) {
765
            return ['errors' => ["Opinion limit date is not a valid date"]];
766
767
        }

768
769
        ResModel::update([
            'set'   => ['opinion_limit_date' => $args['data']['opinionLimitDate']],
770
771
772
773
774
775
776
777
778
            'where' => ['res_id = ?'],
            'data'  => [$args['resId']]
        ]);

        return true;
    }

    public static function sendToParallelOpinion(array $args)
    {
779
780
781
        if (empty($args['resId'])) {
            return ['errors' => ['resId is empty']];
        }
782

783
784
785
        if (!Validator::intVal()->validate($args['resId']) || !ResController::hasRightByResId(['resId' => [$args['resId']], 'userId' => $GLOBALS['id']])) {
            return ['errors' => ['Document out of perimeter']];
        }
786

787
788
789
        if (empty($args['data']['opinionLimitDate'])) {
            return ["errors" => ["Opinion limit date is missing"]];
        }
790

791
792
793
        $opinionLimitDate = new \DateTime($args['data']['opinionLimitDate']);
        $today = new \DateTime('today');
        if ($opinionLimitDate < $today) {
794
            return ['errors' => ["Opinion limit date is not a valid date"]];
795
        }
796

797
798
799
        if (empty($args['data']['opinionCircuit'])) {
            return ['errors' => "opinionCircuit is empty"];
        }
800

801
802
803
804
        foreach ($args['data']['opinionCircuit'] as $instance) {
            if (!in_array($instance['item_mode'], ['avis', 'avis_copy', 'avis_info'])) {
                return ['errors' => ['item_mode is different from avis, avis_copy or avis_info']];
            }
805

806
807
808
809
            $listControl = ['item_id', 'item_type'];
            foreach ($listControl as $itemControl) {
                if (empty($instance[$itemControl])) {
                    return ['errors' => ["ListInstance {$itemControl} is not set or empty"]];
810
811
                }
            }
812
        }
813

814
815
816
817
818
819
820
821
822
        DatabaseModel::beginTransaction();

        ListInstanceModel::delete([
            'where' => ['res_id = ?', 'difflist_type = ?', 'item_mode in (?)'],
            'data'  => [$args['resId'], 'entity_id', ['avis', 'avis_copy', 'avis_info']]
        ]);

        foreach ($args['data']['opinionCircuit'] as $key => $instance) {
            if (in_array($instance['item_type'], ['user_id', 'user'])) {
823
                $user = UserModel::getById(['id' => $instance['item_id'], 'select' => [1]]);
824
                if (empty($user)) {
825
                    DatabaseModel::rollbackTransaction();
826
                    return ['errors' => ['User not found']];
827
                }
828
829
830
            } else {
                DatabaseModel::rollbackTransaction();
                return ['errors' => ['item_type does not exist']];
831
832
            }

833
834
835
836
            ListInstanceModel::create([
                'res_id'                => $args['resId'],
                'sequence'              => $key,
                'item_id'               => $instance['item_id'],
837
                'item_type'             => 'user_id',
838
                'item_mode'             => $instance['item_mode'],
839
                'added_by_user'         => $GLOBALS['id'],
840
841
842
843
844
845
                'difflist_type'         => 'entity_id',
                'process_date'          => null,
                'process_comment'       => null,
                'requested_signature'   => false,
                'viewed'                => empty($instance['viewed']) ? 0 : $instance['viewed']
            ]);
846
847
        }

848
        DatabaseModel::commitTransaction();
849
850
851
852
853

        ResModel::update([
            'set'   => ['opinion_limit_date' => $args['data']['opinionLimitDate']],
            'where' => ['res_id = ?'],
            'data'  => [$args['resId']]
854
855
        ]);

856
857
        return true;
    }
858
859
860
861
862
863
864
865
866
867
868
869
870
871

    public static function continueOpinionCircuit(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

        $currentStep = ListInstanceModel::get([
            'select'  => ['listinstance_id', 'item_id'],
            'where'   => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'    => [$args['resId'], 'AVIS_CIRCUIT'],
            'orderBy' => ['listinstance_id'],
            'limit'   => 1
        ]);

872
        if (empty($currentStep)) {
873
874
875
876
            return ['errors' => ['No workflow or workflow finished']];
        }
        $currentStep = $currentStep[0];

877
878
        $set = ['process_date' => 'CURRENT_TIMESTAMP'];

879
        $message = null;
880
        if ($currentStep['item_id'] != $GLOBALS['id']) {
881
882
883
            $currentUser = UserModel::getById(['select' => ['firstname', 'lastname'], 'id' => $GLOBALS['id']]);
            $stepUser = UserModel::get([
                'select' => ['firstname', 'lastname'],
884
                'where' => ['id = ?'],
885
886
887
888
889
890
891
892
                'data' => [$currentStep['item_id']]
            ]);
            $stepUser = $stepUser[0];

            $message = ' ' . _AVIS_SENT . " " . _BY ." "
                . $currentUser['firstname'] . ' ' . $currentUser['lastname']
                . " " . _INSTEAD_OF . " "
                . $stepUser['firstname'] . ' ' . $stepUser['lastname'];
893
894

            $set['delegate'] = $GLOBALS['id'];
895
896
897
        }

        ListInstanceModel::update([
898
            'set'   => $set,
899
900
901
902
            'where' => ['listinstance_id = ?'],
            'data'  => [$currentStep['listinstance_id']]
        ]);

903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
        $circuit = ListInstanceModel::get([
            'select'    => ['requested_signature', 'item_id', 'listinstance_id'],
            'where'     => ['res_id = ?', 'difflist_type = ?', 'process_date is null'],
            'data'      => [$args['resId'], 'AVIS_CIRCUIT'],
            'orderBy'   => ['listinstance_id']
        ]);

        $skipList = [];
        $nextValid = null;
        foreach ($circuit as $item) {
            $user = UserModel::getById(['id' => $item['item_id'], 'select' => ['status']]);
            $isValid = !empty($user) && !in_array($user['status'], ['SPD', 'DEL']);
            if (!$isValid) {
                $skipList[] = $item['listinstance_id'];
            } else {
                $nextValid = $item;
                break;
            }
        }

        if (!empty($skipList)) {
            ListInstanceModel::update([
                'set'   => [
                    'process_date' => 'CURRENT_TIMESTAMP',
                    'process_comment' => _USER_SKIPPED
                ],
                'where' => ['listinstance_id in (?)'],
                'data'  => [$skipList]
            ]);
        }

        if (empty($nextValid)) {
            return true;
        }

938
939
940
        if ($message == null) {
            return true;
        }
941

942
943
        return ['history' => $message];
    }
944
945
946

    public static function giveOpinionParallel(array $args)
    {
947
948
        ValidatorModel::notEmpty($args, ['resId', 'userId']);
        ValidatorModel::intVal($args, ['resId', 'userId']);
949
950

        $currentStep = ListInstanceModel::get([
951
            'select'  => ['listinstance_id', 'item_id'],
952
            'where'   => ['res_id = ?', 'difflist_type = ?', 'item_id = ?', 'item_mode in (?)'],
953
            'data'    => [$args['resId'], 'entity_id', $args['userId'], ['avis', 'avis_copy', 'avis_info']],
954
955
956
957
958
959
960
961
            'limit'   => 1
        ]);

        if (empty($currentStep)) {
            return ['errors' => ['No workflow available']];
        }
        $currentStep = $currentStep[0];

962
963
964
965
966
        $set = ['process_date' => 'CURRENT_TIMESTAMP'];
        if ($currentStep['item_id'] != $GLOBALS['id']) {
            $set['delegate'] = $GLOBALS['id'];
        }

967
        ListInstanceModel::update([
968
            'set'   => $set,
969
970
971
972
973
974
            'where' => ['listinstance_id = ?'],
            'data'  => [$currentStep['listinstance_id']]
        ]);

        return true;
    }
975

976
    public static function validateParallelOpinionDiffusion(array $args)
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

        if (empty($args['data']['opinionLimitDate'])) {
            return ["errors" => ["Opinion limit date is missing"]];
        }

        $opinionLimitDate = new \DateTime($args['data']['opinionLimitDate']);
        $today = new \DateTime('today');
        if ($opinionLimitDate < $today) {
            return ['errors' => ["Opinion limit date is not a valid date"]];
        }

        $latestNote = NoteModel::get([
            'where'  => ['identifier = ?', "note_text like '[" . _TO_AVIS . "]%'"],
            'data'   => [$args['resId']],
            'oderBy' => ['creation_date desc'],
            'limit'  => 1
        ]);

        if (empty($latestNote)) {
            return ["errors" => ["No note for opinion available"]];
        }