EntityController.php 38 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 Respect\Validation\Validator;
Damien's avatar
Damien committed
30
31
use Slim\Http\Request;
use Slim\Http\Response;
Damien's avatar
Damien committed
32
use Template\models\TemplateAssociationModel;
33
use User\models\UserEntityModel;
Damien's avatar
Damien committed
34
use User\models\UserModel;
35
use \Template\models\TemplateModel;
Damien's avatar
Damien committed
36
37
38
39

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

44
    public function getById(Request $request, Response $response, array $args)
45
    {
46
47
        $entity = EntityModel::getById([
            'id' => $args['id'],
48
            'select' => ['*']
49
        ]);
50
51
52
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
        $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']
        ];
71

72
        return $response->withJson($entity);
73
74
    }

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

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

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
        $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'],
105
106
            'external_id'           => $entity['external_id'],
            'fastParapheurSubscriberId' => json_decode($entity['external_id'], true)['fastParapheurSubscriberId'],
107
        ];
108

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

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

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

Damien's avatar
Damien committed
127
128
129
130
        $entity['listTemplate'] = [];
        foreach ($rolesForService as $role) {
            $role == 'copy' ? $entity['listTemplate']['cc'] = [] : $entity['listTemplate'][$role] = [];
        }
131
132
        $entity['visaCircuit'] = [];
        $entity['opinionCircuit'] = [];
133
        foreach ($listTemplates as $listTemplate) {
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
            $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'  => ''
155
156
                        ];
                    }
157
158
159
160
161
162
163
164
165
166
167
168
                }
            } 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']
169
170
171
172
173
                    ];
                }
            }
        }

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

kevin.dezaphi's avatar
kevin.dezaphi committed
179
        $entity['users'] = EntityModel::getUsersById(['id' => $entity['entity_id'], 'select' => ['users.id','users.user_id', 'users.firstname', 'users.lastname', 'users.status']]);
180
        $children = EntityModel::get(['select' => [1], 'where' => ['parent_entity_id = ?'], 'data' => [$args['id']]]);
181
        $entity['hasChildren'] = count($children) > 0;
182
        $documents = ResModel::get(['select' => [1], 'where' => ['destination = ?'], 'data' => [$args['id']]]);
183
        $entity['documents'] = count($documents);
184
        $instances = ListInstanceModel::get(['select' => [1], 'where' => ['item_id = ?', 'item_type = ?'], 'data' => [$entity['id'], 'entity_id']]);
185
        $entity['instances'] = count($instances);
186
        $redirects = GroupBasketRedirectModel::get(['select' => [1], 'where' => ['entity_id = ?'], 'data' => [$args['id']]]);
187
        $entity['redirects'] = count($redirects);
188
189
        $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
190
191
        $siret = ParameterModel::getById(['id' => 'siret', 'select' => ['param_value_string']]);
        $entity['canSynchronizeSiret'] = !empty($siret['param_value_string']);
192
193
194
195
196
197

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

    public function create(Request $request, Response $response)
    {
198
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
199
200
201
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

202
        $body = $request->getParsedBody();
203

204
205
206
207
208
209
210
211
212
213
214
215
        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']);
216
217
        }

218
        $existingEntity = EntityModel::getByEntityId(['entityId' => $body['entity_id'], 'select' => [1]]);
219
        if (!empty($existingEntity)) {
Pegane Nestor's avatar
Pegane Nestor committed
220
            return $response->withStatus(400)->withJson(['errors' => _ENTITY_ID_ALREADY_EXISTS]);
221
222
        }

223
224
225
226
        $externalId = [];
        if (!empty($body['fastParapheurSubscriberId'])) {
            $externalId['fastParapheurSubscriberId'] = $body['fastParapheurSubscriberId'];
        }
227
        $id = EntityModel::create([
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
            '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'],
244
245
            'producer_service'      => $body['producerService'],
            'external_id'           => json_encode($externalId)
246
        ]);
247
248
        HistoryController::add([
            'tableName' => 'entities',
249
            'recordId'  => $body['entity_id'],
250
            'eventType' => 'ADD',
251
            'info'      => _ENTITY_CREATION . " : {$body['entity_id']}",
252
253
254
            'moduleId'  => 'entity',
            'eventId'   => 'entityCreation',
        ]);
255

