EntityController.php 41.9 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 Entity Controller
* @author dev@maarch.org
*/

namespace Entity\controllers;

Damien's avatar
Damien committed
17
use Basket\models\GroupBasketRedirectModel;
18
use Contact\models\ContactGroupListModel;
19
use Entity\models\EntityModel;
20
use Entity\models\ListInstanceModel;
21
use Entity\models\ListTemplateItemModel;
22
use Entity\models\ListTemplateModel;
23
use Group\controllers\PrivilegeController;
24
use Group\models\GroupModel;
25
use History\controllers\HistoryController;
Damien's avatar
Damien committed
26
27
use MessageExchange\controllers\AnnuaryController;
use Parameter\models\ParameterModel;
28
use Resource\models\ResModel;
29
use Resource\models\ResourceContactModel;
30
use Respect\Validation\Validator;
Damien's avatar
Damien committed
31
32
use Slim\Http\Request;
use Slim\Http\Response;
Damien's avatar
Damien committed
33
use Template\models\TemplateAssociationModel;
34
use User\models\UserEntityModel;
Damien's avatar
Damien committed
35
use User\models\UserModel;
36
37
use Template\models\TemplateModel;
use SrcCore\models\TextFormatModel;
Damien's avatar
Damien committed
38
39
40
41

class EntityController
{
    public function get(Request $request, Response $response)
42
    {
43
        return $response->withJson(['entities' => EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']])]);
44
45
    }

46
    public function getById(Request $request, Response $response, array $args)
47
    {
48
49
        $entity = EntityModel::getById([
            'id' => $args['id'],
50
            'select' => ['*']
51
        ]);
52
53
54
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
        $entity = [
            'id'                    => $entity['id'],
            'entity_label'          => $entity['entity_label'],
            'short_label'           => $entity['short_label'],
            'entity_full_name'      => $entity['entity_full_name'],
            'entity_type'           => $entity['entity_type'],
            'entity_id'             => $entity['entity_id'],
            'enabled'               => $entity['enabled'],
            'parent_entity_id'      => $entity['parent_entity_id'],
            'addressNumber'         => $entity['address_number'],
            'addressStreet'         => $entity['address_street'],
            'addressAdditional1'    => $entity['address_additional1'],
            'addressAdditional2'    => $entity['address_additional2'],
            'addressPostcode'       => $entity['address_postcode'],
            'addressTown'           => $entity['address_town'],
            'addressCountry'        => $entity['address_country'],
            'email'                 => $entity['email']
        ];
73

74
        return $response->withJson($entity);
75
76
    }

77
    public function getDetailledById(Request $request, Response $response, array $args)
78
    {
79
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
80
81
82
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

83
        $entity = EntityModel::getByEntityId(['entityId' => $args['id']]);
84
85
86
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }
87

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        $entity = [
            'id'                    => $entity['id'],
            'entity_label'          => $entity['entity_label'],
            'short_label'           => $entity['short_label'],
            'entity_full_name'      => $entity['entity_full_name'],
            'entity_type'           => $entity['entity_type'],
            'entity_id'             => $entity['entity_id'],
            'enabled'               => $entity['enabled'],
            'parent_entity_id'      => $entity['parent_entity_id'],
            'addressNumber'         => $entity['address_number'],
            'addressStreet'         => $entity['address_street'],
            'addressAdditional1'    => $entity['address_additional1'],
            'addressAdditional2'    => $entity['address_additional2'],
            'addressPostcode'       => $entity['address_postcode'],
            'addressTown'           => $entity['address_town'],
            'addressCountry'        => $entity['address_country'],
            'email'                 => $entity['email'],
            'producerService'       => $entity['producer_service'],
            'business_id'           => $entity['business_id'],
107
108
            'external_id'           => $entity['external_id'],
            'fastParapheurSubscriberId' => json_decode($entity['external_id'], true)['fastParapheurSubscriberId'],
109
        ];
110

111
        $aEntities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
112
        foreach ($aEntities as $aEntity) {
113
            if ($aEntity['entity_id'] == $args['id'] && $aEntity['allowed'] == false) {
114
115
116
117
                return $response->withStatus(403)->withJson(['errors' => 'Entity out of perimeter']);
            }
        }

Damien's avatar
Damien committed
118
        $entity['types'] = EntityModel::getTypes();
Damien's avatar
Damien committed
119
        $listTemplateTypes = ListTemplateModel::getTypes(['select' => ['difflist_type_roles'], 'where' => ['difflist_type_id = ?'], 'data' => ['entity_id']]);
Damien's avatar
Damien committed
120
        $rolesForService = empty($listTemplateTypes[0]['difflist_type_roles']) ? [] : explode(' ', $listTemplateTypes[0]['difflist_type_roles']);
121
122

        //List Templates
123
        $listTemplates = ListTemplateModel::get([
124
125
126
            'select'    => ['id', 'title', 'description', 'type'],
            'where'     => ['entity_id = ?'],
            'data'      => [$entity['id']]
127
128
        ]);

Damien's avatar
Damien committed
129
130
131
132
        $entity['listTemplate'] = [];
        foreach ($rolesForService as $role) {
            $role == 'copy' ? $entity['listTemplate']['cc'] = [] : $entity['listTemplate'][$role] = [];
        }
133
134
        $entity['visaCircuit'] = [];
        $entity['opinionCircuit'] = [];
135
        foreach ($listTemplates as $listTemplate) {
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
            $listTemplateItems = ListTemplateItemModel::get(['select' => ['*'], 'where' => ['list_template_id = ?'], 'data' => [$listTemplate['id']]]);

            if ($listTemplate['type'] == 'diffusionList') {
                $entity['listTemplate'] = $listTemplate;
                $entity['listTemplate']['items'] = [];
                foreach ($listTemplateItems as $listTemplateItem) {
                    if ($listTemplateItem['item_type'] == 'user') {
                        $entity['listTemplate']['items'][$listTemplateItem['item_mode']][] = [
                            'id'                    => $listTemplateItem['item_id'],
                            'type'                  => $listTemplateItem['item_type'],
                            'sequence'              => $listTemplateItem['sequence'],
                            'labelToDisplay'        => UserModel::getLabelledUserById(['id' => $listTemplateItem['item_id']]),
                            'descriptionToDisplay'  => UserModel::getPrimaryEntityById(['id' => $listTemplateItem['item_id'], 'select' => ['entities.entity_label']])['entity_label']
                        ];
                    } elseif ($listTemplateItem['item_type'] == 'entity') {
                        $entity['listTemplate']['items'][$listTemplateItem['item_mode']][] = [
                            'id'                    => $listTemplateItem['item_id'],
                            'type'                  => $listTemplateItem['item_type'],
                            'sequence'              => $listTemplateItem['sequence'],
                            'labelToDisplay'        => EntityModel::getById(['id' => $listTemplateItem['item_id'], 'select' => ['entity_label']])['entity_label'],
                            'descriptionToDisplay'  => ''
157
158
                        ];
                    }
159
160
161
162
163
164
165
166
167
168
169
170
                }
            } else {
                $entity[$listTemplate['type']] = $listTemplate;
                $entity[$listTemplate['type']]['items'] = [];
                foreach ($listTemplateItems as $listTemplateItem) {
                    $entity[$listTemplate['type']]['items'][] = [
                        'id'                    => $listTemplateItem['item_id'],
                        'type'                  => $listTemplateItem['item_type'],
                        'mode'                  => $listTemplateItem['item_mode'],
                        'sequence'              => $listTemplateItem['sequence'],
                        'idToDisplay'           => UserModel::getLabelledUserById(['id' => $listTemplateItem['item_id']]),
                        'descriptionToDisplay'  => UserModel::getPrimaryEntityById(['id' => $listTemplateItem['item_id'], 'select' => ['entities.entity_label']])['entity_label']
171
172
173
174
175
                    ];
                }
            }
        }

176
177
        $entity['templates'] = TemplateModel::getByEntity([
            'select'    => ['t.template_id', 't.template_label', 'template_comment', 't.template_target', 't.template_attachment_type'],
178
            'entities'  => [$args['id']]
179
180
        ]);

kevin.dezaphi's avatar
kevin.dezaphi committed
181
        $entity['users'] = EntityModel::getUsersById(['id' => $entity['entity_id'], 'select' => ['users.id','users.user_id', 'users.firstname', 'users.lastname', 'users.status']]);
182
        $children = EntityModel::get(['select' => [1], 'where' => ['parent_entity_id = ?'], 'data' => [$args['id']]]);
183
        $entity['contact'] = $this->getContactLinkCount($entity['id']);
184
        $entity['hasChildren'] = count($children) > 0;
185
        $documents = ResModel::get(['select' => [1], 'where' => ['destination = ?'], 'data' => [$args['id']]]);
186
        $entity['documents'] = count($documents);
187
        $instances = ListInstanceModel::get(['select' => [1], 'where' => ['item_id = ?', 'item_type = ?'], 'data' => [$entity['id'], 'entity_id']]);
188
        $entity['instances'] = count($instances);
189
        $redirects = GroupBasketRedirectModel::get(['select' => [1], 'where' => ['entity_id = ?'], 'data' => [$args['id']]]);
190
        $entity['redirects'] = count($redirects);
191
192
        $entity['canAdminUsers'] = PrivilegeController::hasPrivilege(['privilegeId' => 'admin_users', 'userId' => $GLOBALS['id']]);
        $entity['canAdminTemplates'] = PrivilegeController::hasPrivilege(['privilegeId' => 'admin_templates', 'userId' => $GLOBALS['id']]);
Damien's avatar
Damien committed
193
194
        $siret = ParameterModel::getById(['id' => 'siret', 'select' => ['param_value_string']]);
        $entity['canSynchronizeSiret'] = !empty($siret['param_value_string']);
195
196
197
198

        return $response->withJson(['entity' => $entity]);
    }

199
200
201
202
203
204
205
    public function getContactLinkCount(int $id)
    {
        $linkCount = count(ResourceContactModel::get(['select' => ['distinct res_id'], 'where' => ['item_id = ?', 'type = ?'], 'data' => [$id, 'entity']]));
        return $linkCount;
    }


206
207
    public function create(Request $request, Response $response)
    {
208
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
209
210
211
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

212
        $body = $request->getParsedBody();
213

214
215
216
217
218
219
220
221
222
223
224
225
        if (empty($body)) {
            return $response->withStatus(400)->withJson(['errors' => 'Body is empty']);
        } elseif (!Validator::stringType()->notEmpty()->validate($body['entity_id']) || !preg_match("/^[\w-]*$/", $body['entity_id']) || (strlen($body['entity_id']) > 32)) {
            return $response->withStatus(400)->withJson(['errors' => 'Body entity_id is empty, not a string or not valid']);
        } elseif (!Validator::stringType()->notEmpty()->validate($body['entity_label'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body entity_label is empty or not a string']);
        } elseif (!Validator::stringType()->notEmpty()->validate($body['short_label'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body short_label is empty or not a string']);
        } elseif (!Validator::stringType()->notEmpty()->validate($body['entity_type'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body entity_type is empty or not a string']);
        } elseif (!empty($body['email']) && !filter_var($body['email'], FILTER_VALIDATE_EMAIL)) {
            return $response->withStatus(400)->withJson(['errors' => 'Body email is not valid']);
226
227
        }

228
        $existingEntity = EntityModel::getByEntityId(['entityId' => $body['entity_id'], 'select' => [1]]);
229
        if (!empty($existingEntity)) {
Pegane Nestor's avatar
Pegane Nestor committed
230
            return $response->withStatus(400)->withJson(['errors' => _ENTITY_ID_ALREADY_EXISTS]);
231
232
        }

233
234
235
236
        $externalId = [];
        if (!empty($body['fastParapheurSubscriberId'])) {
            $externalId['fastParapheurSubscriberId'] = $body['fastParapheurSubscriberId'];
        }
237
        $id = EntityModel::create([
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
            'entity_id'             => $body['entity_id'],
            'entity_label'          => $body['entity_label'],
            'short_label'           => $body['short_label'],
            'address_number'        => $body['addressNumber'],
            'address_street'        => $body['addressStreet'],
            'address_additional1'   => $body['addressAdditional1'],
            'address_additional2'   => $body['addressAdditional2'],
            'address_postcode'      => $body['addressPostcode'],
            'address_town'          => $body['addressTown'],
            'address_country'       => $body['addressCountry'],
            'email'                 => $body['email'],
            'business_id'           => $body['business_id'],
            'parent_entity_id'      => $body['parent_entity_id'],
            'entity_type'           => $body['entity_type'],
            'ldap_id'               => $body['ldap_id'],
            'entity_full_name'      => $body['entity_full_name'],
254
            'producer_service'      => $body['producerService'],
255
            'external_id'           => !empty($externalId) ? json_encode($externalId) : '{}',
256
        ]);
257
258
        HistoryController::add([
            'tableName' => 'entities',
259
            'recordId'  => $body['entity_id'],
260
            'eventType' => 'ADD',
261
            'info'      => _ENTITY_CREATION . " : {$body['entity_id']}",
262
263
264
            'moduleId'  => 'entity',
            'eventId'   => 'entityCreation',
        ]);
265

266
        if (empty($body['parent_entity_id'])) {
267
            $primaryEntity = UserModel::getPrimaryEntityById(['id' => $GLOBALS['id'], 'select' => [1]]);
268
269
270
271
272
            $pEntity = 'N';
            if (empty($primaryEntity)) {
                $pEntity = 'Y';
            }

273
            UserEntityModel::addUserEntity(['id' => $GLOBALS['id'], 'entityId' => $body['entity_id'], 'role' => '', 'primaryEntity' => $pEntity]);
274
275
            HistoryController::add([
                'tableName' => 'users',
276
                'recordId'  => $GLOBALS['id'],
277
                'eventType' => 'UP',
278
                'info'      => _USER_ENTITY_CREATION . " : {$GLOBALS['login']} {$body['entity_id']}",
279
280
281
282
283
                'moduleId'  => 'user',
                'eventId'   => 'userModification',
            ]);
        }

284
        return $response->withJson(['entities' => EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]), 'id' => $id]);
285
286
    }

287
288
    public function update(Request $request, Response $response, array $aArgs)
    {
289
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
290
291
292
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

293
        $entity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => ['id', 'external_id']]);
294
295
296
297
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }

298
        $aEntities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
299
300
301
302
303
304
        foreach ($aEntities as $aEntity) {
            if ($aEntity['entity_id'] == $aArgs['id'] && $aEntity['allowed'] == false) {
                return $response->withStatus(403)->withJson(['errors' => 'Entity out of perimeter']);
            }
        }

305
        $body = $request->getParsedBody();
306

307
308
309
        $check = Validator::stringType()->notEmpty()->validate($body['entity_label']);
        $check = $check && Validator::stringType()->notEmpty()->validate($body['short_label']);
        $check = $check && Validator::stringType()->notEmpty()->validate($body['entity_type']);
310
311
312
313
        if (!$check) {
            return $response->withStatus(400)->withJson(['errors' => 'Bad Request']);
        }

314
        $fatherAndSons = EntityModel::getEntityChildren(['entityId' => $aArgs['id']]);
315
        if (in_array($body['parent_entity_id'], $fatherAndSons)) {
316
317
318
            return $response->withStatus(400)->withJson(['errors' => _CAN_NOT_MOVE_IN_CHILD_ENTITY]);
        }

319
320
321
322
323
324
        if (!empty($body['producerService'])) {
            $body['producer_service'] = $body['producerService'];
        } else {
            $body['producer_service'] = $aArgs['id'];
        }

325
326
327
328
329
330
        $externalId = json_decode($entity['external_id'], true);
        if (!empty($body['fastParapheurSubscriberId'])) {
            $externalId['fastParapheurSubscriberId'] = $body['fastParapheurSubscriberId'];
        } else {
            unset($externalId['fastParapheurSubscriberId']);
        }
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
        EntityModel::update(['set' => [
                'entity_label'          => $body['entity_label'],
                'short_label'           => $body['short_label'],
                'address_number'        => $body['addressNumber'],
                'address_street'        => $body['addressStreet'],
                'address_additional1'   => $body['addressAdditional1'],
                'address_additional2'   => $body['addressAdditional2'],
                'address_postcode'      => $body['addressPostcode'],
                'address_town'          => $body['addressTown'],
                'address_country'       => $body['addressCountry'],
                'email'                 => $body['email'],
                'business_id'           => $body['business_id'],
                'parent_entity_id'      => $body['parent_entity_id'],
                'entity_type'           => $body['entity_type'],
                'ldap_id'               => $body['ldap_id'],
                'entity_full_name'      => $body['entity_full_name'],
347
                'producer_service'      => $body['producerService'],
348
                'external_id'           => !empty($externalId) ? json_encode($externalId) : '{}',
349
350
351
352
            ],
            'where' => ['entity_id = ?'],
            'data'  => [$aArgs['id']]
        ]);
353
354
355
356
357
358
359
360
361
        HistoryController::add([
            'tableName' => 'entities',
            'recordId'  => $aArgs['id'],
            'eventType' => 'UP',
            'info'      => _ENTITY_MODIFICATION . " : {$aArgs['id']}",
            'moduleId'  => 'entity',
            'eventId'   => 'entityModification',
        ]);

362
        if (empty($body['parent_entity_id'])) {
363
            $hasEntity = UserEntityModel::get(['select' => [1], 'where' => ['user_id = ?', 'entity_id = ?'], 'data' => [$GLOBALS['id'], $aArgs['id']]]);
Damien's avatar
Damien committed
364
            if (empty($hasEntity)) {
365
                $primaryEntity = UserModel::getPrimaryEntityById(['id' => $GLOBALS['id'], 'select' => [1]]);
Damien's avatar
Damien committed
366
367
368
369
370
                $pEntity = 'N';
                if (empty($primaryEntity)) {
                    $pEntity = 'Y';
                }

371
                UserEntityModel::addUserEntity(['id' => $GLOBALS['id'], 'entityId' => $aArgs['id'], 'role' => '', 'primaryEntity' => $pEntity]);
Damien's avatar
Damien committed
372
373
                HistoryController::add([
                    'tableName' => 'users',
374
                    'recordId'  => $GLOBALS['id'],
Damien's avatar
Damien committed
375
                    'eventType' => 'UP',
376
                    'info'      => _USER_ENTITY_CREATION . " : {$GLOBALS['login']} {$aArgs['id']}",
Damien's avatar
Damien committed
377
378
379
380
381
382
                    'moduleId'  => 'user',
                    'eventId'   => 'userModification',
                ]);
            }
        }

383
        return $response->withJson(['entities' => EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']])]);
384
    }
385
386
387

    public function delete(Request $request, Response $response, array $aArgs)
    {
388
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
389
390
391
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

Damien's avatar
Damien committed
392
        $entity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => ['id', 'business_id']]);
393
394
395
396
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }

397
        $aEntities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
398
399
400
401
402
403
        foreach ($aEntities as $aEntity) {
            if ($aEntity['entity_id'] == $aArgs['id'] && $aEntity['allowed'] == false) {
                return $response->withStatus(403)->withJson(['errors' => 'Entity out of perimeter']);
            }
        }

404
        $children  = EntityModel::get(['select' => [1], 'where' => ['parent_entity_id = ?'], 'data' => [$aArgs['id']]]);
405
        $documents = ResModel::get(['select' => [1], 'where' => ['destination = ?'], 'data' => [$aArgs['id']]]);
406
        $users     = EntityModel::getUsersById(['select' => [1], 'id' => $aArgs['id']]);
Damien's avatar
Damien committed
407
        $templates = TemplateAssociationModel::get(['select' => [1], 'where' => ['value_field = ?'], 'data' => [$aArgs['id']]]);
408
        $instances = ListInstanceModel::get(['select' => [1], 'where' => ['item_id = ?', 'item_type = ?'], 'data' => [$entity['id'], 'entity_id']]);
Damien's avatar
Damien committed
409
        $redirects = GroupBasketRedirectModel::get(['select' => [1], 'where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
410

Damien's avatar
Damien committed
411
        $allowedCount = count($children) + count($documents) + count($users) + count($templates) + count($instances) + count($redirects);
412
413
414
415
        if ($allowedCount > 0) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity is still used']);
        }

Damien's avatar
Damien committed
416
417
418
419
420
421
422
423
424
        $entities = [];
        if (!empty($entity['business_id'])) {
            $control = AnnuaryController::deleteEntityToOrganization(['entityId' => $aArgs['id']]);
            if (!empty($control['errors'])) {
                return $response->withStatus(400)->withJson(['errors' => $control['errors']]);
            }
            $entities['deleted'] = $control['deleted'];
        }

425
426
427
428
429
430
431
432
433
434
435
        $templateLists = ListTemplateModel::get(['select' => ['id'], 'where' => ['entity_id = ?'], 'data' => [$entity['id']]]);
        if (!empty($templateLists)) {
            foreach ($templateLists as $templateList) {
                ListTemplateModel::delete([
                    'where' => ['id = ?'],
                    'data'  => [$templateList['id']]
                ]);
                ListTemplateItemModel::delete(['where' => ['list_template_id = ?'], 'data' => [$templateList['id']]]);
            }
        }

436
        ContactGroupListModel::delete(['where' => ['correspondent_id = ?', 'correspondent_type = ?'], 'data' => [$entity['id'], 'entity']]);
437
438
        GroupModel::update([
            'postSet'   => ['indexation_parameters' => "jsonb_set(indexation_parameters, '{entities}', (indexation_parameters->'entities') - '{$entity['id']}')"],
439
440
            'where'     => ["indexation_parameters->'entities' @> ?"],
            'data'      => ['"'.$entity['id'].'"']
441
442
        ]);

443
        EntityModel::delete(['where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
Damien's avatar
Damien committed
444

445
446
447
448
449
450
451
452
        HistoryController::add([
            'tableName' => 'entities',
            'recordId'  => $aArgs['id'],
            'eventType' => 'DEL',
            'info'      => _ENTITY_SUPPRESSION . " : {$aArgs['id']}",
            'moduleId'  => 'entity',
            'eventId'   => 'entitySuppression',
        ]);
453

454
        $entities['entities'] = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
455
        return $response->withJson($entities);
456
457
    }

458
    public function reassignEntity(Request $request, Response $response, array $aArgs)
Damien's avatar
Damien committed
459
    {
460
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
Damien's avatar
Damien committed
461
462
463
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

Damien's avatar
Damien committed
464
        $dyingEntity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => ['id', 'parent_entity_id', 'business_id']]);
465
        $successorEntity = EntityModel::getByEntityId(['entityId' => $aArgs['newEntityId'], 'select' => ['id']]);
466
467
468
        if (empty($dyingEntity) || empty($successorEntity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity does not exist']);
        }
469
        $entities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
470
471
472
473
474
475
        foreach ($entities as $entity) {
            if (($entity['entity_id'] == $aArgs['id'] && $entity['allowed'] == false) || ($entity['entity_id'] == $aArgs['newEntityId'] && $entity['allowed'] == false)) {
                return $response->withStatus(403)->withJson(['errors' => 'Entity out of perimeter']);
            }
        }

Damien's avatar
Damien committed
476
477
478
479
480
481
482
483
484
        $entities = [];
        if (!empty($dyingEntity['business_id'])) {
            $control = AnnuaryController::deleteEntityToOrganization(['entityId' => $aArgs['id']]);
            if (!empty($control['errors'])) {
                return $response->withStatus(400)->withJson(['errors' => $control['errors']]);
            }
            $entities['deleted'] = $control['deleted'];
        }

485
        //Documents
486
487
        ResModel::update(['set' => ['destination' => $aArgs['newEntityId']], 'where' => ['destination = ?', 'status != ?'], 'data' => [$aArgs['id'], 'DEL']]);

488
        //Users
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        $users = UserEntityModel::get(['select' => ['user_id', 'entity_id', 'primary_entity'], 'where' => ['entity_id = ? OR entity_id = ?'], 'data' => [$aArgs['id'], $aArgs['newEntityId']]]);
        $tmpUsers = [];
        $doubleUsers = [];
        foreach ($users as $user) {
            if (in_array($user['user_id'], $tmpUsers)) {
                $doubleUsers[] = $user['user_id'];
            }
            $tmpUsers[] = $user['user_id'];
        }
        foreach ($users as $user) {
            if (in_array($user['user_id'], $doubleUsers)) {
                if ($user['entity_id'] == $aArgs['id'] && $user['primary_entity'] == 'N') {
                    UserEntityModel::delete(['where' => ['user_id = ?', 'entity_id = ?'], 'data' => [$user['user_id'], $aArgs['id']]]);
                } elseif ($user['entity_id'] == $aArgs['id'] && $user['primary_entity'] == 'Y') {
                    UserEntityModel::delete(['where' => ['user_id = ?', 'entity_id = ?'], 'data' => [$user['user_id'], $aArgs['newEntityId']]]);
                }
            }
        }
Damien's avatar
Damien committed
507
        UserEntityModel::update(['set' => ['entity_id' => $aArgs['newEntityId']], 'where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
508

509
        //Entities
510
511
512
        $entities = EntityModel::get(['select' => ['entity_id', 'parent_entity_id'], 'where' => ['parent_entity_id = ?'], 'data' => [$aArgs['id']]]);
        foreach ($entities as $entity) {
            if ($entity['entity_id'] = $aArgs['newEntityId']) {
513
                EntityModel::update(['set' => ['parent_entity_id' => $dyingEntity['parent_entity_id']], 'where' => ['entity_id = ?'], 'data' => [$aArgs['newEntityId']]]);
514
515
516
517
518
            } else {
                EntityModel::update(['set' => ['parent_entity_id' => $aArgs['newEntityId']], 'where' => ['entity_id = ?'], 'data' => [$entity['entity_id']]]);
            }
        }

519
        //Baskets
Damien's avatar
Damien committed
520
        GroupBasketRedirectModel::update(['set' => ['entity_id' => $aArgs['newEntityId']], 'where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
521
        //ListInstances
522
        ListInstanceModel::update(['set' => ['item_id' => $successorEntity['id']], 'where' => ['item_id = ?', 'item_type = ?'], 'data' => [$dyingEntity['id'], 'entity_id']]);
523
        //ListTemplates
524
525
526
527
528
529
530
531
532
533
        $templateLists = ListTemplateModel::get(['select' => ['id'], 'where' => ['entity_id = ?'], 'data' => [$dyingEntity['id']]]);
        if (!empty($templateLists)) {
            foreach ($templateLists as $templateList) {
                ListTemplateModel::delete([
                    'where' => ['id = ?'],
                    'data'  => [$templateList['id']]
                ]);
                ListTemplateItemModel::delete(['where' => ['list_template_id = ?'], 'data' => [$templateList['id']]]);
            }
        }
534
        //Templates
Damien's avatar
Damien committed
535
        TemplateAssociationModel::update(['set' => ['value_field' => $aArgs['newEntityId']], 'where' => ['value_field = ?'], 'data' => [$aArgs['id']]]);
536
537
538
        //GroupIndexing
        GroupModel::update([
            'postSet'   => ['indexation_parameters' => "jsonb_set(indexation_parameters, '{entities}', (indexation_parameters->'entities') - '{$dyingEntity['id']}')"],
539
540
            'where'     => ["indexation_parameters->'entities' @> ?"],
            'data'      => ['"'.$dyingEntity['id'].'"']
541
        ]);
542
        //ResourceContact
543
544
545
546
547
548
549
550
551
552
553
554
555
        $dyingOcc = ResourceContactModel::get(['select' => ['id', 'res_id', 'item_id', 'mode'], 'where' => ['type = ?', 'item_id = ?'], 'data' => ['entity', $dyingEntity['id']]]);
        $succOcc = ResourceContactModel::get(['select' => ['id', 'res_id', 'item_id', 'mode'], 'where' => ['type = ?', 'item_id = ?', 'res_id in (?)'], 'data' => ['entity', $successorEntity['id'], array_uniq(array_column($dyingOcc, 'res_id'))]]);
        $dyingIds = array_column($dyingOcc, 'id');
        $idsToDelete = [];
        foreach ($dyingOcc as $d) {
            foreach ($succOcc as $s) {
                if ($d['mode'] == $s['mode'] && $d['res_id'] == $s['res_id']) {
                    $idsToDelete[] = $d['id'];
                }
            }
        }
        ResourceContactModel::delete(['where' => ['id in (?)'], 'data' => [$idsToDelete]]);
        ResourceContactModel::update(['set' => ['item_id' => $successorEntity['id']], 'where' => ['id in (?)'], 'data' => [$dyingIds]]);
556

557
558
559
560
561
562
563
564
        HistoryController::add([
            'tableName' => 'entities',
            'recordId'  => $aArgs['id'],
            'eventType' => 'DEL',
            'info'      => _ENTITY_SUPPRESSION . " : {$aArgs['id']}",
            'moduleId'  => 'entity',
            'eventId'   => 'entitySuppression',
        ]);
565

566
        $entities['entities'] = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
567
        return $response->withJson($entities);
Damien's avatar
Damien committed
568
    }
Damien's avatar
Damien committed
569
570
571

    public function updateStatus(Request $request, Response $response, array $aArgs)
    {
572
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
Damien's avatar
Damien committed
573
574
575
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

576
        $entity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => [1]]);
Damien's avatar
Damien committed
577
578
579
580
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }

581
        $aEntities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
        foreach ($aEntities as $aEntity) {
            if ($aEntity['entity_id'] == $aArgs['id'] && $aEntity['allowed'] == false) {
                return $response->withStatus(403)->withJson(['errors' => 'Entity out of perimeter']);
            }
        }

        $data = $request->getParams();
        $check = Validator::stringType()->notEmpty()->validate($data['method']);
        if (!$check) {
            return $response->withStatus(400)->withJson(['errors' => 'Bad Request']);
        }

        if ($data['method'] == 'disable') {
            $status = 'N';
        } else {
            $status = 'Y';
        }
        $fatherAndSons = EntityModel::getEntityChildren(['entityId' => $aArgs['id']]);

        EntityModel::update(['set' => ['enabled' => $status], 'where' => ['entity_id in (?)'], 'data' => [$fatherAndSons]]);
        HistoryController::add([
            'tableName' => 'entities',
            'recordId'  => $aArgs['id'],
            'eventType' => 'UP',
            'info'      => _ENTITY_MODIFICATION . " : {$aArgs['id']}",
            'moduleId'  => 'entity',
            'eventId'   => 'entityModification',
        ]);

        return $response->withJson(['success' => 'success']);
    }
613

614
615
    public function getUsersById(Request $request, Response $response, array $aArgs)
    {
Vinciane's avatar
Vinciane committed
616
        $entity = EntityModel::getById(['id' => $aArgs['id'], 'select' => ['entity_id']]);
617
618
619
620
621
622
623
624
625
626
627
628
629
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }

        $users = UserEntityModel::getWithUsers([
            'select'    => ['DISTINCT users.id', 'users.user_id', 'firstname', 'lastname'],
            'where'     => ['users_entities.entity_id = ?', 'status not in (?)'],
            'data'      => [$entity['entity_id'], ['DEL', 'ABS']],
            'orderBy'   => ['lastname', 'firstname']
        ]);

        foreach ($users as $key => $user) {
            $users[$key]['labelToDisplay'] = "{$user['firstname']} {$user['lastname']}";
630
            $users[$key]['descriptionToDisplay'] = UserModel::getPrimaryEntityById(['id' => $user['id'], 'select' => ['entities.entity_label']])['entity_label'];
631
632
633
634
635
        }

        return $response->withJson(['users' => $users]);
    }

636
637
638
639
    public function getTypes(Request $request, Response $response)
    {
        return $response->withJson(['types' => EntityModel::getTypes()]);
    }
640

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
    public function getParentAddress(Request $request, Response $response, array $args)
    {
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

        $entity = EntityModel::getById(['id' => $args['id'], 'select' => ['parent_entity_id']]);
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity does not exist']);
        }

        while (!empty($entity['parent_entity_id'])) {
            $entity = EntityModel::getByEntityId([
                'entityId'  => $entity['parent_entity_id'],
                'select'    => ['parent_entity_id', 'address_number', 'address_street', 'address_additional1', 'address_additional2', 'address_postcode', 'address_town', 'address_country']
            ]);
            if (!empty($entity['address_street'])) {
                return $response->withJson([
                    'addressNumber'         => $entity['address_number'],
                    'addressStreet'         => $entity['address_street'],
                    'addressAdditional1'    => $entity['address_additional1'],
                    'addressAdditional2'    => $entity['address_additional2'],
                    'addressPostcode'       => $entity['address_postcode'],
                    'addressTown'           => $entity['address_town'],
                    'addressCountry'        => $entity['address_country']
                ]);
            }
        }

670
        return $response->withJson(null);
671
672
    }

673
674
675
676
677
678
    public function export(Request $request, Response $response)
    {
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

679
        $allowedFieldsCamelCase = [
680
681
682
683
684
685
            'id', 'entityId', 'entityLabel', 'shortLabel', 'entityFullName', 'enabled', 'addressNumber', 'addressStreet', 'addressAdditional1', 'addressAdditional2',
            'addressPostcode', 'addressTown', 'addressCountry', 'email', 'parentEntityId', 'entityType', 'businessId', 'folderImport', 'producerService',
            'diffusionList', 'visaCircuit', 'opinionCircuit',
            'users',
            'templates'
        ];
686
687
688
689
690
691
692
693
694
        $allowedFields = [];
        foreach ($allowedFieldsCamelCase as $camelCaseField) {
            if (in_array($camelCaseField, ['diffusionList', 'visaCircuit', 'opinionCircuit'])) {
                $allowedFields[$camelCaseField] = $camelCaseField;
            } else {
                $allowedFields[$camelCaseField] = TextFormatModel::camelToSnake($camelCaseField);
            }
        }
        unset($allowedFieldsCamelCase);
695

696
697
698
699
700
701
702
703
704
        $body = $request->getParsedBody();

        $delimiter = ';';
        if (!empty($body['delimiter'])) {
            if (in_array($body['delimiter'], [',', ';', 'TAB'])) {
                $delimiter = ($body['delimiter'] == 'TAB' ? "\t" : $body['delimiter']);
            }
        }

705
706
707
708
        $fields = [];
        foreach ($allowedFields as $camel => $snake) {
            $fields[] = ['label' => $snake, 'value' => $camel];
        }
709
710
711
712
        if (!empty($body['data'])) {
            $fields = [];
            foreach ($body['data'] as $parameter) {
                if (!empty($parameter['label']) && is_string($parameter['label']) && !empty($parameter['value']) && is_string($parameter['value'])) {
713
                    if (!in_array($parameter['value'], array_keys($allowedFields))) {
714
715
716
717
718
719
720
721
722
723
724
725
                        continue;
                    }
                    $fields[] = [
                        'label' => $parameter['label'],
                        'value' => $parameter['value']
                    ];
                }
            }
        }
        if (empty($fields)) {
            return $response->withStatus(400)->withJson(['errors' => 'no allowed fields selected for entities export']);
        }
726
727
728
729
730
731
732
733
734
735
736

        ini_set('memory_limit', -1);

        $file = fopen('php://temp', 'w');
        $delimiter = ($delimiter == 'TAB' ? "\t" : $delimiter);

        $entities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
        $entities = array_filter($entities, function ($entity) {
            return $entity['allowed'] == true;
        });
        $entitiesIds = array_column($entities, 'serialId');
737

738
739
        $select = array_map(function ($field) use ($allowedFields) {
            return $allowedFields[$field['value']];
740
        }, $fields);
741
        $select = array_diff($select, ['diffusionList', 'visaCircuit', 'opinionCircuit', 'users', 'templates']);
742
743
744
745
746
747
748
        if (!in_array('id', $select)) {
            $select[] = 'id';
        }
        if (!in_array('entity_id', $select)) {
            $select[] = 'entity_id';
        }

749
        $entities = EntityModel::get([
750
            'select'  => $select,
751
752
753
754
755
            'where'   => ['id in (?)'],
            'data'    => [$entitiesIds],
            'orderBy' => ['parent_entity_id', 'entity_label']
        ]);

756
757
758
759
760
761
762
763
        $templateTypes = [];
        foreach ($fields as $key => $field) {
            if (in_array($field['value'], ['diffusionList', 'visaCircuit', 'opinionCircuit'])) {
                $templateTypes[] = $field['value'];
            }
        }
        $includeUsers     = in_array('users', array_column($fields, 'value'));
        $includeTemplates = in_array('templates', array_column($fields, 'value'));
764

765
766
767
        $roles = EntityModel::getRoles();
        $roles = array_column($roles, 'label', 'id');

768
769
        foreach ($entities as $key => $entity) {
            // list templates
770
            foreach ($templateTypes as $type) {
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
                $template = ListTemplateModel::get([
                    'select' => ['*'],
                    'where'  => ['entity_id = ?', 'type = ?'],
                    'data'   => [$entity['id'], $type]
                ]);

                $list = [];
                if (!empty($template)) {
                    $template = $template[0];
                    $templateItems = ListTemplateItemModel::get([
                        'select'  => ['*'],
                        'where'   => ['list_template_id = ?'],
                        'data'    => [$template['id']],
                        'orderBy' => ['sequence']
                    ]);
                    foreach ($templateItems as $templateItem) {
                        $item = [];
788
789
                        if ($templateItem['item_mode'] == 'cc') {
                            $templateItem['item_mode'] = 'copy';
790
                        }
791
                        $item[] = $roles[$templateItem['item_mode']];
792
793
794
795
796
797
798
799
800
801
802

                        if ($templateItem['item_type'] == 'user') {
                            $item[] = UserModel::getLabelledUserById(['id' => $templateItem['item_id']]);
                        } elseif ($templateItem['item_type'] == 'entity') {
                            $entityLabel = EntityModel::getById(['select' => ['entity_label'], 'id' => $templateItem['item_id']]);
                            $item[] = $entityLabel['entity_label'];
                        }

                        $list[] = implode(' ', $item);
                    }
                }
803
                $entities[$key][$type] = implode("\n", $list);
804
805
806
            }

            // Users in entity
807
808
809
810
811
812
813
814
815
816
817
            if ($includeUsers) {
                $users = UserEntityModel::getWithUsers([
                    'select'    => ['DISTINCT users.id', 'firstname', 'lastname'],
                    'where'     => ['users_entities.entity_id = ?'],
                    'data'      => [$entity['entity_id']]
                ]);
                $users = array_map(function ($user) {
                    return $user['firstname'] . ' ' . $user['lastname'];
                }, $users);
                $entities[$key]['users'] = implode("\n", $users);
            }
818
819

            // Document templates
820
821
822
823
824
825
826
827
828
829
            if ($includeTemplates) {
                $templates = TemplateModel::getByEntity([
                    'select'    => ['t.template_label', 't.template_target'],
                    'entities'  => [$entity['entity_id']]
                ]);
                $templates = array_map(function ($template) {
                    return $template['template_label'] . ' ' . $template['template_target'];
                }, $templates);
                $entities[$key]['templates'] = implode("\n", $templates);
            }
830
831
        }

832
        $csvHead = array_map(function ($field) { return $field; }, array_column($fields, 'label'));
833
        fputcsv($file, $csvHead, $delimiter);
834
835

        foreach ($entities as $entity) {
836
837
            $entityValues = [];
            foreach ($fields as $field) {
838
                $entityValues[] = $entity[$allowedFields[$field['value']]];
839
840
            }
            fputcsv($file, $entityValues, $delimiter);
841
842
843
844
845
846
847
848
849
850
851
        }

        rewind($file);

        $response->write(stream_get_contents($file));
        $response = $response->withAddedHeader('Content-Disposition', 'attachment; filename=export_maarch.csv');
        $contentType = 'application/vnd.ms-excel';
        fclose($file);

        return $response->withHeader('Content-Type', $contentType);
    }
Damien's avatar
Damien committed
852
}