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

namespace Action\controllers;

use AcknowledgementReceipt\models\AcknowledgementReceiptModel;
16
use Action\models\ActionModel;
17
use Attachment\models\AttachmentModel;
18
use Attachment\models\AttachmentTypeModel;
Damien's avatar
Damien committed
19
20
use Basket\models\BasketModel;
use Basket\models\GroupBasketRedirectModel;
21
use Configuration\models\ConfigurationModel;
22
use Contact\controllers\ContactController;
Damien's avatar
Damien committed
23
use Contact\models\ContactModel;
24
use Convert\controllers\ConvertPdfController;
25
use Convert\models\AdrModel;
26
use CustomField\models\CustomFieldModel;
Damien's avatar
Damien committed
27
use Docserver\models\DocserverModel;
28
use Docserver\models\DocserverTypeModel;
29
use Doctype\models\DoctypeModel;
30
use Email\controllers\EmailController;
Damien's avatar
Damien committed
31
use Entity\models\EntityModel;
32
use Entity\models\ListInstanceModel;
33
use ExternalSignatoryBook\controllers\IxbusController;
34
use ExternalSignatoryBook\controllers\MaarchParapheurController;
35
use Group\controllers\PrivilegeController;
Damien's avatar
Damien committed
36
use Group\models\GroupModel;
37
use IndexingModel\models\IndexingModelFieldModel;
38
use Note\models\NoteModel;
Damien's avatar
Damien committed
39
use Parameter\models\ParameterModel;
40
use RegisteredMail\models\RegisteredMailModel;
Damien's avatar
Damien committed
41
42
use Resource\controllers\ResController;
use Resource\controllers\ResourceListController;
43
use Resource\controllers\StoreController;
Damien's avatar
Damien committed
44
use Resource\models\ResModel;
45
use Resource\models\ResourceContactModel;
Damien's avatar
Damien committed
46
use Respect\Validation\Validator;
47
use Shipping\controllers\ShippingTemplateController;
48
use Shipping\models\ShippingTemplateModel;
Damien's avatar
Damien committed
49
50
51
use Slim\Http\Request;
use Slim\Http\Response;
use SrcCore\controllers\PreparedClauseController;
52
use SrcCore\models\CoreConfigModel;
53
use SrcCore\models\ValidatorModel;
Damien's avatar
Damien committed
54
55
56
use Template\models\TemplateModel;
use User\models\UserEntityModel;
use User\models\UserModel;
57
use ExportSeda\controllers\PreProcessActionSEDATrait;
Damien's avatar
Damien committed
58
59
60