256
        if (empty($body['parent_entity_id'])) {
257
            $primaryEntity = UserModel::getPrimaryEntityById(['id' => $GLOBALS['id'], 'select' => [1]]);
258
259
260
261
262
            $pEntity = 'N';
            if (empty($primaryEntity)) {
                $pEntity = 'Y';
            }

263
            UserEntityModel::addUserEntity(['id' => $GLOBALS['id'], 'entityId' => $body['entity_id'], 'role' => '', 'primaryEntity' => $pEntity]);
264
265
            HistoryController::add([
                'tableName' => 'users',
266
                'recordId'  => $GLOBALS['id'],
267
                'eventType' => 'UP',
268
                'info'      => _USER_ENTITY_CREATION . " : {$GLOBALS['login']} {$body['entity_id']}",
269
270
271
272
273
                'moduleId'  => 'user',
                'eventId'   => 'userModification',
            ]);
        }

274
        return $response->withJson(['entities' => EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]), 'id' => $id]);
275
276
    }

277
278
    public function update(Request $request, Response $response, array $aArgs)
    {
279
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
280
281
282
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

283
        $entity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => ['id', 'external_id']]);
284
285
286
287
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }

288
        $aEntities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
289
290
291
292
293
294
        foreach ($aEntities as $aEntity) {
            if ($aEntity['entity_id'] == $aArgs['id'] && $aEntity['allowed'] == false) {
                return $response->withStatus(403)->withJson(['errors' => 'Entity out of perimeter']);
            }
        }

295
        $body = $request->getParsedBody();
296

297
298
299
        $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']);
300
301
302
303
        if (!$check) {
            return $response->withStatus(400)->withJson(['errors' => 'Bad Request']);
        }

304
        $fatherAndSons = EntityModel::getEntityChildren(['entityId' => $aArgs['id']]);
305
        if (in_array($body['parent_entity_id'], $fatherAndSons)) {
306
307
308
            return $response->withStatus(400)->withJson(['errors' => _CAN_NOT_MOVE_IN_CHILD_ENTITY]);
        }

309
310
311
312
313
314
        if (!empty($body['producerService'])) {
            $body['producer_service'] = $body['producerService'];
        } else {
            $body['producer_service'] = $aArgs['id'];
        }

315
316
317
318
319
320
        $externalId = json_decode($entity['external_id'], true);
        if (!empty($body['fastParapheurSubscriberId'])) {
            $externalId['fastParapheurSubscriberId'] = $body['fastParapheurSubscriberId'];
        } else {
            unset($externalId['fastParapheurSubscriberId']);
        }
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
        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'],
337
338
                'producer_service'      => $body['producerService'],
                'external_id'           => json_encode($externalId)
339
340
341
342
            ],
            'where' => ['entity_id = ?'],
            'data'  => [$aArgs['id']]
        ]);
343
344
345
346
347
348
349
350
351
        HistoryController::add([
            'tableName' => 'entities',
            'recordId'  => $aArgs['id'],
            'eventType' => 'UP',
            'info'      => _ENTITY_MODIFICATION . " : {$aArgs['id']}",
            'moduleId'  => 'entity',
            'eventId'   => 'entityModification',
        ]);

352
        if (empty($body['parent_entity_id'])) {
353
            $hasEntity = UserEntityModel::get(['select' => [1], 'where' => ['user_id = ?', 'entity_id = ?'], 'data' => [$GLOBALS['id'], $aArgs['id']]]);
Damien's avatar
Damien committed
354
            if (empty($hasEntity)) {
355
                $primaryEntity = UserModel::getPrimaryEntityById(['id' => $GLOBALS['id'], 'select' => [1]]);
Damien's avatar
Damien committed
356
357
358
359
360
                $pEntity = 'N';
                if (empty($primaryEntity)) {
                    $pEntity = 'Y';
                }

361
                UserEntityModel::addUserEntity(['id' => $GLOBALS['id'], 'entityId' => $aArgs['id'], 'role' => '', 'primaryEntity' => $pEntity]);
Damien's avatar
Damien committed
362
363
                HistoryController::add([
                    'tableName' => 'users',
364
                    'recordId'  => $GLOBALS['id'],
Damien's avatar
Damien committed
365
                    'eventType' => 'UP',
366
                    'info'      => _USER_ENTITY_CREATION . " : {$GLOBALS['login']} {$aArgs['id']}",
Damien's avatar
Damien committed
367
368
369
370
371
372
                    'moduleId'  => 'user',
                    'eventId'   => 'userModification',
                ]);
            }
        }

373
        return $response->withJson(['entities' => EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']])]);
374
    }
375
376
377

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

Damien's avatar
Damien committed
382
        $entity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => ['id', 'business_id']]);
