WebdpoFiche.php 36.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
<?php

/**
 * Model WebdpoFiche
 *
 * web-DPO : Outil de gestion de vos traitements dans le cadre de la 
 * réglementation relative à la protection des données personnelles (RGPD)
 * 
 * Copyright (c) Libriciel SCOP (https://www.libriciel.fr/)
 *
 * Licensed under The CeCiLL V2 License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright   Copyright (c) Libriciel SCOP (https://www.libriciel.fr/)
 * @link        https://www.libriciel.fr/web-cil/
 * @since       web-DPO v1.0.0
 * @license     http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html CeCiLL V2 License
 * @version     v1.0.0
 * @package     AppModel
 */

App::uses('AppModel', 'Model');

class WebdpoFiche extends AppModel {

    public $name = 'WebdpoFiche';

    public $useTable = false;
    
    protected $_schema = [];

    public $validate = [
tguillon's avatar
tguillon committed
34
        // ------------------REDACTEUR------------------------------------------
35
        'declarantpersonnenom' => [
36 37 38 39
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
40
        'declarantpersonneemail' => [
41 42 43 44 45 46 47 48 49
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
        'declarantservice' => [
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
50 51 52
        // ---------------------------------------------------------------------
        // ------------------INFORMATION TRAITEMENT-----------------------------
        'outilnom' => [
53 54 55 56
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
57
        'finaliteprincipale' => [
58 59 60 61 62 63 64 65 66
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
        'transfertHorsUe' => [
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
67
        'donneesSensible' => [
68 69 70 71
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
72
        // ---------------------------------------------------------------------
73
        // ------------------INFORMATION TRAITEMENT-----------------------------
74
        'decisionAutomatisee' => [
75 76 77 78
            'notBlank' => [
                'rule' => ['notBlank']
            ]
        ],
79 80
        'descriptionDecisionAutomatisee' => [
            'checkNotBlankIf' => [
81 82 83 84
                'rule' => ['checkNotBlankIf', 'decisionAutomatisee', true, ['Oui']]
            ]
        ],
        // ---------------------------------------------------------------------
85
        // ------------------INFORMATION COMPLEMENTAIRE HORS UE-----------------
86 87 88 89 90 91 92 93 94 95 96 97 98
        'organismeDestinataireHorsUe' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'transfertHorsUe', true, ['Oui']]
            ]
        ],
        'paysDestinataireHorsUe' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'transfertHorsUe', true, ['Oui']]
            ]
        ],
        'typeGarantieHorsUe' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'transfertHorsUe', true, ['Oui']]
99 100 101
            ]
        ],
        // ---------------------------------------------------------------------
102
        // ------------------INFORMATION COMPLEMENTAIRE DONNEE SENSIBLE---------
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        'typeDonneeSensible' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'donneesSensible', true, ['Oui']]
            ]
        ],
        'descriptionDonneeSensible' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'donneesSensible', true, ['Oui']]
            ]
        ],
        'dureeConservationDonneeSensible' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'donneesSensible', true, ['Oui']]
            ]
        ],
        // ---------------------------------------------------------------------