class PreProcessActionController
{
61
62
    use PreProcessActionSEDATrait;

Damien's avatar
Damien committed
63
64
    public static function getRedirectInformations(Request $request, Response $response, array $args)
    {
65
        $errors = ResourceListController::listControl(['groupId' => $args['groupId'], 'userId' => $args['userId'], 'basketId' => $args['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $basket = BasketModel::getById(['id' => $args['basketId'], 'select' => ['basket_id']]);
        $group = GroupModel::getById(['id' => $args['groupId'], 'select' => ['group_id']]);

        $keywords = [
            'ALL_ENTITIES'          => '@all_entities',
            'ENTITIES_JUST_BELOW'   => '@immediate_children[@my_primary_entity]',
            'ENTITIES_BELOW'        => '@subentities[@my_entities]',
            'ALL_ENTITIES_BELOW'    => '@subentities[@my_primary_entity]',
            'ENTITIES_JUST_UP'      => '@parent_entity[@my_primary_entity]',
            'MY_ENTITIES'           => '@my_entities',
            'MY_PRIMARY_ENTITY'     => '@my_primary_entity',
            'SAME_LEVEL_ENTITIES'   => '@sisters_entities[@my_primary_entity]'
        ];

Damien's avatar
Damien committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
        $users = [];
        $allEntities = [];

        foreach (['ENTITY', 'USERS'] as $mode) {
            $entityRedirects = GroupBasketRedirectModel::get([
                'select'    => ['entity_id', 'keyword'],
                'where'     => ['basket_id = ?', 'group_id = ?', 'action_id = ?', 'redirect_mode = ?'],
                'data'      => [$basket['basket_id'], $group['group_id'], $args['actionId'], $mode]
            ]);

            $allowedEntities = [];
            $clauseToProcess = '';
            foreach ($entityRedirects as $entityRedirect) {
                if (!empty($entityRedirect['entity_id'])) {
                    $allowedEntities[] = $entityRedirect['entity_id'];
                } elseif (!empty($entityRedirect['keyword'])) {
                    if (!empty($keywords[$entityRedirect['keyword']])) {
                        if (!empty($clauseToProcess)) {
                            $clauseToProcess .= ', ';
                        }
                        $clauseToProcess .= $keywords[$entityRedirect['keyword']];
Damien's avatar
Damien committed
105
106
107
108
                    }
                }
            }

Damien's avatar
Damien committed
109
            if (!empty($clauseToProcess)) {
110
                $preparedClause = PreparedClauseController::getPreparedClause(['clause' => $clauseToProcess, 'userId' => $args['userId']]);
Damien's avatar
Damien committed
111
112
113
                $preparedEntities = EntityModel::get(['select' => ['entity_id'], 'where' => ['enabled = ?', "entity_id in {$preparedClause}"], 'data' => ['Y']]);
                foreach ($preparedEntities as $preparedEntity) {
                    $allowedEntities[] = $preparedEntity['entity_id'];
Damien's avatar
Damien committed
114
115
                }
            }
Damien's avatar
Damien committed
116
117
118
119
120
121
122
123

            $allowedEntities = array_unique($allowedEntities);

            if ($mode == 'USERS') {
                if (!empty($allowedEntities)) {
                    $users = UserEntityModel::getWithUsers([
                        'select'    => ['DISTINCT users.id', 'users.user_id', 'firstname', 'lastname'],
                        'where'     => ['users_entities.entity_id in (?)', 'status not in (?)'],
124
                        'data'      => [$allowedEntities, ['DEL', 'ABS', 'SPD']],
Damien's avatar
Damien committed
125
126
127
128
129
                        'orderBy'   => ['lastname', 'firstname']
                    ]);

                    foreach ($users as $key => $user) {
                        $users[$key]['labelToDisplay'] = "{$user['firstname']} {$user['lastname']}";
130
                        $users[$key]['descriptionToDisplay'] = UserModel::getPrimaryEntityById(['id' => $user['id'], 'select' => ['entities.entity_label']])['entity_label'];
Damien's avatar
Damien committed
131
                    }
Damien's avatar
Damien committed
132
                }
Damien's avatar
Damien committed
133
            } elseif ($mode == 'ENTITY') {
Alex ORLUC's avatar
Alex ORLUC committed
134
                $primaryEntity = UserModel::getPrimaryEntityById(['id' => $GLOBALS['id'], 'select' => ['entities.entity_id']]);
Damien's avatar
Damien committed
135
136
137
138
139
140
141
142
143
144
145

                $allEntities = EntityModel::get(['select' => ['id', 'entity_id', 'entity_label', 'parent_entity_id'], 'where' => ['enabled = ?'], 'data' => ['Y'], 'orderBy' => ['parent_entity_id']]);
                foreach ($allEntities as $key => $value) {
                    $allEntities[$key]['id'] = $value['entity_id'];
                    $allEntities[$key]['serialId'] = $value['id'];
                    if (empty($value['parent_entity_id'])) {
                        $allEntities[$key]['parent'] = '#';
                        $allEntities[$key]['icon'] = "fa fa-building";
                    } else {
                        $allEntities[$key]['parent'] = $value['parent_entity_id'];
                        $allEntities[$key]['icon'] = "fa fa-sitemap";
Damien's avatar
Damien committed
146
147
                    }
                    $allEntities[$key]['state']['opened'] = false;
Damien's avatar
Damien committed
148
149
150
151
152
153
154
155
156
157
158
                    if (in_array($value['entity_id'], $allowedEntities)) {
                        $allEntities[$key]['allowed'] = true;
                        if ($primaryEntity['entity_id'] == $value['entity_id']) {
                            $allEntities[$key]['state']['opened'] = true;
                            $allEntities[$key]['state']['selected'] = true;
                        }
                    } else {
                        $allEntities[$key]['allowed'] = false;
                        $allEntities[$key]['state']['disabled'] = true;
                    }
                    $allEntities[$key]['text'] = $value['entity_label'];
Damien's avatar
Damien committed
159
160
161
162
163
164
                }
            }
        }

        $parameter = ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'keepDestForRedirection']);

Damien's avatar
Damien committed
165
        return $response->withJson(['entities' => $allEntities, 'users' => $users, 'keepDestForRedirection' => !empty($parameter['param_value_int'])]);
Damien's avatar
Damien committed
166
167
    }

168
    public function checkAcknowledgementReceipt(Request $request, Response $response, array $args)
Damien's avatar
Damien committed
169
    {
170
171
172
173
174
        $action = ActionModel::getById(['id' => $args['actionId'], 'select' => ['parameters']]);
        if (empty($action)) {
            return $response->withStatus(400)->withJson(['errors' => 'Action does not exist']);
        }
        $parameters = json_decode($action['parameters'], true);
175
176
177
178
179
180
181
182
183
184
185
186
187
        $mode       = $parameters['mode'] ?? 'auto';
        $data       = $request->getQueryParams();

        if (empty($data['mode']) && $mode == 'both') {
            $currentMode = 'auto';
        } elseif (empty($data['mode']) && $mode != 'both') {
            $currentMode = $mode;
        } elseif (!empty($data['mode'])) {
            $currentMode = $data['mode'];
        }
        if (!in_array($currentMode, ['manual', 'auto'])) {
            $currentMode = 'auto';
        }
188

189
        $errors = ResourceListController::listControl(['groupId' => $args['groupId'], 'userId' => $args['userId'], 'basketId' => $args['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $data = $request->getParsedBody();

        if (!Validator::arrayType()->notEmpty()->validate($data['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
        }

        $sendList = [];
        $sendEmail = 0;
        $sendPaper = 0;
        $noSendAR = [
            'number'    => 0,
            'list'      => [],
        ];
        $alreadyGenerated = [
            'number'    => 0,
            'list'      => [],
        ];
        $alreadySend = [
            'number'    => 0,
            'list'      => [],
        ];

        $data['resources'] = array_slice($data['resources'], 0, 500);
217
218
219
220
221
222
223
224
225
226
227
228

        $resources = ResModel::get([
            'select' => ['res_id', 'locker_user_id', 'locker_time'],
            'where'  => ['res_id in (?)'],
            'data'   => [$data['resources']]
        ]);

        $resourcesForProcess = [];
        foreach ($resources as $resource) {
            $lock = true;
            if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
                $lock = false;
229
            } elseif ($resource['locker_user_id'] == $GLOBALS['id']) {
230
231
232
233
234
235
236
237
238
239
                $lock = false;
            } elseif (strtotime($resource['locker_time']) < time()) {
                $lock = false;
            }
            if (!$lock) {
                $resourcesForProcess[] = $resource['res_id'];
            }
        }
        $data['resources'] = $resourcesForProcess;

240
241
        $currentUser = UserModel::getById(['id' => $GLOBALS['id'], 'select' => ['mail']]);
        $emailSenders = [];
Damien's avatar
Damien committed
242
        foreach ($data['resources'] as $resId) {
243
            $resource = ResModel::getById(['select' => ['res_id', 'category_id', 'alt_identifier', 'type_id', 'destination'], 'resId' => $resId]);
Damien's avatar
Damien committed
244

245
            if (empty($resource)) {
Damien's avatar
Damien committed
246
                $noSendAR['number'] += 1;
247
                $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => '', 'info' => _DOCUMENT_NOT_FOUND ];
Damien's avatar
Damien committed
248
249
250
                continue;
            }

251
            if (!ResController::hasRightByResId(['resId' => [$resId], 'userId' => $GLOBALS['id']])) {
Damien's avatar
Damien committed
252
                $noSendAR['number'] += 1;
253
                $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _DOCUMENT_OUT_PERIMETER ];
Damien's avatar
Damien committed
254
255
256
                continue;
            }

257
            if ($resource['category_id'] != 'incoming') {
Damien's avatar
Damien committed
258
                $noSendAR['number'] += 1;
259
                $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NOT_INCOMING_CATEGORY ];
Damien's avatar
Damien committed
260
261
262
                continue;
            }

263
            $doctype = DoctypeModel::getById(['id' => $resource['type_id'], 'select' => ['process_mode']]);
Damien's avatar
Damien committed
264

265
            if (empty($resource['destination']) && $currentMode == 'auto') {
Damien's avatar
Damien committed
266
                $noSendAR['number'] += 1;
267
                $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NO_ENTITY];
Damien's avatar
Damien committed
268
269
270
271
272
273
274
275
276
277
                continue;
            }

            if ($doctype['process_mode'] == 'SVA') {
                $templateAttachmentType = 'sva';
            } elseif ($doctype['process_mode'] == 'SVR') {
                $templateAttachmentType = 'svr';
            } else {
                $templateAttachmentType = 'simple';
            }
278
279
280
281
282
283
284
285

            $entity   = EntityModel::getByEntityId(['select' => ['id', 'entity_label', 'email'], 'entityId' => $resource['destination']]);
            $template = TemplateModel::getWithAssociation([
                'select'    => ['template_content', 'template_path', 'template_file_name', 'options'],
                'where'     => ['template_target = ?', 'template_attachment_type = ?', 'value_field = ?'],
                'data'      => ['acknowledgementReceipt', $templateAttachmentType, $resource['destination']]
            ]);
            $acknowledgementOptions = !empty($template[0]) ? json_decode($template[0]['options'], true) : null;
286
287
288
289
290
291
292
293
294
            if ($currentMode == 'auto') {
                if (empty($template[0])) {
                    $noSendAR['number'] += 1;
                    $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NO_TEMPLATE . ' \'' . $templateAttachmentType . '\' ' . _FOR_ENTITY . ' ' .$entity['entity_label'] ];
                    continue;
                }
    
                $docserver = DocserverModel::getByDocserverId(['docserverId' => 'TEMPLATES', 'select' => ['path_template']]);
                $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $template[0]['template_path']) . $template[0]['template_file_name'];
Damien's avatar
Damien committed
295
296
297
298
299
300
301
302
303
304
            }

            //Verify sending
            $acknowledgements = AcknowledgementReceiptModel::get([
                'select'    => ['res_id', 'type', 'format', 'creation_date', 'send_date'],
                'where'     => ['res_id = ?', 'type = ?'],
                'data'      => [$resId, $templateAttachmentType],
            ]);

            if (!empty($acknowledgements)) {
305
                $sent = 0;
Damien's avatar
Damien committed
306
307
308
309
                $generated = 0;

                foreach ($acknowledgements as $acknowledgement) {
                    if (!empty($acknowledgement['creation_date']) && !empty($acknowledgement['send_date'])) {
310
                        $sent += 1;
Damien's avatar
Damien committed
311
312
313
314
315
                    } elseif (!empty($acknowledgement['creation_date']) && empty($acknowledgement['send_date'])) {
                        $generated += 1;
                    }
                }

316
317
                if ($sent > 0) {
                    $alreadySend['number'] += $sent;
318
                    $alreadySend['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier']];
Damien's avatar
Damien committed
319
320
321
322
                }

                if ($generated > 0) {
                    $alreadyGenerated['number'] += $generated;
323
                    $alreadyGenerated['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier']];
Damien's avatar
Damien committed
324
325
326
327
                }
            }

            //Verify associated contact