383
384
385
386
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }

387
        $aEntities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
388
389
390
391
392
393
        foreach ($aEntities as $aEntity) {
            if ($aEntity['entity_id'] == $aArgs['id'] && $aEntity['allowed'] == false) {
                return $response->withStatus(403)->withJson(['errors' => 'Entity out of perimeter']);
            }
        }

394
        $children  = EntityModel::get(['select' => [1], 'where' => ['parent_entity_id = ?'], 'data' => [$aArgs['id']]]);
395
        $documents = ResModel::get(['select' => [1], 'where' => ['destination = ?'], 'data' => [$aArgs['id']]]);
396
        $users     = EntityModel::getUsersById(['select' => [1], 'id' => $aArgs['id']]);
Damien's avatar
Damien committed
397
        $templates = TemplateAssociationModel::get(['select' => [1], 'where' => ['value_field = ?'], 'data' => [$aArgs['id']]]);
398
        $instances = ListInstanceModel::get(['select' => [1], 'where' => ['item_id = ?', 'item_type = ?'], 'data' => [$entity['id'], 'entity_id']]);
Damien's avatar
Damien committed
399
        $redirects = GroupBasketRedirectModel::get(['select' => [1], 'where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
400

Damien's avatar
Damien committed
401
        $allowedCount = count($children) + count($documents) + count($users) + count($templates) + count($instances) + count($redirects);
402
403
404
405
        if ($allowedCount > 0) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity is still used']);
        }

Damien's avatar
Damien committed
406
407
408
409
410
411
412
413
414
        $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'];
        }

415
416
417
418
419
420
421
422
423
424
425
        $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']]]);
            }
        }

426
        ContactGroupListModel::delete(['where' => ['correspondent_id = ?', 'correspondent_type = ?'], 'data' => [$entity['id'], 'entity']]);
427
428
        GroupModel::update([
            'postSet'   => ['indexation_parameters' => "jsonb_set(indexation_parameters, '{entities}', (indexation_parameters->'entities') - '{$entity['id']}')"],
429
430
            'where'     => ["indexation_parameters->'entities' @> ?"],
            'data'      => ['"'.$entity['id'].'"']
431
432
        ]);

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

435
436
437
438
439
440
441
442
        HistoryController::add([
            'tableName' => 'entities',
            'recordId'  => $aArgs['id'],
            'eventType' => 'DEL',
            'info'      => _ENTITY_SUPPRESSION . " : {$aArgs['id']}",
            'moduleId'  => 'entity',
            'eventId'   => 'entitySuppression',
        ]);
443

444
        $entities['entities'] = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
445
        return $response->withJson($entities);
446
447
    }

448
    public function reassignEntity(Request $request, Response $response, array $aArgs)
Damien's avatar
Damien committed
449
    {
450
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
Damien's avatar
Damien committed
451
452
453
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

Damien's avatar
Damien committed
454
        $dyingEntity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => ['id', 'parent_entity_id', 'business_id']]);
455
        $successorEntity = EntityModel::getByEntityId(['entityId' => $aArgs['newEntityId'], 'select' => ['id']]);
456
457
458
        if (empty($dyingEntity) || empty($successorEntity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity does not exist']);
        }
459
        $entities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
460
461
462
463
464
465
        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
466
467
468
469
470
471
472
473
474
        $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'];
        }

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

478
        //Users
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
        $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
497
        UserEntityModel::update(['set' => ['entity_id' => $aArgs['newEntityId']], 'where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
498

499
        //Entities
500
501
502
        $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']) {
503
                EntityModel::update(['set' => ['parent_entity_id' => $dyingEntity['parent_entity_id']], 'where' => ['entity_id = ?'], 'data' => [$aArgs['newEntityId']]]);
504
505
506
507
508
            } else {
                EntityModel::update(['set' => ['parent_entity_id' => $aArgs['newEntityId']], 'where' => ['entity_id = ?'], 'data' => [$entity['entity_id']]]);
            }
        }

509
        //Baskets
Damien's avatar
Damien committed
510
        GroupBasketRedirectModel::update(['set' => ['entity_id' => $aArgs['newEntityId']], 'where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
511
        //ListInstances
512
        ListInstanceModel::update(['set' => ['item_id' => $successorEntity['id']], 'where' => ['item_id = ?', 'item_type = ?'], 'data' => [$dyingEntity['id'], 'entity_id']]);
513
        //ListTemplates
514
515
516
517
518
519
520
521
522
523
        $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']]]);
            }
        }