119
        // ------------------------------- AIPD --------------------------------
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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 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 315 316 317 318 319 320 321 322 323 324 325
        // @info: usepia est un champ virtuel nécessaire venant du modèle Formulaire
        'ressources_humaines' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'usepia', true, [true]]
            ]
        ],
        'relation_fournisseurs' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'ressources_humaines', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'ressources_humaines', true, ['Oui']]
            ]
        ],
        'gestion_electoral' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'relation_fournisseurs', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'relation_fournisseurs', true, ['Oui']]
            ]
        ],
        'comites_entreprise' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'gestion_electoral', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'gestion_electoral', true, ['Oui']]
            ]
        ],
        'association' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'comites_entreprise', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'comites_entreprise', true, ['Oui']]
            ]
        ],
        'sante_prise_patient' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'association', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'association', true, ['Oui']]
            ]
        ],
        'avocats' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'sante_prise_patient', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'sante_prise_patient', true, ['Oui']]
            ]
        ],
        'greffiers' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'avocats', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'avocats', true, ['Oui']]
            ]
        ],
        'notaires' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'greffiers', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'greffiers', true, ['Oui']]
            ]
        ],
        'collectivites_affaires_scolaires' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'notaires', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'notaires', true, ['Oui']]
            ]
        ],
        'controles_acces' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'collectivites_affaires_scolaires', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'collectivites_affaires_scolaires', true, ['Oui']]
            ]
        ],
        'ethylotests' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'controles_acces', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'controles_acces', true, ['Oui']]
            ]
        ],
        'sante_medicosociaux' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'ethylotests', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'ethylotests', true, ['Oui']]
            ]
        ],
        'donnees_genetiques' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'sante_medicosociaux', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'sante_medicosociaux', true, ['Oui']]
            ]
        ],
        'profils_personnes_gestion_rh' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'donnees_genetiques', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'donnees_genetiques', true, ['Oui']]
            ]
        ],
        'surveiller_constante_employes' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'profils_personnes_gestion_rh', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'profils_personnes_gestion_rh', true, ['Oui']]
            ]
        ],
        'gestion_alertes_sociale_sanitaire' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'surveiller_constante_employes', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'surveiller_constante_employes', true, ['Oui']]
            ]
        ],
        'gestion_alertes_professionnelle' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'gestion_alertes_sociale_sanitaire', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'gestion_alertes_sociale_sanitaire', true, ['Oui']]
            ]
        ],
        'donnees_sante_registre' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'gestion_alertes_professionnelle', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'gestion_alertes_professionnelle', true, ['Oui']]
            ]
        ],
        'profilage_rupture_contrat' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'donnees_sante_registre', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'donnees_sante_registre', true, ['Oui']]
            ]
        ],
        'mutualises_manquements_rupture_contrat' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'profilage_rupture_contrat', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'profilage_rupture_contrat', true, ['Oui']]
            ]
        ],
        'profilage_donnees_externes' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'mutualises_manquements_rupture_contrat', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'mutualises_manquements_rupture_contrat', true, ['Oui']]
            ]
        ],
        'biometriques' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'profilage_donnees_externes', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'profilage_donnees_externes', true, ['Oui']]
            ]
        ],
        'gestion_logements_sociaux' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'biometriques', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'biometriques', true, ['Oui']]
            ]
        ],
        'accompagnement_social' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'gestion_logements_sociaux', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'gestion_logements_sociaux', true, ['Oui']]
            ]
        ],
        'localisation_large_echelle' => [
            'checkNotBlankIf' => [
                'rule' => ['checkNotBlankIf', 'accompagnement_social', true, ['Non']]
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'accompagnement_social', true, ['Oui']]
            ]
        ],
tguillon's avatar
tguillon committed
326
        // ---------------------------------------------------------------------
327
        'criteres' => [
tguillon's avatar
tguillon committed
328 329
            'checkNotBlankIfMultiple' => [
                'rule' => ['checkMultipleIf', 'localisation_large_echelle', true, ['Non'], ['min' => 1]]
330 331 332 333 334
            ],
            'checkBlankIf' => [
                'rule' => ['checkBlankIf', 'localisation_large_echelle', true, ['Oui']]
            ]
        ],
tguillon's avatar
tguillon committed
335 336 337 338 339 340 341 342
        'traitement_considere_risque' => [
            'checkNotBlankIfCountOptionsChecked' => [
                'rule' => ['checkNotBlankIfCountOptionsChecked', 'criteres', 1]
            ],
            'checkBlankIfCountOptionsChecked' => [
                'rule' => ['checkBlankIfCountOptionsChecked', 'criteres', 2]
            ]
        ],
tguillon's avatar
tguillon committed
343
        // ---------------------------------------------------------------------
344
    ];
345

