ResourceListController.php 69.2 KB
Newer Older
Damien's avatar
Damien committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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 Resource List Controller
* @author dev@maarch.org
*/

namespace Resource\controllers;

17
use Action\controllers\ActionController;
Damien's avatar
Damien committed
18
use Action\controllers\ActionMethodController;
Damien's avatar
Damien committed
19
use Action\models\ActionModel;
20
use Attachment\models\AttachmentModel;
Damien's avatar
Damien committed
21
use Basket\models\ActionGroupBasketModel;
Damien's avatar
Damien committed
22
23
24
use Basket\models\BasketModel;
use Basket\models\GroupBasketModel;
use Basket\models\RedirectBasketModel;
25
use Contact\controllers\ContactController;
26
use Convert\models\AdrModel;
27
use CustomField\models\CustomFieldModel;
28
29
use Docserver\models\DocserverModel;
use Docserver\models\DocserverTypeModel;
30
use Entity\models\EntityModel;
Damien's avatar
Damien committed
31
use Entity\models\ListInstanceModel;
32
use Folder\models\FolderModel;
Damien's avatar
Damien committed
33
use Group\models\GroupModel;
34
use Note\models\NoteModel;
Damien's avatar
Damien committed
35
use Priority\models\PriorityModel;
36
37
use RegisteredMail\models\IssuingSiteModel;
use RegisteredMail\models\RegisteredMailModel;
Damien's avatar
Damien committed
38
use Resource\models\ResModel;
39
use Resource\models\ResourceListModel;
40
use Resource\models\UserFollowedResourceModel;
Damien's avatar
Damien committed
41
use Respect\Validation\Validator;
Damien's avatar
Damien committed
42
43
44
use Slim\Http\Request;
use Slim\Http\Response;
use SrcCore\controllers\PreparedClauseController;
Damien's avatar
Damien committed
45
use SrcCore\models\TextFormatModel;
Damien's avatar
Damien committed
46
use SrcCore\models\ValidatorModel;
Damien's avatar
Damien committed
47
use Status\models\StatusModel;
Damien's avatar
Damien committed
48
49
50
51
52
53
use User\models\UserModel;

class ResourceListController
{
    public function get(Request $request, Response $response, array $aArgs)
    {
54
        $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
55
56
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
Damien's avatar
Damien committed
57
58
        }

Damien's avatar
Damien committed
59
        $basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause', 'basket_res_order', 'basket_name', 'basket_id']]);
Damien's avatar
Damien committed
60
        $user = UserModel::getById(['id' => $aArgs['userId'], 'select' => ['user_id']]);
Damien's avatar
Damien committed
61
        $group = GroupModel::getById(['id' => $aArgs['groupId'], 'select' => ['group_id']]);
Damien's avatar
Damien committed
62

63
        $data = $request->getQueryParams();
Damien's avatar
Damien committed
64
65
        $data['offset'] = (empty($data['offset']) || !is_numeric($data['offset']) ? 0 : (int)$data['offset']);
        $data['limit'] = (empty($data['limit']) || !is_numeric($data['limit']) ? 10 : (int)$data['limit']);
66

Damien's avatar
Damien committed
67
68
69
        $allQueryData = ResourceListController::getResourcesListQueryData(['data' => $data, 'basketClause' => $basket['basket_clause'], 'login' => $user['user_id']]);
        if (!empty($allQueryData['order'])) {
            $data['order'] = $allQueryData['order'];
Damien's avatar
Damien committed
70
        }
71

Damien's avatar
Damien committed
72
        $rawResources = ResourceListModel::getOnView([
Damien's avatar
Damien committed
73
            'select'    => ['res_id'],
Damien's avatar
Damien committed
74
75
76
77
            'table'     => $allQueryData['table'],
            'leftJoin'  => $allQueryData['leftJoin'],
            'where'     => $allQueryData['where'],
            'data'      => $allQueryData['queryData'],
Damien's avatar
Damien committed
78
            'orderBy'   => empty($data['order']) ? [$basket['basket_res_order']] : [$data['order']]
Damien's avatar
Damien committed
79
        ]);
Damien's avatar
Damien committed
80
81
        $count = count($rawResources);

82
83
        $resIds = ResourceListController::getIdsWithOffsetAndLimit(['resources' => $rawResources, 'offset' => $data['offset'], 'limit' => $data['limit']]);

84
        $followedDocuments = UserFollowedResourceModel::get([
85
86
87
            'select'    => ['res_id'],
            'where'     => ['user_id = ?'],
            'data'      => [$GLOBALS['id']],
88
89
90
91
        ]);