328
329
330
331
332
333
            $contactsToProcess = ResourceContactModel::get([
                'select' => ['item_id'],
                'where' => ['res_id = ?', 'type = ?', 'mode = ?'],
                'data' => [$resId, 'contact', 'sender']
            ]);
            $contactsToProcess = array_column($contactsToProcess, 'item_id');
Damien's avatar
Damien committed
334
335
336
337
338
339
340

            //Verify contact informations
            $email = 0;
            $paper = 0;
            foreach ($contactsToProcess as $contactToProcess) {
                if (empty($contactToProcess)) {
                    $noSendAR['number'] += 1;
341
                    $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NO_CONTACT ];
Damien's avatar
Damien committed
342
343
344
                    continue 2;
                }

345
                $contact = ContactModel::getById(['select' => ['*'], 'id' => $contactToProcess]);
Damien's avatar
Damien committed
346

347
                if (empty($contact['email']) && (empty($contact['address_street']) || empty($contact['address_town']) || empty($contact['address_postcode']))) {
Damien's avatar
Damien committed
348
                    $noSendAR['number'] += 1;
349
                    $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _USER_MISSING_INFORMATIONS ];
Damien's avatar
Damien committed
350
351
352
353
                    continue 2;
                }

                if (!empty($contact['email'])) {
354
                    if (empty($template[0]['template_content']) && $currentMode == 'auto') {
Damien's avatar
Damien committed
355
                        $noSendAR['number'] += 1;
356
                        $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NO_EMAIL_TEMPLATE . ' \'' . $templateAttachmentType . '\' ' . _FOR_ENTITY . ' ' . $entity['entity_label'] ];
Damien's avatar
Damien committed
357
358
359
360
                        continue 2;
                    } else {
                        $email += 1;
                    }