tguillon's avatar
tguillon committed
346 347
    public function saveWithVirtualFields($data, $champs, $formulaireOptions, $formulaireOLD = false, $actionAdd = false)
    {
348
        $success = true;
349 350
        $Fiche = ClassRegistry::init('Fiche');

351 352
        unset($data['Fiche']['soustraitant']);

tguillon's avatar
tguillon committed
353 354 355 356 357
        // champ virtuel pour la régle de validation
        $data['Fiche']['usepia'] = $formulaireOptions['Formulaire']['usepia'];
        $data['Fiche']['formulaireOLD'] = $formulaireOLD;

        // Sauvegarde BDD Fiches
358 359 360
        $Fiche->create($data['Fiche']);
        $success = false !== $Fiche->save(null, ['atomic' => false]) && $success;

361 362
        // Co-responsable
        $success = false !== $this->coresponsableSave($Fiche->id, $data['Coresponsable'], $data['Fiche']['coresponsable']) && $success;
363
        $data = $this->cleanAndCheckDataCoresponsable($data, $champs);
364

365 366 367
        // Soustraitance
        $success = false !== $this->soustraitanceSave($Fiche->id, $data['Soustraitance'], $data['Fiche']['soustraitance']) && $success;

368 369 370 371
        $newDataChamps = $this->checkDataConditons($data, $champs);
        $data = Hash::extract($newDataChamps, 'data');
        $champs = Hash::extract($newDataChamps, 'champs');

372 373 374
        foreach ($champs as $champ) {
            $details = json_decode(Hash::get($champ, 'Champ.details'));
            if ($details->obligatoire == true) {
375 376 377 378 379 380
                $exit = false;

                if ($champ['Champ']['champ_coresponsable'] === true && $data['Fiche']['coresponsable'] == false ||
                    $champ['Champ']['champ_soustraitant'] === true && $data['Fiche']['soustraitance'] == false
                ) {
                    $exit = true;
381
                    unset($data['Valeur'][$details->name]);
382
                }
383 384 385 386 387

                if ($exit === false) {
                    if (isset($this->validate[$details->name]) == false) {
                        $this->validate[$details->name] = [];
                    }
388

389 390 391 392 393
                    if (in_array(Hash::get($champ, 'Champ.type'), ['checkboxes', 'multi-select'])) {
                        $this->validate[$details->name]['multiple'] = ['rule' => ['multiple', ['min' => 1]]];
                    } else {
                        $this->validate[$details->name]['notBlank'] = ['rule' => ['notBlank']];
                    }
tguillon's avatar
tguillon committed
394
                }
395 396
            }
        }
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

        $fieldsToKeep = [
            'raisonsociale',
            'telephone',
            'fax',
            'adresse',
            'email',
            'sigle',
            'siret',
            'ape',
            'civiliteresponsable',
            'nomresponsable',
            'prenomresponsable',
            'fonctionresponsable',
            'emailresponsable',
            'telephoneresponsable',
            'dpo',
            'numerodpo',
            'fixDpo',
            'portableDpo',
            'emailDpo'
        ];

        if ($actionAdd === false) {
            $fieldsToKeep = array_merge ($fieldsToKeep, [
                'declarantpersonnenom',
                'declarantservice',
                'declarantpersonneportable',
                'declarantpersonneemail',
                'declarantpersonnefix'
            ]);
428 429
        }

430
        $data = $this->cleanupData($data, $champs, $formulaireOLD, $fieldsToKeep);
431
        $data[$this->alias]['usepia'] = $formulaireOptions['Formulaire']['usepia'];
432 433 434

        $this->data[$this->alias] = $data[$this->alias];

435 436 437
        $dynamicValidationErrors = [];
        $originalData = $this->data;
        $originalValidationErrors = $this->validationErrors;
438
        foreach (['horsue', 'donneessensibles'] as $fieldIndex) {
439 440 441 442 443
            if (isset($originalData[$this->alias][$fieldIndex]) === true && empty($originalData[$this->alias][$fieldIndex]) === false) {
                foreach ($originalData[$this->alias][$fieldIndex] as $key => $organisme) {
                    $dynamicData = [
                        $this->alias => $organisme +
                            [
444 445
//                                'coresponsable' => $originalData[$this->alias]['coresponsable']
                                'coresponsable' => $data['Fiche']['coresponsable']
446 447 448
                            ]
                    ];

449 450 451 452 453 454 455 456 457 458
                    // Ajout de la valeur des champs pour les règles de validation dynamiques checkNotBlankIf
                    foreach (array_keys($organisme) as $tmp) {
                        $validate = (array)Hash::get($this->validate, $tmp);
                        foreach ($validate as $validationRule) {
                            if (isset($validationRule['rule'][0]) === true && $validationRule['rule'][0] === 'checkNotBlankIf') {
                                $dynamicData[$this->alias][$validationRule['rule'][1]] = $originalData[$this->alias][$validationRule['rule'][1]];
                            }
                        }
                    }

459 460 461 462 463 464 465 466 467 468 469
                    $this->create($dynamicData);
                    if ($this->validates() !== true) {
                        foreach ($this->validationErrors as $idx => $errors) {
                            $dynamicValidationErrors[$fieldIndex][$key][$idx] = $errors;
                        }
                    }
                }
            }
        }
        $this->data = $originalData;
        $this->validationErrors = $originalValidationErrors;
470
        $this->create([$this->alias => $this->data[$this->alias]]);
471
        $success = $this->validates() && $success && empty($dynamicValidationErrors) === true;
472

473 474 475
        $validationErrors = $Fiche->validationErrors + $this->validationErrors;
        $this->validationErrors = Hash::merge($this->validationErrors, $dynamicValidationErrors);

tguillon's avatar
tguillon committed
476 477 478 479 480 481 482 483 484 485 486 487
        if ($actionAdd === false) {
            $idsToDelete = array_keys($Fiche->Valeur->find('list', [
                'conditions' => [
                    'champ_name !=' => $fieldsToKeep,
                    'fiche_id' => $Fiche->id
                ],
                'contain' => false
            ]));

            if (empty($idsToDelete) == false) {
                $success = $Fiche->Valeur->deleteAll([
                        'Valeur.id' => $idsToDelete
tguillon's avatar
tguillon committed
488
                ]) && $success;
tguillon's avatar
tguillon committed
489
            }
490 491
        }

492 493
        unset($this->data[$this->alias]['usepia']);

494 495 496 497 498
        foreach($this->data[$this->alias] as $fieldName => $value) {
            if ($fieldName != 'formulaire_id' && ($value != '' || in_array($fieldName, $this->validate))) {
                if (is_array($value)) {
                    $value = json_encode($value);
                }
499

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
                $Fiche->Valeur->create([
                    'champ_name' => $fieldName,
                    'fiche_id' => $Fiche->id,
                    'valeur' => $value
                ]);

                $success = false !== $Fiche->Valeur->save(null, ['atomic' => false]) && $success;
                $Fiche->Valeur->validationErrors = [];
            }
        }

        return $success;
    }

    protected function cleanupData(array $data, array $formulaireChamps, bool $formulaireOLD, array $fieldsToDelete)
    {
516 517 518 519
        // @TODO faire cela au moment de la génération
        // Ajout textuel de la coresponsabilité
        if ($data['Fiche']['coresponsable'] == true) {
            $data[$this->alias]['coresponsable'] = 'Oui';
520
        } else {
521 522
            $data[$this->alias]['coresponsable'] = 'Non';
        }
523

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        // @TODO faire cela au moment de la génération
        //Ajout textuel de la sous-traitance
        if ($data['Fiche']['soustraitance'] == true) {
            $data[$this->alias]['soustraitance'] = 'Oui';
        } else {
            $data[$this->alias]['soustraitance'] = 'Non';
        }

        // @TODO faire cela au moment de la génération
        // @TODO passer le champ en column dans fiches
        // Add value textuel en fonction
        if (isset($data[$this->alias]['decisionAutomatisee']) === false) {
            $data[$this->alias]['decisionAutomatisee'] = 'Non';
        }

        // Suppression de la valeur de décrivant la prise de décision automatique si cela n'a pas été indiquer à Oui
        if ($data[$this->alias]['decisionAutomatisee'] === 'Non') {
            unset($data[$this->alias]['descriptionDecisionAutomatisee']);
542 543 544 545 546 547
        }

        /**
         * On supprimer les valeurs des champs du formulaire de la co-reponsabilité si il est indiqué qu'il n'y a pas
         * de co-responsabilité sur le traitement
         */
548 549 550 551 552 553 554 555 556 557 558
//        if ($data['Fiche']['coresponsable'] == false) {
//            foreach ($formulaireChamps as $champ) {
//                if ($champ['Champ']['champ_coresponsable'] === true) {
//                    $champDetails = json_decode(Hash::get($champ, 'Champ.details'));
//
//                    if (isset($data[$this->alias][$champDetails->name])) {
//                        unset($data[$this->alias][$champDetails->name]);
//                    }
//                }
//            }
//        }
559

560 561 562 563
        /**
         * On supprimer les valeurs des champs du formulaire de la sous-traitance si il est indiqué qu'il n'y a pas
         * de sous-traitance sur le traitement
         */
564 565 566 567 568 569 570 571 572 573 574 575 576
//        if ($data['Fiche']['soustraitance'] == false) {
//            foreach ($formulaireChamps as $champ) {
//                if ($champ['Champ']['champ_soustraitant'] === true) {
//                    $champDetails = json_decode(Hash::get($champ, 'Champ.details'));
//
//                    if (isset($data[$this->alias][$champDetails->name])) {
//                        unset($data[$this->alias][$champDetails->name]);
//                    }
//                }
//            }
//        }

        // @TODO passer le champ en column dans fiches
577 578 579 580 581
        // Suppression des valeurs associées aux transfère hors UE si cela n'a pas été indiquer dans les infos générale
        if ($data[$this->alias]['transfertHorsUe'] === 'Non') {
            unset($data[$this->alias]['horsue']);
        }

582
        // @TODO passer le champ en column dans fiches
583 584 585
        // Suppression des valeurs associées aux données sensible si cela n'a pas été indiquer dans les infos générale
        if ($data[$this->alias]['donneesSensible'] === 'Non') {
            unset($data[$this->alias]['donneessensibles']);
586 587
        }

588 589 590 591 592
        // Suppression des sous-finalité vide avant enregistrement en BDD
        if (isset($data[$this->alias]['sousFinalite']) === true) {
            foreach ($data[$this->alias]['sousFinalite'] as $key => $sousFinalite) {
                if (empty($sousFinalite)) {
                    unset($data[$this->alias]['sousFinalite'][$key]);
593
                }
594 595 596
            }
        }

597 598 599
        foreach ($fieldsToDelete as $field) {
            if (isset($data[$this->alias][$field]) == true) {
                unset($data[$this->alias][$field]);
600 601 602
            }
        }

603 604 605
        return ($data);
    }