        $trackedMails = array_column($followedDocuments, 'res_id');
        $allResources = array_column($rawResources, 'res_id');
Damien's avatar
Damien committed
92

Damien's avatar
Damien committed
93
        $formattedResources = [];
94
95
96
        $defaultAction      = [];
        $displayFolderTags  = false;
        $templateColumns    = 0;
97
        if (!empty($resIds)) {
98
            $excludeAttachmentTypes = ['signed_response', 'summary_sheet'];
99
            $attachments = AttachmentModel::get([
100
                'select'    => ['COUNT(res_id)', 'res_id_master'],
Damien's avatar
Damien committed
101
                'where'     => ['res_id_master in (?)', 'status not in (?)', 'attachment_type not in (?)', '((status = ? AND typist = ?) OR status != ?)'],
Damien's avatar
Damien committed
102
                'data'      => [$resIds, ['DEL', 'OBS'], $excludeAttachmentTypes, 'TMP', $GLOBALS['id'], 'TMP'],
103
104
                'groupBy'   => ['res_id_master']
            ]);
105

106
107
            $groupBasket     = GroupBasketModel::get(['select' => ['list_display', 'list_event', 'list_event_data'], 'where' => ['basket_id = ?', 'group_id = ?'], 'data' => [$basket['basket_id'], $group['group_id']]]);
            $listDisplay     = json_decode($groupBasket[0]['list_display'], true);
108
            $templateColumns = $listDisplay['templateColumns'];
109
110
111
            $listDisplay     = $listDisplay['subInfos'];

            $selectData = ResourceListController::getSelectData(['listDisplay' => $listDisplay]);
Damien's avatar
Damien committed
112
113
114
115
116
117
118
119

            $order = 'CASE res_letterbox.res_id ';
            foreach ($resIds as $key => $resId) {
                $order .= "WHEN {$resId} THEN {$key} ";
            }
            $order .= 'END';

            $resources = ResourceListModel::getOnResource([
120
121
122
                'select'    => $selectData['select'],
                'table'     => $selectData['tableFunction'],
                'leftJoin'  => $selectData['leftJoinFunction'],
Damien's avatar
Damien committed
123
124
                'where'     => ['res_letterbox.res_id in (?)'],
                'data'      => [$resIds],
Damien's avatar
Damien committed
125
                'orderBy'   => [$order]
Damien's avatar
Damien committed
126
            ]);
Damien's avatar
Damien committed
127

128
129
130
131
132
            $formattedResources = ResourceListController::getFormattedResources([
                'resources'     => $resources,
                'userId'        => $GLOBALS['id'],
                'attachments'   => $attachments,
                'checkLocked'   => true,
133
134
                'listDisplay'   => $listDisplay,
                'trackedMails'  => $trackedMails
135
            ]);
136

137
            $defaultAction['component'] = $groupBasket[0]['list_event'];
138
            $defaultAction['data'] = json_decode($groupBasket[0]['list_event_data'], true);
139
140
141
142

            if (in_array('getFolders', array_column($listDisplay, 'value'))) {
                $displayFolderTags = true;
            }
Damien's avatar
Damien committed
143
        }
Damien's avatar
Damien committed
144

145
146
147
148
149
150
151
152
153
154
        return $response->withJson([
            'resources'         => $formattedResources,
            'count'             => $count,
            'basketLabel'       => $basket['basket_name'],
            'basket_id'         => $basket['basket_id'],
            'allResources'      => $allResources,
            'defaultAction'     => $defaultAction,
            'displayFolderTags' => $displayFolderTags,
            'templateColumns'   => $templateColumns
        ]);
Damien's avatar
Damien committed
155
156
    }

157
158
159
160
161
162
    public static function getSelectData(array $args)
    {
        $select = [
            'res_letterbox.res_id', 'res_letterbox.subject', 'res_letterbox.barcode', 'res_letterbox.alt_identifier',
            'status.label_status AS "status.label_status"', 'status.img_filename AS "status.img_filename"', 'priorities.color AS "priorities.color"',
            'res_letterbox.closing_date', 'res_letterbox.locker_user_id', 'res_letterbox.locker_time', 'res_letterbox.confidentiality',
163
            'res_letterbox.filename as res_filename', 'res_letterbox.integrations', 'res_letterbox.retention_frozen', 'res_letterbox.binding'
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
        ];
        $tableFunction    = ['status', 'priorities'];
        $leftJoinFunction = ['res_letterbox.status = status.id', 'res_letterbox.priority = priorities.id'];
        foreach ($args['listDisplay'] as $value) {
            $value = (array)$value;
            if ($value['value'] == 'getPriority') {
                $select[] = 'priorities.label AS "priorities.label"';
            } elseif ($value['value'] == 'getCategory') {
                $select[] = 'res_letterbox.category_id';
            } elseif ($value['value'] == 'getDoctype') {
                $select[] = 'doctypes.description AS "doctypes.description"';
                $tableFunction[] = 'doctypes';
                $leftJoinFunction[] = 'res_letterbox.type_id = doctypes.type_id';
            } elseif ($value['value'] == 'getCreationAndProcessLimitDates') {
                $select[] = 'res_letterbox.creation_date';
                $select[] = 'res_letterbox.process_limit_date';
            } elseif ($value['value'] == 'getModificationDate') {
                $select[] = 'res_letterbox.modification_date';
            } elseif ($value['value'] == 'getOpinionLimitDate') {
                $select[] = 'res_letterbox.opinion_limit_date';
            } elseif (strpos($value['value'], 'indexingCustomField_') !== false && !in_array('res_letterbox.custom_fields', $select)) {
                $select[] = 'res_letterbox.custom_fields';
            }
        }

        return ['select' => $select, 'tableFunction' => $tableFunction, 'leftJoinFunction' => $leftJoinFunction];
    }

Damien's avatar
Damien committed
192
    public function getFilters(Request $request, Response $response, array $aArgs)
Damien's avatar
Damien committed
193
    {
194
        $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
195
196
197
198
199
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause']]);
200
        $whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'userId' => $aArgs['userId']]);
Damien's avatar
Damien committed
201
202
        $where = [$whereClause];
        $queryData = [];
Damien's avatar
Damien committed
203

Damien's avatar
Damien committed
204
        $queryParams = $request->getQueryParams();
Damien's avatar
Damien committed
205

Damien's avatar
Damien committed
206
        $filters = ResourceListController::getFormattedFilters(['where' => $where, 'queryData' => $queryData, 'queryParams' => $queryParams]);
Damien's avatar
Damien committed
207

Damien's avatar
Damien committed
208
        return $response->withJson($filters);
Damien's avatar
Damien committed
209
210
    }