361
                } elseif (!empty($contact['address_street']) && !empty($contact['address_town']) && !empty($contact['address_postcode'])) {
362
                    if ((!file_exists($pathToDocument) || !is_file($pathToDocument)) && $currentMode == 'auto') {
Damien's avatar
Damien committed
363
                        $noSendAR['number'] += 1;
364
                        $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NO_PAPER_TEMPLATE . ' \'' . $templateAttachmentType . '\' ' . _FOR_ENTITY . ' ' . $entity['entity_label'] ];
Damien's avatar
Damien committed
365
366
367
368
369
370
371
372
                        continue 2;
                    } else {
                        $paper += 1;
                    }
                }
            }

            if ($email > 0) {
373
374
375
376
377
378
379
380
381
382
383
384
385
386
                $emailSender = null;
                if (!empty($acknowledgementOptions)) {
                    if ($acknowledgementOptions['acknowledgementReceiptFrom'] == 'user') {
                        $emailSender = ['entityId' => null, 'email' => $currentUser['mail'], 'label' => UserModel::getLabelledUserById(['id' => $GLOBALS['id']])];
                    } elseif ($acknowledgementOptions['acknowledgementReceiptFrom'] == 'destination' && !empty($entity['email'])) {
                        $emailSender = ['entityId' => $entity['id'], 'email' => $entity['email'], 'label' => $entity['entity_label']];
                    } elseif ($acknowledgementOptions['acknowledgementReceiptFrom'] == 'mailServer') {
                        $configuration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_email_server', 'select' => ['value']]);
                        $configuration = json_decode($configuration['value'], true);
                        $emailSender = ['entityId' => null, 'email' => $configuration['from'], 'label' => ''];
                    } elseif ($acknowledgementOptions['acknowledgementReceiptFrom'] == 'manual') {
                        $emailSender = ['entityId' => null, 'email' => $acknowledgementOptions['acknowledgementReceiptFromMail'], 'label' => ''];
                    }
                }
387
                if (!empty($emailSender) || $currentMode == 'manual') {
388
389
390
391
392
393
394
                    $emailSenders[] = $emailSender;
                    $sendEmail += $email;
                } elseif (empty($emailSender) && $currentMode != 'manual') {
                    $noSendAR['number'] += 1;
                    $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NO_SENDER_EMAIL];
                    continue;
                }
Damien's avatar
Damien committed
395
396
397
398
399
400
            }
            if ($paper > 0) {
                $sendPaper += $paper;
            }
            if ($email > 0 || $paper > 0) {
                $sendList[] = $resId;
401
            } else {
402
403
                $noSendAR['number'] += 1;
                $noSendAR['list'][] = ['resId' => $resId, 'alt_identifier' => $resource['alt_identifier'], 'info' => _NO_SENDERS ];
Damien's avatar
Damien committed
404
405
406
            }
        }

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
        $emailSenders = array_values(array_unique($emailSenders, SORT_REGULAR));

        if ($currentMode == 'manual') {
            if (empty($entity['email']) || !PrivilegeController::hasPrivilege(['privilegeId' => 'use_mail_services', 'userId' => $GLOBALS['id']])) {
                $emailSenders = [['email' => $currentUser['mail']]];
            } else {
                $availableEmails = EmailController::getAvailableEmailsByUserId(['userId' => $GLOBALS['id']]);
                $entities = array_column($availableEmails, 'entityId');

                if (!in_array($entity['id'], $entities)) {
                    $emailSenders = [['email' => $currentUser['mail']]];
                } else {
                    $emailSenders = [['email' => $entity['email'], 'entityId' => $entity['id']]];
                }
            }
        }

        return $response->withJson([
            'sendEmail'        => $sendEmail,
            'sendPaper'        => $sendPaper,
            'sendList'         => $sendList,
            'noSendAR'         => $noSendAR,
            'alreadySend'      => $alreadySend,
            'alreadyGenerated' => $alreadyGenerated,
            'mode'             => $mode,
            'canAddCopies'     => !empty($parameters['canAddCopies']),
            'emailSenders'     => $emailSenders
        ]);
Damien's avatar
Damien committed
435
    }
Damien's avatar
Damien committed
436