tguillon's avatar
tguillon committed
606 607 608 609 610 611 612 613 614 615
    public function checkNotBlankIfCountOptionsChecked($checks, $reference, $nbOptionsChecked)
    {
        if (!(is_array($checks) && !empty($reference))) {
            return false;
        }

        $success = true;
        $referenceValue = Hash::get($this->data, "{$this->alias}.{$reference}");

        if (!empty($checks)) {
tguillon's avatar
tguillon committed
616
            if (empty($referenceValue)) {
tguillon's avatar
tguillon committed
617 618 619 620 621 622
                $countOptionsChecked = 0;
            } else {
                $countOptionsChecked = count($referenceValue);
            }

            if ($countOptionsChecked == $nbOptionsChecked) {
tguillon's avatar
tguillon committed
623 624 625
                foreach ($checks as $value) {
                    $success = Validation::notBlank($value) && $success;
                }
tguillon's avatar
tguillon committed
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
            }
        }

        return $success;
    }

    public function checkBlankIfCountOptionsChecked($checks, $reference, $nbOptionsChecked)
    {
        if (!(is_array($checks) && !empty($reference))) {
            return false;
        }

        $success = true;
        $referenceValue = Hash::get($this->data, "{$this->alias}.{$reference}");

        if (!empty($checks)) {
tguillon's avatar
tguillon committed
642 643 644 645 646
            if (empty($referenceValue)) {
                $countOptionsChecked = 0;
            } else {
                $countOptionsChecked = count($referenceValue);
            }
tguillon's avatar
tguillon committed
647 648

            if ($countOptionsChecked >= $nbOptionsChecked) {
tguillon's avatar
tguillon committed
649 650 651
                foreach ($checks as $value) {
                    $success = Validation::blank($value) && $success;
                }
tguillon's avatar
tguillon committed
652 653 654 655 656 657
            }
        }

        return $success;
    }