Damien's avatar
Damien committed
211
212
213
214
215
216
217
    public static function getResourcesListQueryData(array $args)
    {
        ValidatorModel::stringType($args, ['basketClause', 'login']);
        ValidatorModel::arrayType($args, ['data']);

        $table = [];
        $leftJoin = [];
218
219
        $where = [];
        if (!empty($args['basketClause'])) {
220
221
            $user = UserModel::getByLogin(['login' => $args['login'], 'select' => ['id']]);
            $whereClause = PreparedClauseController::getPreparedClause(['clause' => $args['basketClause'], 'userId' => $user['id']]);
222
223
            $where = [$whereClause];
        }
Damien's avatar
Damien committed
224
225
226
227
228
229
230
        $queryData = [];
        $order = null;

        if (!empty($args['data']['delayed']) && $args['data']['delayed'] == 'true') {
            $where[] = 'process_limit_date < CURRENT_TIMESTAMP';
        }
        if (!empty($args['data']['search']) && mb_strlen($args['data']['search']) >= 2) {
231
232
233
234
235
            if (preg_match('/^"([^"]+)"$/', $args['data']['search'], $cleanSearch)) {
                $where[] = '(alt_identifier like ? OR subject like ?)';
                $queryData[] = "{$cleanSearch[1]}";
                $queryData[] = "{$cleanSearch[1]}";
            } else {
236
237
238
                $where[] = "(replace(alt_identifier, ' ', '') ilike ? OR unaccent(subject) ilike unaccent(?::text))";
                $whiteStrippedChrono = str_replace(' ', '', $args['data']['search']);
                $queryData[] = "%{$whiteStrippedChrono}%";
239
240
                $queryData[] = "%{$args['data']['search']}%";
            }
Damien's avatar
Damien committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        }
        if (isset($args['data']['priorities'])) {
            if (empty($args['data']['priorities'])) {
                $where[] = 'priority is null';
            } else {
                $replace = preg_replace('/(^,)|(,$)/', '', $args['data']['priorities']);
                $replace = preg_replace('/(,,)/', ',', $replace);
                if ($replace != $args['data']['priorities']) {
                    $where[] = '(priority is null OR priority in (?))';
                } else {
                    $where[] = 'priority in (?)';
                }
                $queryData[] = explode(',', $replace);
            }
        }
        if (isset($args['data']['categories'])) {
            if (empty($args['data']['categories'])) {
                $where[] = 'category_id is null';
            } else {
                $replace = preg_replace('/(^,)|(,$)/', '', $args['data']['categories']);
                $replace = preg_replace('/(,,)/', ',', $replace);
                if ($replace != $args['data']['categories']) {
                    $where[] = '(category_id is null OR category_id in (?))';
                } else {
                    $where[] = 'category_id in (?)';
                }
                $queryData[] = explode(',', $replace);
            }
        }
        if (!empty($args['data']['statuses'])) {
            $where[] = 'status in (?)';
            $queryData[] = explode(',', $args['data']['statuses']);
        }
        if (isset($args['data']['entities'])) {
            if (empty($args['data']['entities'])) {
                $where[] = 'destination is null';
            } else {
                $replace = preg_replace('/(^,)|(,$)/', '', $args['data']['entities']);
                $replace = preg_replace('/(,,)/', ',', $replace);
                if ($replace != $args['data']['entities']) {
                    $where[] = '(destination is null OR destination in (?))';
                } else {
                    $where[] = 'destination in (?)';
                }
                $queryData[] = explode(',', $replace);
            }
        }
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        if (isset($args['data']['entitiesChildren'])) {
            if (empty($args['data']['entitiesChildren'])) {
                $where[] = 'destination is null';
            } else {
                $entities = explode(',', $args['data']['entitiesChildren']);
                $entitiesChildren = [];
                foreach ($entities as $entity) {
                    if (!empty($entity)) {
                        $children = EntityModel::getEntityChildren(['entityId' => $entity]);
                        $entitiesChildren = array_merge($entitiesChildren, $children);
                    }
                }
    
                $tmpWhere = [];
    
                $replace = preg_replace('/(^,)|(,$)/', '', $args['data']['entitiesChildren']);
                $replace = preg_replace('/(,,)/', ',', $replace);
                if ($replace != $args['data']['entitiesChildren']) {
                    $tmpWhere[] = 'destination is null';
                }
                if (!empty($entitiesChildren)) {
                    $tmpWhere[] = 'destination in (?)';
                    $queryData[] = $entitiesChildren;
                }
                if (!empty($tmpWhere)) {
                    $where[] = '(' . implode(' or ', $tmpWhere) . ')';
                }
Damien's avatar
Damien committed
315
316
            }
        }
317
318
319
320
321
322
        if (!empty($args['data']['doctypes'])) {
            $table[] = 'doctypes';
            $leftJoin[] = 'doctypes.description=res_view_letterbox.type_label';
            $where[] = 'doctypes.type_id in (?)';
            $queryData[] = explode(',', $args['data']['doctypes']);
        }
323
324
325
326
327
328
329
330
331
332
333
        if (!empty($args['data']['folders'])) {
            $resourcesInFolders = FolderModel::getWithResources([
                'select' => ['resources_folders.res_id'],
                'where'  => ['resources_folders.folder_id in (?)'],
                'data'   => [explode(',', $args['data']['folders'])]
            ]);
            $resourcesInFolders = array_column($resourcesInFolders, 'res_id');

            $where[] = 'res_id in (?)';
            $queryData[] = $resourcesInFolders;
        }
Damien's avatar
Damien committed
334
335
336
337

        if (!empty($args['data']['order']) && strpos($args['data']['order'], 'alt_identifier') !== false) {
            $order = 'order_alphanum(alt_identifier) ' . explode(' ', $args['data']['order'])[1];
        }
338
        if (!empty($args['data']['order']) && strpos($args['data']['order'], 'dest_user') !== false) {
339
            $order = '(us.lastname, us.firstname) ' . explode(' ', $args['data']['order'])[1];
340
341
            $table[] = '(SELECT firstname, lastname, id from users) AS us';
            $leftJoin[] = 'us.id = res_view_letterbox.dest_user';
342
        }
Damien's avatar
Damien committed
343
344
        if (!empty($args['data']['order']) && strpos($args['data']['order'], 'priority') !== false) {
            $order = 'priorities.order ' . explode(' ', $args['data']['order'])[1];
345
346
            $table[] = 'priorities';
            $leftJoin[] = 'res_view_letterbox.priority = priorities.id';
Damien's avatar
Damien committed
347
348
349
350
351
        }

        return ['table' => $table, 'leftJoin' => $leftJoin, 'where' => $where, 'queryData' => $queryData, 'order' => $order];
    }

352
    public function getActions(Request $request, Response $response, array $args)