437
438
    public function checkExternalSignatoryBook(Request $request, Response $response, array $aArgs)
    {
439
        $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
440
441
442
443
444
445
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $data = $request->getParsedBody();

Damien's avatar
Damien committed
446
        $data['resources'] = array_slice($data['resources'], 0, 500);
447
        if (!ResController::hasRightByResId(['resId' => $data['resources'], 'userId' => $GLOBALS['id']])) {
Damien's avatar
Damien committed
448
449
450
            return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']);
        }

451
        $data['resources'] = PreProcessActionController::getNonLockedResources(['resources' => $data['resources'], 'userId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
452

453
454
455
456
457
458
459
460
461
462
463
464
465
466
        $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'modules/visa/xml/remoteSignatoryBooks.xml']);

        $errors = [];
        $signatureBookEnabled = '';
        if (!empty($loadedXml)) {
            $config['id'] = (string)$loadedXml->signatoryBookEnabled;
            foreach ($loadedXml->signatoryBook as $value) {
                if ($value->id == $config['id']) {
                    $config['data'] = (array)$value;
                    break;
                }
            }

            $signatureBookEnabled = $config['id'];
467
468
            $additionalsInfos = [
                'attachments'   => [],
469
                'noAttachment'  => []
470
            ];
471
            if ($signatureBookEnabled == 'ixbus') {
472
473
                $additionalsInfos['ixbus'] = IxbusController::getInitializeDatas($config);
            }
474
            $availableResources = [];
475
            if (in_array($signatureBookEnabled, ['maarchParapheur', 'fastParapheur', 'iParapheur', 'ixbus'])) {
476
                if (is_array($data['resources']) && count($data['resources']) == 1) {
477
                    $resDestination = ResModel::getById([
478
                        'select'   => ['destination'],
479
480
                        'resId'    => $data['resources'][0]
                    ]);
Damien's avatar
Damien committed
481
482
483
484
                    if (!empty($resDestination['destination'])) {
                        $destination = EntityModel::getByEntityId(['entityId' => $resDestination['destination'], 'select' => ['id']]);
                        $additionalsInfos['destinationId'] = $destination['id'];
                    }
485
486
                } else {
                    $additionalsInfos['destinationId'] = '';
487
                }
488
                foreach ($data['resources'] as $resId) {
489
                    $noAttachmentsResource = ResModel::getById(['resId' => $resId, 'select' => ['alt_identifier']]);
490
491
492
493
494
                    if (empty($noAttachmentsResource['alt_identifier'])) {
                        $noAttachmentsResource['alt_identifier'] = _UNDEFINED;
                    }

                    // Check attachments
495
496
497
                    $attachmentTypes = AttachmentTypeModel::get(['select' => ['type_id'], 'where' => ['signable = ?', 'type_id != ?'], 'data' => ['true', 'signed_response']]);
                    $attachmentTypes = array_column($attachmentTypes, 'type_id');

498
499
500
501
502
503
504
505
506
507
508
509
                    $attachments = [];
                    if (!empty($attachmentTypes)) {
                        $attachments = AttachmentModel::get([
                            'select'    => [
                                'res_id', 'title', 'identifier', 'attachment_type',
                                'status', 'typist', 'docserver_id', 'path', 'filename', 'creation_date',
                                'validation_date', 'relation', 'origin_id'
                            ],
                            'where'     => ["res_id_master = ?", "attachment_type in (?)", "status not in ('DEL', 'OBS', 'FRZ', 'TMP', 'SIGN')", "in_signature_book = 'true'"],
                            'data'      => [$resId, $attachmentTypes]
                        ]);
                    }
510

511
                    $integratedResource = ResModel::get([
512
                        'select' => ['subject', 'alt_identifier'],
513
                        'where'  => ['integrations->>\'inSignatureBook\' = \'true\'', 'external_id->>\'signatureBookId\' is null', 'res_id = ?'],
514
515
                        'data'   => [$resId]
                    ]);
516
517
518
519
520
521
                    $mainDocumentSigned = AdrModel::getConvertedDocumentById([
                        'select' => [1],
                        'resId'  => $resId,
                        'collId' => 'letterbox_coll',
                        'type'   => 'SIGN'
                    ]);
522
523
524
                    if (!empty($mainDocumentSigned)) {
                        $integratedResource = false;
                    }
525
526

                    if (empty($attachments) && empty($integratedResource)) {
527
                        $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'noAttachmentInSignatoryBook'];
528
                    } else {
529
                        foreach ($attachments as $value) {
530
531
                            $resIdAttachment  = $value['res_id'];
                            $collId = 'attachments_coll';
532
                            
533
                            $adrInfo = ConvertPdfController::getConvertedPdfById(['resId' => $resIdAttachment, 'collId' => $collId]);
534
                            if (empty($adrInfo['docserver_id'])) {
535
536
537
538
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'noAttachmentConversion'];
                                break;
                            }
                            $docserverInfo = DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id']]);
539
                            if (empty($docserverInfo['path_template'])) {
540
541
542
543
544
545
546
547
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'docserverDoesNotExists'];
                                break;
                            }
                            $filePath = $docserverInfo['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
                            if (!is_file($filePath)) {
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'fileDoesNotExists'];
                                break;
                            }
548
                            $availableResources[] = ['resId' => $resIdAttachment, 'subject' => $value['title'], 'chrono' => $value['identifier'], 'mainDocument' => false];
549
                        }
550
551
                        if (!empty($integratedResource)) {
                            $adrInfo = ConvertPdfController::getConvertedPdfById(['resId' => $resId, 'collId' => 'letterbox_coll']);
552
                            if (empty($adrInfo['docserver_id']) || strtolower(pathinfo($adrInfo['filename'], PATHINFO_EXTENSION)) != 'pdf') {
553
554
555
556
557
558
559
560
561
562
563
564
565
566
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'noMailConversion'];
                                break;
                            }
                            $docserverInfo = DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id']]);
                            if (empty($docserverInfo['path_template'])) {
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'docserverDoesNotExists'];
                                break;
                            }
                            $filePath = $docserverInfo['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
                            if (!is_file($filePath)) {
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'fileDoesNotExists'];
                                break;
                            }
                        }
567
                        if (empty($attachments) && empty($integratedResource)) {
568
569
                            $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'noSignableAttachmentInSignatoryBook'];
                        } else {
570
571
572
573
                            $statuses = array_column($attachments, 'status');
                            $mailing = in_array('SEND_MASS', $statuses);

                            $additionalsInfos['attachments'][] = ['res_id' => $resId, 'alt_identifier' => $noAttachmentsResource['alt_identifier'], 'mailing' => $mailing];
574
                        }
575
576
577
                    }
                }
            } elseif ($signatureBookEnabled == 'xParaph') {
578
                $userInfos  = UserModel::getById(['id' => $GLOBALS['id'], 'select' => ['external_id']]);
579
                $externalId = json_decode($userInfos['external_id'], true);
580
581
582
583
                $additionalsInfos['accounts'] = [];
                if (!empty($externalId['xParaph'])) {
                    $additionalsInfos['accounts'] = $externalId['xParaph'];
                }
584
585

                foreach ($data['resources'] as $resId) {
586
                    $noAttachmentsResource = ResModel::getById(['resId' => $resId, 'select' => ['alt_identifier']]);
587
588
589
590
591
                    if (empty($noAttachmentsResource['alt_identifier'])) {
                        $noAttachmentsResource['alt_identifier'] = _UNDEFINED;
                    }

                    // Check attachments
592
                    $attachments = AttachmentModel::get([
593
                        'select'    => [
594
                            'res_id', 'title', 'identifier', 'attachment_type',
595
                            'status', 'typist', 'docserver_id', 'path', 'filename', 'creation_date',
596
                            'validation_date', 'relation', 'origin_id'
597
                        ],
598
                        'where'     => ["res_id_master = ?", "attachment_type not in (?)", "status not in ('DEL', 'OBS', 'FRZ', 'TMP')", "in_signature_book = 'true'"],
599
                        'data'      => [$resId, ['signed_response']]
600
601
602
603
604
605
                    ]);
                    
                    if (empty($attachments)) {
                        $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'noAttachmentInSignatoryBook'];
                    } else {
                        foreach ($attachments as $value) {
606
607
                            $resIdAttachment = $value['res_id'];
                            $collId          = 'attachments_coll';
608
                            
609
                            $adrInfo = ConvertPdfController::getConvertedPdfById(['resId' => $resIdAttachment, 'collId' => $collId]);
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
                            if (empty($adrInfo['docserver_id'])) {
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'noAttachmentConversion'];
                                break;
                            }
                            $docserverInfo = DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id']]);
                            if (empty($docserverInfo['path_template'])) {
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'docserverDoesNotExists'];
                                break;
                            }
                            $filePath = $docserverInfo['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
                            if (!is_file($filePath)) {
                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'fileDoesNotExists'];
                                break;
                            }
                        }
625
626
627
628
                        $statuses = array_column($attachments, 'status');
                        $mailing = in_array('SEND_MASS', $statuses);

                        $additionalsInfos['attachments'][] = ['res_id' => $resId, 'alt_identifier' => $noAttachmentsResource['alt_identifier'], 'mailing' => $mailing];