658 659 660 661 662 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 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    /**
     * On vérifie que les champs dans "data" soit en adéquation avec les conditions créées sur les champs
     *
     * @access protected
     *
     * @param $data
     * @param $champs
     * @return array
     *
     * @created 15/04/2020
     * @version V1.2.0
     * @author Théo GUILLON <theo.guillon@libriciel.coop>
     */
    protected function checkDataConditons($data, $champs)
    {
        foreach ($champs as $key => $champ) {
            $options = json_decode($champ['Champ']['details'], true);

            if (isset($options['conditions']) && !empty($options['conditions'])) {
                $fieldConditions = json_decode($options['conditions'], true);

                foreach ($fieldConditions as $fieldCondition) {
                    if (isset($fieldCondition['ifTheField']) && isset($data[$this->alias][$fieldCondition['ifTheField']])) {
                        $valueCondition = '';

                        if (is_array($data[$this->alias][$fieldCondition['ifTheField']])) {
                            // champ checkbox, multi-select

                            if (in_array(substr($fieldCondition['hasValue'], -1), $data[$this->alias][$fieldCondition['ifTheField']])){
                                $valueCondition = $fieldCondition['mustBe'];
                            } else {
                                $valueCondition = $fieldCondition['ifNot'];
                            }

                        } else {
                            // input, textearea, radio, deroulant

                            if ($data[$this->alias][$fieldCondition['ifTheField']] == $fieldCondition['hasValue']) {
                                $valueCondition = $fieldCondition['mustBe'];
                            } else {
                                $valueCondition = $fieldCondition['ifNot'];
                            }
                        }

                        if ($valueCondition == 'hidden' && isset($data[$this->alias][$fieldCondition['thenTheField']])) {
                            // On supprimer le champ qui doit être cacher par la condition
                            unset($data[$this->alias][$fieldCondition['thenTheField']]);

                            if ($options['obligatoire'] == true) {
                                $options['obligatoire'] = false;
                                $champs[$key]['Champ']['details'] = json_encode($options);
                            }
                        }
                    } else {
                        // On supprimer le champ qui doit être cacher par la condition
                        unset($data[$this->alias][$fieldCondition['thenTheField']]);

                        if ($options['obligatoire'] == true) {
                            $options['obligatoire'] = false;
                            $champs[$key]['Champ']['details'] = json_encode($options);
                        }
                    }
                }
            }
        }

        $newDataChamps = [
            'data' => $data,
            'champs' => $champs
        ];

        return ($newDataChamps);
    }