Damien's avatar
Damien committed
353
    {
354
        $errors = ResourceListController::listControl(['groupId' => $args['groupId'], 'userId' => $args['userId'], 'basketId' => $args['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
355
356
357
358
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

359
360
361
362
363
364
365
366
367
368
        $basket = BasketModel::getById(['id' => $args['basketId'], 'select' => ['basket_clause', 'basket_res_order', 'basket_name', 'basket_id']]);
        $group = GroupModel::getById(['id' => $args['groupId'], 'select' => ['group_id']]);

        $queryParams = $request->getQueryParams();

        if (!empty($queryParams['resId'])) {
            $usedIn = 'used_in_action_page';
        } else {
            $usedIn = 'used_in_basketlist';
        }
Damien's avatar
Damien committed
369
370

        $rawActions = ActionGroupBasketModel::get([
371
372
            'select'    => ['id_action', 'default_action_list', 'where_clause'],
            'where'     => ['basket_id = ?', 'group_id = ?', "{$usedIn} = ?"],
373
            'data'      => [$basket['basket_id'], $group['group_id'], 'Y']
Damien's avatar
Damien committed
374
375
376
        ]);

        $actions = [];
377
        $actionsClauses = [];
378
        $defaultAction = 0;
Damien's avatar
Damien committed
379
        foreach ($rawActions as $rawAction) {
380
381
382
            if ($rawAction['default_action_list'] == 'Y') {
                $defaultAction = $rawAction['id_action'];
            }
Damien's avatar
Damien committed
383
            $actions[] = $rawAction['id_action'];
384
            $actionsClauses[$rawAction['id_action']] = $rawAction['where_clause'];
Damien's avatar
Damien committed
385
386
387
        }

        if (!empty($actions)) {
388
            $actions = ActionModel::get(['select' => ['id', 'label_action', 'component'], 'where' => ['id in (?)'], 'data' => [$actions], 'orderBy' => ["id = {$defaultAction} DESC",'label_action']]);
389
            foreach ($actions as $key => $action) {
390
391
                if (!empty($queryParams['resId'])) {
                    if (!empty($actionsClauses[$action['id']])) {
392
                        $whereClause = PreparedClauseController::getPreparedClause(['clause' => $actionsClauses[$action['id']], 'userId' => $GLOBALS['id']]);
393
394
395
396
397
398
399
400
                        $ressource = ResModel::getOnView(['select' => [1], 'where' => ['res_id = ?', $whereClause], 'data' => [$queryParams['resId']]]);
                        if (empty($ressource)) {
                            unset($actions[$key]);
                            continue;
                        }
                    }
                    $categoriesList = ActionModel::getCategoriesById(['id' => $action['id']]);
                    if (!empty($categoriesList)) {
401
                        $actions[$key]['categories'] = array_column($categoriesList, 'category_id');
402
403
                    } else {
                        $categories = ResModel::getCategories();
404
                        $actions[$key]['categories'] = array_column($categories, 'id');
405
406
                    }
                }
407
408
409
                $actions[$key]['label'] = $action['label_action'];
                unset($actions[$key]['label_action']);
            }
Damien's avatar
Damien committed
410
411
        }

412
        return $response->withJson(['actions' => array_values($actions)]);
Damien's avatar
Damien committed
413
414
    }

Damien's avatar
Damien committed
415
416
417
418
419
420
    public function setAction(Request $request, Response $response, array $aArgs)
    {
        $body = $request->getParsedBody();
        if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
        }
Damien's avatar
Damien committed
421
        $body['resources'] = array_unique($body['resources']);
Damien's avatar
Damien committed
422
423
        $body['resources'] = array_slice($body['resources'], 0, 500);

424
        $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
425
426
427
428
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

Damien's avatar
Damien committed
429
        $basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause', 'basket_id', 'basket_name']]);
Damien's avatar
Damien committed
430
431
432
433
434
435
436
437
438
439
        $group = GroupModel::getById(['id' => $aArgs['groupId'], 'select' => ['group_id']]);
        $actionGroupBasket = ActionGroupBasketModel::get([
            'select'    => [1],
            'where'     => ['basket_id = ?', 'group_id = ?', 'id_action = ?'],
            'data'      => [$basket['basket_id'], $group['group_id'], $aArgs['actionId']]
        ]);
        if (empty($actionGroupBasket)) {
            return $response->withStatus(400)->withJson(['errors' => 'Action is not linked to this group basket']);
        }

440
        $action = ActionModel::getById(['id' => $aArgs['actionId'], 'select' => ['component', 'parameters', 'label_action']]);
Damien's avatar
Damien committed
441
442
443
444
445
446
        if (empty($action['component'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Action component does not exist']);
        }
        if (!array_key_exists($action['component'], ActionMethodController::COMPONENTS_ACTIONS)) {
            return $response->withStatus(400)->withJson(['errors' => 'Action method does not exist']);
        }
447
        $action['parameters'] = json_decode($action['parameters'], true);
448
        $actionRequiredFields = $action['parameters']['requiredFields'] ?? [];
Damien's avatar
Damien committed
449

450
        $whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'userId' => $aArgs['userId']]);
Damien's avatar
Damien committed
451
452
453
454
455
        $resources = ResModel::getOnView([
            'select'    => ['res_id', 'locker_user_id', 'locker_time'],
            'where'     => [$whereClause, 'res_view_letterbox.res_id in (?)'],
            'data'      => [$body['resources']]
        ]);
456
457

        $resourcesInBasket = array_column($resources, 'res_id');
Damien's avatar
Damien committed
458

Damien's avatar
Damien committed
459
460
        if (!empty(array_diff($body['resources'], $resourcesInBasket))) {
            return $response->withStatus(403)->withJson(['errors' => 'Resources out of perimeter']);
Damien's avatar
Damien committed
461
462
        }

Damien's avatar
Damien committed
463
        $resourcesForAction = [];
464
465
466
467
        foreach ($resources as $resource) {
            $lock = true;
            if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
                $lock = false;
468
            } elseif ($resource['locker_user_id'] == $GLOBALS['id']) {
469
470
471
472
                $lock = false;
            } elseif (strtotime($resource['locker_time']) < time()) {
                $lock = false;
            }
Damien's avatar
Damien committed
473
474
            if (!$lock) {
                $resourcesForAction[] = $resource['res_id'];
475
476
477
            }
        }

Damien's avatar
Damien committed
478
479
        if (empty($resourcesForAction)) {
            return $response->withJson(['success' => 'No resource to process']);
Damien's avatar
Damien committed
480
481
        }

482
        $body['data'] = empty($body['data']) ? [] : $body['data'];
483
        $body['note'] = empty($body['note']) ? [] : $body['note'];
484

485
        $method          = ActionMethodController::COMPONENTS_ACTIONS[$action['component']];
Damien's avatar
Damien committed
486
        $methodResponses = [];
487
        foreach ($resourcesForAction as $key => $resId) {
488
            if (!empty($actionRequiredFields)) {
489
490
                $requiredFieldsValid = ActionController::checkRequiredFields(['resId' => $resId, 'actionRequiredFields' => $actionRequiredFields]);
                if (!empty($requiredFieldsValid['errors'])) {
491
492
493
494
495
                    if (empty($methodResponses['errors'])) {
                        $methodResponses['errors'] = [];
                    }
                    $methodResponses['errors'] = array_merge($methodResponses['errors'], [$requiredFieldsValid['errors']]);
                    continue;
496
497
                }
            }
498
499
500
501
502
503
504
505
            $control = ResourceListController::controlFingerprints(['resId' => $resId]);
            if (!$control) {
                if (empty($methodResponses['errors'])) {
                    $methodResponses['errors'] = [];
                }
                $methodResponses['errors'] = array_merge($methodResponses['errors'], ['Fingerprints do not match for resource ' . $resId]);
                continue;
            }
506

Damien's avatar
Damien committed
507
            if (!empty($method)) {
508
                $methodResponse = ActionMethodController::$method(['resId' => $resId, 'data' => $body['data'], 'note' => $body['note'], 'action' => $action, 'resources' => $resourcesForAction, 'userId' => $aArgs['userId']]);
509

Damien's avatar
Damien committed
510
                if (!empty($methodResponse['errors'])) {
511
512
513
514
                    if (empty($methodResponses['errors'])) {
                        $methodResponses['errors'] = [];
                    }
                    $methodResponses['errors'] = array_merge($methodResponses['errors'], $methodResponse['errors']);
515
                    unset($resourcesForAction[$key]);
Damien's avatar
Damien committed
516
                }
517
518
519
520
521
                if (!empty($methodResponse['data'])) {
                    if (empty($methodResponses['data'])) {
                        $methodResponses['data'] = [];
                    }
                    $methodResponses['data'] = array_merge($methodResponses['data'], $methodResponse['data']);
Damien's avatar
Damien committed
522
                }
Damien's avatar
Damien committed
523
524
            }
        }
Damien's avatar
Damien committed
525
        $historic = empty($methodResponse['history']) ? '' : $methodResponse['history'];
526
        if (!empty($resourcesForAction)) {
527
            ActionMethodController::terminateAction(['id' => $aArgs['actionId'], 'resources' => $resourcesForAction, 'basketName' => $basket['basket_name'], 'note' => $body['note'], 'history' => $historic, 'finishInScript' => !empty($methodResponse['postscript'])]);
528
        }
Damien's avatar
Damien committed
529

530
531
532
        if (!empty($methodResponse['postscript'])) {
            $base64Args = base64_encode(json_encode($methodResponse['args']));
            exec("php {$methodResponse['postscript']} --encodedData {$base64Args} > /dev/null &");
533
            unset($methodResponse['postscript']);
534
535
        }

Damien's avatar
Damien committed
536
537
538
539
        if (!empty($methodResponses)) {
            return $response->withJson($methodResponses);
        }

Damien's avatar
Damien committed
540
541
542
        return $response->withStatus(204);
    }

Damien's avatar
Damien committed
543
544
545
546
547
548
    public function lock(Request $request, Response $response, array $aArgs)
    {
        $body = $request->getParsedBody();
        if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
        }
Damien's avatar
Damien committed
549
        $body['resources'] = array_slice($body['resources'], 0, 500);
Damien's avatar
Damien committed
550

551
        $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
552
553
554
555
556
557
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause']]);

558
        $whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'userId' => $aArgs['userId']]);