629
630
                    }
                }
631
632
633
            }
        }

634
635
636
637
638
639
640
        $minimumVisaRole = ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'minimumVisaRole']);
        $maximumSignRole = ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'maximumSignRole']);

        $minimumVisaRole = !empty($minimumVisaRole['param_value_int']) ? $minimumVisaRole['param_value_int'] : 0;
        $maximumSignRole = !empty($maximumSignRole['param_value_int']) ? $maximumSignRole['param_value_int'] : 0;

        return $response->withJson([
641
642
643
644
645
646
            'signatureBookEnabled'  => $signatureBookEnabled,
            'additionalsInfos'      => $additionalsInfos,
            'errors'                => $errors,
            'minimumVisaRole'       => $minimumVisaRole,
            'maximumSignRole'       => $maximumSignRole,
            'availableResources'    => $availableResources
647
        ]);
648
649
    }

650
651
    public function checkExternalNoteBook(Request $request, Response $response, array $aArgs)
    {
652
        $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
653
654
655
656
657
658
659
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $data = $request->getParsedBody();

        $data['resources'] = array_slice($data['resources'], 0, 500);
660
        if (!ResController::hasRightByResId(['resId' => $data['resources'], 'userId' => $GLOBALS['id']])) {
661
662
663
            return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']);
        }

664
        $data['resources'] = PreProcessActionController::getNonLockedResources(['resources' => $data['resources'], 'userId' => $GLOBALS['id']]);
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

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

        $errors = [];
        if (!empty($loadedXml)) {
            $config['id'] = 'maarchParapheur';
            foreach ($loadedXml->signatoryBook as $value) {
                if ($value->id == $config['id']) {
                    $config['data'] = (array)$value;
                    break;
                }
            }

            $additionalsInfos = [
                'mails'  => [],
                'noMail' => []
            ];

            $userList = MaarchParapheurController::getInitializeDatas(['config' => $config]);
            if (!empty($userList['users'])) {
                $additionalsInfos['users'] = $userList['users'];
            } else {
                $additionalsInfos['users'] = [];
            }
            if (!empty($userList['errors'])) {
                $errors[] = $userList['errors'];
            }

            foreach ($data['resources'] as $resId) {
694
                $noAttachmentsResource = ResModel::getById(['resId' => $resId, 'select' => ['alt_identifier', 'filename', 'external_id->>\'signatureBookId\' as signaturebookid']]);
695
696
697
698
                if (empty($noAttachmentsResource['alt_identifier'])) {
                    $noAttachmentsResource['alt_identifier'] = _UNDEFINED;
                }

699
                if (empty($noAttachmentsResource['filename'])) {
700
                    $additionalsInfos['noMail'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'noDocumentToSend'];
701
702
                    continue;
                }
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
                $adrMainInfo = ConvertPdfController::getConvertedPdfById(['resId' => $resId, 'collId' => 'letterbox_coll']);
                if (empty($adrMainInfo['docserver_id'])) {
                    $additionalsInfos['noMail'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'noMailConversion'];
                    continue;
                }
                $docserverMainInfo = DocserverModel::getByDocserverId(['docserverId' => $adrMainInfo['docserver_id']]);
                if (empty($docserverMainInfo['path_template'])) {
                    $additionalsInfos['noMail'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'docserverDoesNotExists'];
                    continue;
                }
                $filePath = $docserverMainInfo['path_template'] . str_replace('#', '/', $adrMainInfo['path']) . $adrMainInfo['filename'];
                if (!is_file($filePath)) {
                    $additionalsInfos['noMail'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'fileDoesNotExists'];
                    continue;
                }
718
                if (!empty($noAttachmentsResource['signaturebookid'])) {
719
                    $additionalsInfos['noMail'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'fileAlreadySentToSignatureBook'];
720
721
                    continue;
                }
722
723
724
725
726
727
728
                $additionalsInfos['mails'][] = ['res_id' => $resId];
            }
        }

        return $response->withJson(['additionalsInfos' => $additionalsInfos, 'errors' => $errors]);
    }

Damien's avatar
Damien committed
729
    public function checkShippings(Request $request, Response $response)