732 733
    private function coresponsableSave ($fiche_id, $dataCoresponsable, $useCoresponsable)
    {
734 735 736 737 738 739 740 741
        $success = true;
        $Coresponsable = ClassRegistry::init('Coresponsable');

        if (empty($dataCoresponsable['currentCoresponsable'])
            && empty($dataCoresponsable['coresponsables'])
            && $useCoresponsable == true
        ) {
            $Coresponsable->invalidate('coresponsables', 'Champ obligatoire');
742 743 744
            return false;
        }

745 746 747
        if (empty($fiche_id)) {
            return false;
        }
748

749 750
        if ($useCoresponsable == false) {
            $success = $Coresponsable->deleteAll([
751 752
                    'Coresponsable.fiche_id' => $fiche_id
                ]) && $success;
753 754 755 756 757

            return true;
        }

        if (isset($dataCoresponsable['currentCoresponsable']) && !empty($dataCoresponsable['currentCoresponsable']) && !empty($dataCoresponsable['coresponsables'])) {
758 759 760 761 762 763 764 765
            foreach ($dataCoresponsable['currentCoresponsable'] as $currentCoresponsable) {
                if (($key = array_search($currentCoresponsable['responsable_id'], $dataCoresponsable['coresponsables'])) !== false) {
                    unset($dataCoresponsable['coresponsables'][$key]);
                }
            }

            $noDeleteCoresponsable = Hash::extract($dataCoresponsable['currentCoresponsable'], '{n}.coresponsable_id');
            $success = $Coresponsable->deleteAll([
766 767
                'Coresponsable.id !=' => $noDeleteCoresponsable,
                'Coresponsable.fiche_id' => $fiche_id
768 769 770 771 772 773 774 775 776
            ]) && $success;
        } else {
            $success = $Coresponsable->deleteAll([
                'Coresponsable.fiche_id' => $fiche_id
            ]) && $success;
        }

        if ($success === false) {
            return $success;
777 778
        }

779
        if (!empty($dataCoresponsable['coresponsables'])) {
780 781 782 783 784 785 786 787 788 789
            $Responsable = ClassRegistry::init('Responsable');

            foreach ($dataCoresponsable['coresponsables'] as $coresponsable_id) {
                $responsable = $Responsable->find('first', [
                   'conditions' => [
                       'id' => $coresponsable_id
                   ]
                ]);

                $Coresponsable->create([
790 791 792 793 794 795 796 797 798 799 800 801 802 803
                    'fiche_id' => $fiche_id,
                    'responsable_id' => $responsable['Responsable']['id'],
                    'nomcoresponsable' => $responsable['Responsable']['nomresponsable'],
                    'prenomcoresponsable' => $responsable['Responsable']['prenomresponsable'],
                    'fonctioncoresponsable' => $responsable['Responsable']['fonctionresponsable'],
                    'emailcoresponsable' => $responsable['Responsable']['emailresponsable'],
                    'telephonecoresponsable' => $responsable['Responsable']['telephoneresponsable'],
                    'raisonsocialestructure' => $responsable['Responsable']['raisonsocialestructure'],
                    'siretstructure' => $responsable['Responsable']['siretstructure'],
                    'apestructure' => $responsable['Responsable']['apestructure'],
                    'telephonestructure' => $responsable['Responsable']['telephonestructure'],
                    'faxstructure' => $responsable['Responsable']['faxstructure'],
                    'adressestructure' => $responsable['Responsable']['adressestructure'],
                    'emailstructure' => $responsable['Responsable']['emailstructure']
804 805 806 807 808 809 810 811
                ]);
                $success = false !== $Coresponsable->save(null, ['atomic' => false]) && $success;
            }
        }

        return $success;
    }

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
    private function cleanAndCheckDataCoresponsable($data, $champs)
    {
        if ($data['Fiche']['coresponsable'] == false) {
            if (isset($data[$this->alias]['coresponsabilitefields'])) {
                unset($data[$this->alias]['coresponsabilitefields']);
            }

            return $data;
        }

        $arrayCoresponsableFields = [];
        foreach ($champs as $champ) {
            if ($champ['Champ']['champ_coresponsable'] === true && $champ['Champ']['champ_soustraitant'] === false) {
                $arrayCoresponsableFields[] = json_decode($champ['Champ']['details'], true);
            }
        }

829

830
        // On vérifie que les champs suplémentaite du formualaire ne soient pas obligatoire
831 832
        if (isset($data[$this->alias]['coresponsabilitefields']) && !empty($data[$this->alias]['coresponsabilitefields'])) {
            $success = true;
833

834 835 836 837 838 839 840 841
            foreach ($data[$this->alias]['coresponsabilitefields'] as $responsable_id => $coresponsabilitefield) {
                foreach ($arrayCoresponsableFields as $arrayCoresponsableField) {
                    if (empty($coresponsabilitefield[$arrayCoresponsableField['name']]) && $arrayCoresponsableField['obligatoire'] === true) {
                        //@TODO ERREUR champ obligatoire
//                        $this->alias->validationErrors['coresponsabilitefields'][$responsable_id][$arrayCoresponsableField['name']] = 'Champ obligatoire';

                        $success = false;
                    }
842 843 844
                }
            }

845 846 847
            if ($success === false) {
                return $data;
            }
848

849 850
            $data[$this->alias]['coresponsabilitefields'] = json_encode($data[$this->alias]['coresponsabilitefields'], true);
        }
851 852 853 854

        return $data;
    }