Damien's avatar
Damien committed
559
560
561
562
563
        $resources = ResModel::getOnView([
            'select'    => ['res_id', 'locker_user_id', 'locker_time'],
            'where'     => [$whereClause, 'res_view_letterbox.res_id in (?)'],
            'data'      => [$body['resources']]
        ]);
564
565

        $resourcesInBasket = array_column($resources, 'res_id');
Damien's avatar
Damien committed
566

Damien's avatar
Damien committed
567
568
        if (!empty(array_diff($body['resources'], $resourcesInBasket))) {
            return $response->withStatus(403)->withJson(['errors' => 'Resources out of perimeter']);
Damien's avatar
Damien committed
569
570
571
        }

        $resourcesToLock = [];
572
        $lockersId = [];
573
        foreach ($resources as $resource) {
Damien's avatar
Damien committed
574
575
576
            $lock = true;
            if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
                $lock = false;
577
            } elseif ($resource['locker_user_id'] == $GLOBALS['id']) {
Damien's avatar
Damien committed
578
579
580
581
582
583
584
585
                $lock = false;
            } elseif (strtotime($resource['locker_time']) < time()) {
                $lock = false;
            }

            if (!$lock) {
                $resourcesToLock[] = $resource['res_id'];
            } else {
586
                $lockersId[] = $resource['locker_user_id'];
Damien's avatar
Damien committed
587
588
589
            }
        }

Damien's avatar
Damien committed
590
591
        if (!empty($resourcesToLock)) {
            ResModel::update([
592
                'set'   => ['locker_user_id' => $GLOBALS['id'], 'locker_time' => 'CURRENT_TIMESTAMP + interval \'1\' MINUTE'],
Damien's avatar
Damien committed
593
594
595
596
                'where' => ['res_id in (?)'],
                'data'  => [$resourcesToLock]
            ]);
        }
Damien's avatar
Damien committed
597

598
        return $response->withStatus(204);
Damien's avatar
Damien committed
599
600
    }

Damien's avatar
Damien committed
601
602
603
604
605
606
607
608
    public function unlock(Request $request, Response $response, array $aArgs)
    {
        $body = $request->getParsedBody();
        if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
        }
        $body['resources'] = array_slice($body['resources'], 0, 500);

609
        $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
610
611
612
613
614
615
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause']]);

616
        $whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'userId' => $aArgs['userId']]);
Damien's avatar
Damien committed
617
618
619
620
621
        $resources = ResModel::getOnView([
            'select'    => ['res_id', 'locker_user_id', 'locker_time'],
            'where'     => [$whereClause, 'res_view_letterbox.res_id in (?)'],
            'data'      => [$body['resources']]
        ]);
622
623

        $resourcesInBasket = array_column($resources, 'res_id');