730
    {
731
732
        $mailevaConfig = CoreConfigModel::getMailevaConfiguration();
        if (empty($mailevaConfig)) {
733
            return $response->withJson(['fatalError' => 'Maileva configuration does not exist', 'reason' => 'missingMailevaConfig']);
734
        } elseif (!$mailevaConfig['enabled']) {
735
            return $response->withJson(['fatalError' => 'Maileva configuration is disabled', 'reason' => 'disabledMailevaConfig']);
736
        }
737
738
739
740

        $data = $request->getParsedBody();

        if (!Validator::arrayType()->notEmpty()->validate($data['resources'])) {
Damien's avatar
Damien committed
741
            return $response->withStatus(400)->withJson(['errors' => 'Body resources is empty or not an array']);
742
743
744
        }

        $data['resources'] = array_slice($data['resources'], 0, 500);
745
        if (!ResController::hasRightByResId(['resId' => $data['resources'], 'userId' => $GLOBALS['id']])) {
Damien's avatar
Damien committed
746
            return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']);
747
748
        }

749
        $data['resources'] = PreProcessActionController::getNonLockedResources(['resources' => $data['resources'], 'userId' => $GLOBALS['id']]);
750

751
        $aDestination = ResModel::get([
752
            'select' => ['distinct(destination)'],
753
754
755
756
            'where'  => ['res_id in (?)'],
            'data'   => [$data['resources']]
        ]);

757
758
759
760
761
        $aTemplates = [];
        $entities   = [];
        $resources  = [];
        $canNotSend = [];

762
        foreach ($aDestination as $values) {
763
764
765
            if (!empty($values['destination'])) {
                $entities[] = $values['destination'];
            }
766
767
        }

Damien's avatar
Damien committed
768
        $entitiesInfos = [];
769
        if (!empty($entities)) {
Alex ORLUC's avatar
Alex ORLUC committed
770
            $aEntities = EntityModel::get(['select' => ['id', 'entity_label'], 'where' => ['entity_id in (?)'], 'data' => [$entities]]);
771
772
773

            $entitiesId = [];
            foreach ($aEntities as $value) {
774
                $entitiesId[] = (string)$value['id'];
775
                $entitiesInfos[] = $value['entity_label'];
776
777
778
779
780
781
            }

            $aTemplates = ShippingTemplateModel::getByEntities([
                'select'   => ['id', 'label', 'description', 'options', 'fee'],
                'entities' => $entitiesId
            ]);
782
783

            $hasRegisteredMail = false;
784
785
786
            foreach ($aTemplates as $key => $value) {
                $aTemplates[$key]['options']  = json_decode($value['options'], true);
                $aTemplates[$key]['fee']      = json_decode($value['fee'], true);
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
                if (strpos($aTemplates[$key]['options']['sendMode'], 'digital_registered_mail') !== false) {
                    $hasRegisteredMail = true;
                }
            }
        }
        $invalidEntityAddress = false;
        if (!empty($hasRegisteredMail)) {
            $addressEntity = UserModel::getPrimaryEntityById([
                'id'        => $GLOBALS['id'],
                'select'    => [
                    'entities.entity_id', 'entities.short_label', 'entities.address_number', 'entities.address_street', 'entities.address_additional1', 'entities.address_additional2', 'entities.address_postcode', 'entities.address_town', 'entities.address_country'
                ]
            ]);
            $entityRoot = EntityModel::getEntityRootById(['entityId' => $addressEntity['entity_id']]);
            $addressEntity = ContactController::getContactAfnor([
                'company'               => $entityRoot['entity_label'],
                'civility'              => '',
                'firstname'             => $addressEntity['short_label'],
                'lastname'              => '',
                'address_number'        => $addressEntity['address_number'],
                'address_street'        => $addressEntity['address_street'],
                'address_additional1'   => $addressEntity['address_additional1'],
                'address_additional2'   => $addressEntity['address_additional2'],
                'address_postcode'      => $addressEntity['address_postcode'],
                'address_town'          => $addressEntity['address_town'],
                'address_country'       => $addressEntity['address_country']
            ]);
            if ((empty($addressEntity[1]) && empty($addressEntity[2])) || empty($addressEntity[6]) || !preg_match("/^\d{5}\s/", $addressEntity[6])) {
                $invalidEntityAddress = true;
816
817
818
            }
        }

819
        if (!empty($aTemplates)) {
820
            $aAttachments = AttachmentModel::get([
821
                'select'    => ['max(relation) as relation', 'res_id_master', 'title', 'res_id', 'identifier as chrono', 'recipient_id', 'recipient_type'],
822
823
                'where'     => ['res_id_master in (?)', 'status not in (?)', 'in_send_attach = ?'],
                'data'      => [$data['resources'], ['OBS', 'DEL', 'TMP', 'FRZ'], true],
824
                'groupBy'   => ['res_id_master', 'title', 'res_id', 'chrono', 'recipient_id', 'recipient_type']
825
826
            ]);

827
828
829
            $resourcesInfo   = ResModel::get(['select' => ['alt_identifier', 'res_id'], 'where' => ['res_id in (?)'], 'data' => [$data['resources']]]);
            $resourcesChrono = array_column($resourcesInfo, 'alt_identifier', 'res_id');

830
            foreach ($data['resources'] as $valueResId) {
831
                $documentToSend = false;
832
833
                foreach ($aAttachments as $key => $attachment) {
                    if ($attachment['res_id_master'] == $valueResId) {
834
                        $documentToSend = true;
835
                        $attachmentId = $attachment['res_id'];
836
                        $convertedDocument = ConvertPdfController::getConvertedPdfById([
Damien's avatar
Damien committed
837
                            'resId'     => $attachmentId,
838
                            'collId'    => 'attachments_coll'
Damien's avatar
Damien committed
839
                        ]);
840
                        if (empty($convertedDocument['docserver_id']) || strtolower(pathinfo($convertedDocument['filename'], PATHINFO_EXTENSION)) != 'pdf') {
841
                            $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resourcesChrono[$valueResId], 'reason' => 'noAttachmentConversion', 'attachmentIdentifier' => $attachment['chrono']];
Damien's avatar
Damien committed
842
843
844
                            unset($aAttachments[$key]);
                            break;
                        }
845
846
847
848
849
850
851
852
853
854
                        $docserver = DocserverModel::getByDocserverId(['docserverId' => $convertedDocument['docserver_id'], 'select' => ['path_template', 'docserver_type_id']]);
                        $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $convertedDocument['path']) . $convertedDocument['filename'];
                        if (!is_file($pathToDocument)) {
                            $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resourcesChrono[$valueResId], 'reason' => 'noAttachmentConversion', 'attachmentIdentifier' => $attachment['chrono']];
                            unset($aAttachments[$key]);
                            break;
                        }
                        $docserverType = DocserverTypeModel::getById(['id' => $docserver['docserver_type_id'], 'select' => ['fingerprint_mode']]);
                        $fingerprint = StoreController::getFingerPrint(['filePath' => $pathToDocument, 'mode' => $docserverType['fingerprint_mode']]);
                        if ($convertedDocument['fingerprint'] != $fingerprint) {
855
                            $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resourcesChrono[$valueResId], 'reason' => 'fingerprintsDoNotMatch', 'attachmentIdentifier' => $attachment['chrono']];
856
857
858
                            unset($aAttachments[$key]);
                            break;
                        }
859
                        if (empty($attachment['recipient_id']) || $attachment['recipient_type'] != 'contact') {
860
                            $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resourcesChrono[$valueResId], 'reason' => 'noAttachmentContact', 'attachmentIdentifier' => $attachment['chrono']];
861
862
863
                            unset($aAttachments[$key]);
                            break;
                        }
864
865
                        $contact = ContactModel::getById(['select' => ['*'], 'id' => $attachment['recipient_id']]);
                        if (empty($contact)) {
866
                            $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resourcesChrono[$valueResId], 'reason' => 'noAttachmentContact', 'attachmentIdentifier' => $attachment['chrono']];
867
868
869
                            unset($aAttachments[$key]);
                            break;
                        }