855 856
    private function soustraitanceSave ($fiche_id, $dataSoustraitance, $useSoustraitance)
    {
857 858 859 860 861 862 863 864
        $success = true;
        $Soustraitance = ClassRegistry::init('Soustraitance');

        if (empty($dataSoustraitance['currentSoustraitance'])
            && empty($dataSoustraitance['soustraitances'])
            && $useSoustraitance == true
        ) {
            $Soustraitance->invalidate('soustraitances', 'Champ obligatoire');
865 866 867
            return false;
        }

868 869 870
        if (empty($fiche_id)) {
            return false;
        }
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888

        if ($useSoustraitance == false) {
            $success = $Soustraitance->deleteAll([
                'Soustraitance.fiche_id' => $fiche_id
            ]) && $success;

            return true;
        }

        if (isset($dataSoustraitance['currentSoustraitance']) && !empty($dataSoustraitance['currentSoustraitance']) && !empty($dataSoustraitance['soustraitances'])) {
            foreach ($dataSoustraitance['currentSoustraitance'] as $currentSoustraitance) {
                if (($key = array_search($currentSoustraitance['soustraitant_id'], $dataSoustraitance['soustraitances'])) !== false) {
                    unset($dataSoustraitance['soustraitances'][$key]);
                }
            }

            $noDeleteSoustraitance = Hash::extract($dataSoustraitance['currentSoustraitance'], '{n}.soustraitance_id');
            $success = $Soustraitance->deleteAll([
889 890
                'Soustraitance.id !=' => $noDeleteSoustraitance,
                'Soustraitance.fiche_id' => $fiche_id
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
            ]) && $success;
        } else {
            $success = $Soustraitance->deleteAll([
                'Soustraitance.fiche_id' => $fiche_id
            ]) && $success;
        }

        if ($success === false) {
            return $success;
        }

        if (!empty($dataSoustraitance['soustraitances'])) {
            $Soustraitant = ClassRegistry::init('Soustraitant');

            foreach ($dataSoustraitance['soustraitances'] as $soustraitant_id) {
                $soustraitant = $Soustraitant->find('first', [
                    'conditions' => [
                        'id' => $soustraitant_id
                    ]
                ]);

                $Soustraitance->create([
                    'fiche_id' => $fiche_id,
                    'soustraitant_id' => $soustraitant['Soustraitant']['id'],
                    'raisonsociale' => $soustraitant['Soustraitant']['raisonsociale'],
                    'siret' => $soustraitant['Soustraitant']['siret'],
                    'ape' => $soustraitant['Soustraitant']['ape'],
                    'telephone' => $soustraitant['Soustraitant']['telephone'],
                    'fax' => $soustraitant['Soustraitant']['fax'],
                    'adresse' => $soustraitant['Soustraitant']['adresse'],
                    'email' => $soustraitant['Soustraitant']['email'],
                ]);
                $success = false !== $Soustraitance->save(null, ['atomic' => false]) && $success;
            }
        }

        return $success;
    }

930
    public function beforeValidate($options = array()) {
931
//        $this->data = $this->cleanupData($this->data);
932 933 934
        return parent::beforeValidate($options);
    }
}