Damien's avatar
Damien committed
624

Damien's avatar
Damien committed
625
626
        if (!empty(array_diff($body['resources'], $resourcesInBasket))) {
            return $response->withStatus(403)->withJson(['errors' => 'Resources out of perimeter']);
Damien's avatar
Damien committed
627
628
629
630
        }

        $resourcesToUnlock = [];
        foreach ($resources as $resource) {
631
            if (!(!empty($resource['locker_user_id']) && $resource['locker_user_id'] != $GLOBALS['id'] && strtotime($resource['locker_time']) > time())) {
Damien's avatar
Damien committed
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
                $resourcesToUnlock[] = $resource['res_id'];
            }
        }

        if (!empty($resourcesToUnlock)) {
            ResModel::update([
                'set'   => ['locker_user_id' => null, 'locker_time' => null],
                'where' => ['res_id in (?)'],
                'data'  => [$resourcesToUnlock]
            ]);
        }

        return $response->withStatus(204);
    }

647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
    public function areLocked(Request $request, Response $response, array $args)
    {
        $body = $request->getParsedBody();
        if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
        }
        $body['resources'] = array_slice($body['resources'], 0, 500);

        $errors = ResourceListController::listControl(['groupId' => $args['groupId'], 'userId' => $args['userId'], 'basketId' => $args['basketId'], 'currentUserId' => $GLOBALS['id']]);
        if (!empty($errors['errors'])) {
            return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
        }

        $basket = BasketModel::getById(['id' => $args['basketId'], 'select' => ['basket_clause']]);

662
        $whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'userId' => $args['userId']]);
663
664
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
694
695
696
697
698
699
700
701
702
703
704
705
        $resources = ResModel::getOnView([
            'select'    => ['res_id', 'locker_user_id', 'locker_time'],
            'where'     => [$whereClause, 'res_view_letterbox.res_id in (?)'],
            'data'      => [$body['resources']]
        ]);

        $resourcesInBasket = array_column($resources, 'res_id');
        if (!empty(array_diff($body['resources'], $resourcesInBasket))) {
            return $response->withStatus(403)->withJson(['errors' => 'Resources out of perimeter']);
        }

        $locked = 0;
        $resourcesToLock = [];
        $lockersId = [];
        foreach ($resources as $resource) {
            $lock = true;
            if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
                $lock = false;
            } elseif ($resource['locker_user_id'] == $GLOBALS['id']) {
                $lock = false;
            } elseif (strtotime($resource['locker_time']) < time()) {
                $lock = false;
            }

            if (!$lock) {
                $resourcesToLock[] = $resource['res_id'];
            } else {
                $lockersId[] = $resource['locker_user_id'];
                ++$locked;
            }
        }

        $lockers = [];
        if (!empty($lockersId)) {
            $lockersId = array_unique($lockersId);
            foreach ($lockersId as $lockerId) {
                $lockers[] = UserModel::getLabelledUserById(['id' => $lockerId]);
            }
        }

        return $response->withJson(['countLockedResources' => $locked, 'lockers' => $lockers, 'resourcesToProcess' => $resourcesToLock]);
    }

Damien's avatar
Damien committed
706
    public static function listControl(array $aArgs)
Damien's avatar
Damien committed
707
708
    {
        ValidatorModel::notEmpty($aArgs, ['groupId', 'userId', 'basketId', 'currentUserId']);
Damien's avatar
Damien committed
709
        ValidatorModel::intVal($aArgs, ['groupId', 'userId', 'basketId', 'currentUserId']);
Damien's avatar
Damien committed
710
711

        $group = GroupModel::getById(['id' => $aArgs['groupId'], 'select' => ['group_id']]);
Damien's avatar
Damien committed
712
        $basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_id', 'basket_clause', 'basket_res_order', 'basket_name']]);
Damien's avatar
Damien committed
713
        if (empty($group) || empty($basket)) {
714
            return ['errors' => 'Group or basket does not exist', 'code' => 403];
Damien's avatar
Damien committed
715
716
717
718
719
720
        }

        if ($aArgs['userId'] == $aArgs['currentUserId']) {
            $redirectedBasket = RedirectBasketModel::get([
                'select'    => [1],
                'where'     => ['owner_user_id = ?', 'basket_id = ?', 'group_id = ?'],
Damien's avatar
Damien committed
721
                'data'      => [$aArgs['userId'], $basket['basket_id'], $aArgs['groupId']]
Damien's avatar
Damien committed
722
723
724
725
726
727
728
729
            ]);
            if (!empty($redirectedBasket[0])) {
                return ['errors' => 'Basket out of perimeter (redirected)', 'code' => 403];
            }
        } else {
            $redirectedBasket = RedirectBasketModel::get([
                'select'    => ['actual_user_id'],
                'where'     => ['owner_user_id = ?', 'basket_id = ?', 'group_id = ?'],
Damien's avatar
Damien committed
730
                'data'      => [$aArgs['userId'], $basket['basket_id'], $aArgs['groupId']]
731
            ]);
Damien's avatar
Damien committed
732
733
734
735
            if (empty($redirectedBasket[0]) || $redirectedBasket[0]['actual_user_id'] != $aArgs['currentUserId']) {
                return ['errors' => 'Basket out of perimeter', 'code' => 403];
            }
        }
736

737
        $groups = UserModel::getGroupsById(['id' => $aArgs['userId']]);
738
739
740
        $groups = array_column($groups, 'id');
        if (!in_array($aArgs['groupId'], $groups)) {
            return ['errors' => 'Group is not linked to this user', 'code' => 403];
Damien's avatar
Damien committed
741
742
        }

Damien's avatar
Damien committed
743
        $isBasketLinked = GroupBasketModel::get(['select' => [1], 'where' => ['basket_id = ?', 'group_id = ?'], 'data' => [$basket['basket_id'], $group['group_id']]]);
Damien's avatar
Damien committed
744
        if (empty($isBasketLinked)) {
745
            return ['errors' => 'Group is not linked to this basket', 'code' => 403];
Damien's avatar
Damien committed
746
        }
747

Damien's avatar
Damien committed
748
        return ['success' => 'success'];
Damien's avatar
Damien committed
749
    }
Damien's avatar
Damien committed
750
751
752
753
754
755

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