870
                        if (!empty($contact['address_country']) && strtoupper(trim($contact['address_country'])) != 'FRANCE') {
871
                            $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resourcesChrono[$valueResId], 'reason' => 'noFranceContact', 'attachmentIdentifier' => $attachment['chrono']];
872
873
874
                            unset($aAttachments[$key]);
                            break;
                        }
875
                        $afnorAddress = ContactController::getContactAfnor($contact);
Damien's avatar
Damien committed
876
                        if ((empty($afnorAddress[1]) && empty($afnorAddress[2])) || empty($afnorAddress[6]) || !preg_match("/^\d{5}\s/", $afnorAddress[6])) {
877
                            $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resourcesChrono[$valueResId], 'reason' => 'incompleteAddressForPostal', 'attachmentIdentifier' => $attachment['chrono']];
878
879
880
881
                            unset($aAttachments[$key]);
                            break;
                        }

882
                        $attachment['type'] = 'attachment';
883
                        $resources[] = $attachment;
884
885
886
                        unset($aAttachments[$key]);
                    }
                }
887

888
                $resInfo = ResModel::getById(['select' => ['alt_identifier as chrono', 'integrations', 'res_id', 'subject as title', 'docserver_id'], 'resId' => $valueResId]);
889
                $integrations = json_decode($resInfo['integrations'], true);
890
                if (!empty($integrations['inShipping']) && empty($resInfo['docserver_id'])) {
891
                    $documentToSend = true;
892
893
894
                    $canNotSend[] = [
                        'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'noMailConversion'
                    ];
895
                } elseif (!empty($integrations['inShipping']) && !empty($resInfo['docserver_id'])) {
896
                    $documentToSend = true;
897
898
899

                    $convertedDocument = ConvertPdfController::getConvertedPdfById([
                        'resId'  => $valueResId,
900
                        'collId' => 'letterbox_coll'
901
                    ]);
902
                    if (empty($convertedDocument['docserver_id']) || strtolower(pathinfo($convertedDocument['filename'], PATHINFO_EXTENSION)) != 'pdf') {
903
                        $canNotSend[] = [
904
                            'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'noMailConversion'
905
906
                        ];
                    } else {
907
908
909
                        $docserver = DocserverModel::getByDocserverId(['docserverId' => $convertedDocument['docserver_id'], 'select' => ['path_template', 'docserver_type_id']]);
                        $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $convertedDocument['path']) . $convertedDocument['filename'];
                        if (!is_file($pathToDocument)) {
910
                            $canNotSend[] = [
911
                                'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'noMailConversion'
912
913
                            ];
                        } else {
914
915
916
917
                            $docserverType = DocserverTypeModel::getById(['id' => $docserver['docserver_type_id'], 'select' => ['fingerprint_mode']]);
                            $fingerprint = StoreController::getFingerPrint(['filePath' => $pathToDocument, 'mode' => $docserverType['fingerprint_mode']]);
                            if ($convertedDocument['fingerprint'] != $fingerprint) {
                                $canNotSend[] = [
918
                                    'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'fingerprintsDoNotMatch'
919
920
921
922
923
924
925
                                ];
                            } else {
                                $resourceContacts = ResourceContactModel::get([
                                    'where' => ['res_id = ?', 'mode = ?', 'type = ?'],
                                    'data'  => [$valueResId, 'recipient', 'contact']
                                ]);
                                if (empty($resourceContacts)) {
926
                                    $canNotSend[] = [
927
                                        'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'noMailContact'
928
929
                                    ];
                                } else {
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
                                    foreach ($resourceContacts as $resourceContact) {
                                        $contact = ContactModel::getById(['select' => ['*'], 'id' => $resourceContact['item_id']]);
                                        if (empty($contact)) {
                                            $canNotSend[] = [
                                                'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'noMailContact'
                                            ];
                                        } elseif (!empty($contact['address_country']) && strtoupper(trim($contact['address_country'])) != 'FRANCE') {
                                            $canNotSend[] = [
                                                'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'noFranceContact'
                                            ];
                                        } else {
                                            $afnorAddress = ContactController::getContactAfnor($contact);
                                            if ((empty($afnorAddress[1]) && empty($afnorAddress[2])) || empty($afnorAddress[6]) || !preg_match("/^\d{5}\s/", $afnorAddress[6])) {
                                                $canNotSend[] = [
                                                    'resId'  => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'incompleteAddressForPostal'
                                                ];
                                            }
                                        }
948
949
                                    }
                                }
950
951
                                $resInfo['type'] = 'mail';
                                $resources[] = $resInfo;
952
953
954
955
                            }
                        }
                    }
                }
956
                if (!$documentToSend) {
957
                    $canNotSend[] = ['resId' => $valueResId, 'chrono' => $resInfo['chrono'], 'reason' => 'noDocumentToSend'];
958
959
                }
            }
960
    
961
962
            foreach ($aTemplates as $key => $value) {
                if (!empty($resources)) {
963
                    $templateFee = ShippingTemplateController::calculShippingFee([
964
965
966
967
968
969
                        'fee'       => $value['fee'],
                        'resources' => $resources
                    ]);
                } else {
                    $templateFee = 0;
                }
970
                $aTemplates[$key]['fee'] = number_format($templateFee, 2, '.', '');
971
            }
972
973
974
        }

        return $response->withJson([
975
976
977
978
979
            'shippingTemplates'     => $aTemplates,
            'entities'              => $entitiesInfos,
            'resources'             => $resources,
            'canNotSend'            => $canNotSend,
            'invalidEntityAddress'  => $invalidEntityAddress
980
981
982
        ]);
    }

983
984
    public function checkInitiatorEntity(Request $request, Response $response, array $args)
    {
985
        $errors = ResourceListController::listControl(['groupId' => $args['groupId'], 'userId' => $args['userId'], 'basketId' => $args['basketId'], 'currentUserId' => $GLOBALS['id']]);
986
987
988
989
990
991
992
993
994
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $data = $request->getParsedBody();

        if (!Validator::arrayType()->notEmpty()->validate($data['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
        }
995
        $data['resources'] = PreProcessActionController::getNonLockedResources(['resources' => $data['resources'], 'userId' => $GLOBALS['id']]);
996
997
998
999
1000

        $withEntity = [];
        $withoutEntity = [];

        $resources = ResModel::get([