524
        //Templates
Damien's avatar
Damien committed
525
        TemplateAssociationModel::update(['set' => ['value_field' => $aArgs['newEntityId']], 'where' => ['value_field = ?'], 'data' => [$aArgs['id']]]);
526
527
528
        //GroupIndexing
        GroupModel::update([
            'postSet'   => ['indexation_parameters' => "jsonb_set(indexation_parameters, '{entities}', (indexation_parameters->'entities') - '{$dyingEntity['id']}')"],
529
530
            'where'     => ["indexation_parameters->'entities' @> ?"],
            'data'      => ['"'.$dyingEntity['id'].'"']
531
        ]);
532

533
534

        EntityModel::delete(['where' => ['entity_id = ?'], 'data' => [$aArgs['id']]]);
535
536
537
538
539
540
541
542
        HistoryController::add([
            'tableName' => 'entities',
            'recordId'  => $aArgs['id'],
            'eventType' => 'DEL',
            'info'      => _ENTITY_SUPPRESSION . " : {$aArgs['id']}",
            'moduleId'  => 'entity',
            'eventId'   => 'entitySuppression',
        ]);
543

544
        $entities['entities'] = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
545
        return $response->withJson($entities);
Damien's avatar
Damien committed
546
    }
Damien's avatar
Damien committed
547
548
549

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

554
        $entity = EntityModel::getByEntityId(['entityId' => $aArgs['id'], 'select' => [1]]);
Damien's avatar
Damien committed
555
556
557
558
        if (empty($entity)) {
            return $response->withStatus(400)->withJson(['errors' => 'Entity not found']);
        }

559
        $aEntities = EntityModel::getAllowedEntitiesByUserId(['userId' => $GLOBALS['login']]);
Damien's avatar
Damien committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
        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']);
    }
591

592
593
    public function getUsersById(Request $request, Response $response, array $aArgs)
    {
Vinciane's avatar
Vinciane committed
594
        $entity = EntityModel::getById(['id' => $aArgs['id'], 'select' => ['entity_id']]);
595
596
597
598
599
600
601
602
603
604
605
606
607
        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']}";
608
            $users[$key]['descriptionToDisplay'] = UserModel::getPrimaryEntityById(['id' => $user['id'], 'select' => ['entities.entity_label']])['entity_label'];
609
610
611
612
613
        }

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

614
615
616
617
    public function getTypes(Request $request, Response $response)
    {
        return $response->withJson(['types' => EntityModel::getTypes()]);
    }
618

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
    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']
                ]);
            }
        }

648
        return $response->withJson(null);
649
650
    }

651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    public function export(Request $request, Response $response)
    {
        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'manage_entities', 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

        $body = $request->getParsedBody();

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

        $fields = [
667
668
            'id', 'entity_id', 'entity_label', 'short_label', 'entity_full_name', 'enabled', 'address_number', 'address_street', 'address_additional1', 'address_additional2',
            'address_postcode', 'address_town', 'address_country', 'email', 'parent_entity_id', 'entity_type', 'business_id', 'folder_import', 'producer_service'
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
        ];

        $csvHead = array_merge($fields, [ 'diffusionList', 'visaCircuit', 'opinionCircuit', 'users', 'templates']);

        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');
        $entities = EntityModel::get([
            'select'  => $fields,
            'where'   => ['id in (?)'],
            'data'    => [$entitiesIds],
            'orderBy' => ['parent_entity_id', 'entity_label']
        ]);

        $templateType = ['diffusionList', 'visaCircuit', 'opinionCircuit'];

692
693
694
        $roles = EntityModel::getRoles();
        $roles = array_column($roles, 'label', 'id');

695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
        foreach ($entities as $key => $entity) {
            // list templates
            foreach ($templateType as $type) {
                $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 = [];
715
716
                        if ($templateItem['item_mode'] == 'cc') {
                            $templateItem['item_mode'] = 'copy';
717
                        }
718
                        $item[] = $roles[$templateItem['item_mode']];
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770

                        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);
                    }
                }
                $entities[$key][] = implode("\n", $list);
            }

            // Users in entity
            $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][] = implode("\n", $users);


            // Document templates
            $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][] = implode("\n", $templates);
        }

        fputcsv($file, $csvHead, $delimiter);

        foreach ($entities as $entity) {
            fputcsv($file, $entity, $delimiter);
        }

        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
771
}