756
        $res = ResModel::getById(['select' => ['destination'], 'resId' => $args['resId']]);
Damien's avatar
Damien committed
757
758
759
        $listInstances = ListInstanceModel::get([
            'select'    => ['item_id'],
            'where'     => ['difflist_type = ?', 'res_id = ?', 'item_mode = ?'],
Damien's avatar
Damien committed
760
            'data'      => ['entity_id', $args['resId'], 'dest']
Damien's avatar
Damien committed
761
762
        ]);

763
764
        $assignee = '';
        if (!empty($listInstances[0])) {
765
            $assignee .= UserModel::getLabelledUserById(['id' => $listInstances[0]['item_id']]);
766
767
        }
        if (!empty($res['destination'])) {
768
769
            $entityLabel = EntityModel::getByEntityId(['select' => ['entity_label'], 'entityId' => $res['destination']]);
            $assignee .= (empty($assignee) ? "({$entityLabel['entity_label']})" : " ({$entityLabel['entity_label']})");
Damien's avatar
Damien committed
770
771
        }

772
        return $assignee;
Damien's avatar
Damien committed
773
774
775
776
777
778
779
780
781
782
    }

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

        $listInstances = ListInstanceModel::get([
            'select'    => ['item_id', 'requested_signature', 'process_date'],
            'where'     => ['difflist_type = ?', 'res_id = ?'],
Damien's avatar
Damien committed
783
            'data'      => ['VISA_CIRCUIT', $args['resId']],
Damien's avatar
Damien committed
784
785
786
787
            'orderBy'   => ['listinstance_id']
        ]);

        $users = [];
788
        $currentFound = false;
Damien's avatar
Damien committed
789
790
        foreach ($listInstances as $listInstance) {
            $users[] = [
791
                'user'      => UserModel::getLabelledUserById(['id' => $listInstance['item_id']]),
792
793
794
                'mode'      => $listInstance['requested_signature'] ? 'sign' : 'visa',
                'date'      => TextFormatModel::formatDate($listInstance['process_date']),
                'current'   => empty($listInstance['process_date']) && !$currentFound
Damien's avatar
Damien committed
795
            ];
796
797
798
            if (empty($listInstance['process_date']) && !$currentFound) {
                $currentFound = true;
            }
Damien's avatar
Damien committed
799
800
801
802
803
        }

        return $users;
    }

804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
    private static function getSignatories(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

        $listInstances = ListInstanceModel::get([
            'select'    => ['item_id', 'process_date'],
            'where'     => ['difflist_type = ?', 'res_id = ?' ,'requested_signature = ?'],
            'data'      => ['VISA_CIRCUIT', $args['resId'], true],
            'orderBy'   => ['listinstance_id']
        ]);

        $users = [];
        foreach ($listInstances as $listInstance) {
            $users[] = [
819
                'user'      => UserModel::getLabelledUserById(['id' => $listInstance['item_id']]),
820
821
822
823
824
825
826
                'date'      => TextFormatModel::formatDate($listInstance['process_date']),
            ];
        }

        return $users;
    }

Damien's avatar
Damien committed
827
    private static function getParallelOpinionsNumber(array $args)
Damien's avatar
Damien committed
828
829
830
831
832
833
834
835
    {
        ValidatorModel::notEmpty($args, ['resId']);
        ValidatorModel::intVal($args, ['resId']);

        $notes = NoteModel::get(['select' => ['count(1)'], 'where' => ['identifier = ?', 'note_text like ?'], 'data' => [$args['resId'], '[avis%']]);

        return $notes[0]['count'];
    }
836

837
838
839
840
841
    private static function getFolders(array $args)
    {
        ValidatorModel::notEmpty($args, ['resId', 'userId']);
        ValidatorModel::intVal($args, ['resId', 'userId']);

842
        $entities = UserModel::getEntitiesById(['id' => $args['userId'], 'select' => ['entities.id']]);
843
844
845
846
847
848
849
        $entities = array_column($entities, 'id');

        if (empty($entities)) {
            $entities = [0];
        }

        $folders = FolderModel::getWithEntitiesAndResources([
850
            'select'    => ['DISTINCT(folders.id)', 'folders.label'],
851
852
            'where'     => ['res_id = ?', '(user_id = ? OR entity_id in (?) OR keyword = ?)'],
            'data'      => [$args['resId'], $args['userId'], $entities, 'ALL_ENTITIES']
853
854
855
856
857
        ]);

        return $folders;
    }

858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
    public static function getIdsWithOffsetAndLimit(array $args)
    {
        ValidatorModel::arrayType($args, ['resources']);
        ValidatorModel::intVal($args, ['offset', 'limit']);

        $ids = [];
        if (!empty($args['resources'][$args['offset']])) {
            $start = $args['offset'];
            $i = 0;
            while ($i < $args['limit'] && !empty($args['resources'][$start])) {
                $ids[] = $args['resources'][$start]['res_id'];
                ++$start;
                ++$i;
            }
        }

        return $ids;
    }

    public static function getFormattedResources(array $args)
    {
        ValidatorModel::notEmpty($args, ['resources', 'userId']);
        ValidatorModel::arrayType($args, ['resources', 'attachments', 'listDisplay']);
        ValidatorModel::intVal($args, ['userId']);
        ValidatorModel::boolType($args, ['checkLocked']);

        $formattedResources = [];

886
        $resources   = $args['resources'];
887
888
        $attachments = $args['attachments'];

889
        $customFields       = CustomFieldModel::get(['select' => ['id', 'type', 'label']]);
890
        $customFieldsLabels = array_column($customFields, 'label', 'id');
891
        $customFields       = array_column($customFields, 'type', 'id');
892

893
        foreach ($resources as $key => $resource) {
894
895
            $formattedResources[$key]['resId']              = $resource['res_id'];
            $formattedResources[$key]['chrono']             = $resource['alt_identifier'];
896
897
898
899
900
901
902
903
            $formattedResources[$key]['barcode']            = $resource['barcode'];
            $formattedResources[$key]['subject']            = $resource['subject'];
            $formattedResources[$key]['confidentiality']    = $resource['confidentiality'];
            $formattedResources[$key]['statusLabel']        = $resource['status.label_status'];
            $formattedResources[$key]['statusImage']        = $resource['status.img_filename'];
            $formattedResources[$key]['priorityColor']      = $resource['priorities.color'];
            $formattedResources[$key]['closing_date']       = $resource['closing_date'];
            $formattedResources[$key]['countAttachments']   = 0;
904
            $formattedResources[$key]['hasDocument']        = $resource['res_filename'] != null;
905
            $formattedResources[$key]['mailTracking']       = in_array($resource['res_id'], $args['trackedMails']);
906
            $formattedResources[$key]['integrations']       = json_decode($resource['integrations'], true);
907
908
            $formattedResources[$key]['retentionFrozen']    = $resource['retention_frozen'];
            $formattedResources[$key]['binding']            = $resource['binding'];
909
910
911
912
913
914
            foreach ($attachments as $attachment) {
                if ($attachment['res_id_master'] == $resource['res_id']) {
                    $formattedResources[$key]['countAttachments'] = $attachment['count'];
                    break;
                }
            }
915
            $formattedResources[$key]['countNotes'] = NoteModel::countByResId(['resId' => [$resource['res_id']], 'userId' => $args['userId']])[$resource['res_id']];
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933

            if (!empty($args['checkLocked'])) {
                $isLocked = true;
                if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
                    $isLocked = false;
                } elseif ($resource['locker_user_id'] == $args['userId']) {
                    $isLocked = false;
                } elseif (strtotime($resource['locker_time']) < time()) {
                    $isLocked = false;
                }
                if ($isLocked) {
                    $formattedResources[$key]['locker'] = UserModel::getLabelledUserById(['id' => $resource['locker_user_id']]);
                }
                $formattedResources[$key]['isLocked'] = $isLocked;
            }

            if (isset($args['listDisplay'])) {
                $display = [];
934
935
936
937
938
                $listDisplayValues = array_column($args['listDisplay'], 'value');
                if (in_array('getRegisteredMailRecipient', $listDisplayValues) || in_array('getRegisteredMailReference', $listDisplayValues)
                    || in_array('getRegisteredMailIssuingSite', $listDisplayValues)) {
                    $registeredMail = RegisteredMailModel::getByResId(['resId' => $resource['res_id'], 'select' => ['issuing_site', 'recipient', 'reference']]);
                }
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
                foreach ($args['listDisplay'] as $value) {
                    $value = (array)$value;
                    if ($value['value'] == 'getPriority') {
                        $value['displayValue'] = $resource['priorities.label'];
                        $display[] = $value;
                    } elseif ($value['value'] == 'getCategory') {
                        $value['displayValue'] = $resource['category_id'];
                        $display[] = $value;
                    } elseif ($value['value'] == 'getDoctype') {
                        $value['displayValue'] = $resource['doctypes.description'];
                        $display[] = $value;
                    } elseif ($value['value'] == 'getAssignee') {
                        $value['displayValue'] = ResourceListController::getAssignee(['resId' => $resource['res_id']]);
                        $display[] = $value;
                    } elseif ($value['value'] == 'getSenders') {
954
                        $value['displayValue'] = ContactController::getFormattedContacts(['resId' => $resource['res_id'], 'mode' => 'sender', 'onlyContact' => true]);
955
956
                        $display[] = $value;
                    } elseif ($value['value'] == 'getRecipients') {
957
                        $value['displayValue'] = ContactController::getFormattedContacts(['resId' => $resource['res_id'], 'mode' => 'recipient', 'onlyContact' => true]);
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
                        $display[] = $value;
                    } elseif ($value['value'] == 'getVisaWorkflow') {
                        $value['displayValue'] = ResourceListController::getVisaWorkflow(['resId' => $resource['res_id']]);
                        $display[] = $value;
                    } elseif ($value['value'] == 'getSignatories') {
                        $value['displayValue'] = ResourceListController::getSignatories(['resId' => $resource['res_id']]);
                        $display[] = $value;
                    } elseif ($value['value'] == 'getParallelOpinionsNumber') {
                        $value['displayValue'] = ResourceListController::getParallelOpinionsNumber(['resId' => $resource['res_id']]);
                        $display[] = $value;
                    } elseif ($value['value'] == 'getCreationAndProcessLimitDates') {
                        $value['displayValue'] = ['creationDate' => $resource['creation_date'], 'processLimitDate' => $resource['process_limit_date']];
                        $display[] = $value;
                    } elseif ($value['value'] == 'getModificationDate') {
                        $value['displayValue'] = $resource['modification_date'];
                        $display[] = $value;
                    } elseif ($value['value'] == 'getOpinionLimitDate') {
                        $value['displayValue'] = $resource['opinion_limit_date'];
                        $display[] = $value;
977
978
979
                    } elseif ($value['value'] == 'getResId') {
                        $value['displayValue'] = $resource['res_id'];
                        $display[] = $value;
980
981
982
                    } elseif ($value['value'] == 'getBarcode') {
                        $value['displayValue'] = $resource['barcode'];
                        $display[] = $value;
983
984
985
                    } elseif ($value['value'] == 'getRegisteredMailRecipient') {
                        if (!empty($registeredMail)) {
                            $recipient = json_decode($registeredMail['recipient'], true);
986
987
988
989
990
991
992
                            if (!empty($recipient['company']) && (!empty($recipient['firstname']) || !empty($recipient['lastname']))) {
                                $recipient = $recipient['firstname'] . ' ' . $recipient['lastname'] . ' (' . $recipient['company'] . ')';
                            } elseif (empty($recipient['company']) && (!empty($recipient['firstname']) || !empty($recipient['lastname']))) {
                                $recipient = $recipient['firstname'] . ' ' . $recipient['lastname'];
                            } elseif (!empty($recipient['company']) && empty($recipient['firstname']) && empty($recipient['lastname'])) {
                                $recipient = $recipient['company'];
                            }
993
994
995
996
997
                            $value['displayValue'] = $recipient;
                        } else {
                            $value['displayValue'] = '';
                        }
                        $display[] = $value;
998
                    } elseif ($value['value'] == 'getRegisteredMailReference') {
999
1000
                        $value['displayValue'] = !empty($registeredMail) ? $registeredMail['reference'] : '';
                        $display[] = $value;
For faster browsing, not all history is shown. View entire blame