/[openfoncier]/trunk/obj/instruction.class.php
ViewVC logotype

Diff of /trunk/obj/instruction.class.php

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 8989 by softime, Thu Oct 31 15:09:51 2019 UTC revision 11418 by softime, Mon Feb 7 14:59:54 2022 UTC
# Line 69  class instruction extends instruction_ge Line 69  class instruction extends instruction_ge
69              "groupeInstruction" => 'getGroupeInstruction',              "groupeInstruction" => 'getGroupeInstruction',
70              "title" => 'getTitle',              "title" => 'getTitle',
71              'concerneERP' => 'get_concerne_erp',              'concerneERP' => 'get_concerne_erp',
72    
73                'date_cloture_metier' => 'getDossierDateDecision',
74                'type' => 'getDocumentType',
75                'dossier_autorisation_type_detaille' => 'getDossierAutorisationTypeDetaille',
76                'dossier_instruction_type' => 'getDossierInstructionTypeLibelle',
77                'region' => 'getDossierRegion',
78                'departement' => 'getDossierDepartement',
79                'commune' => 'getDossierCommune',
80                'annee' => 'getDossierAnnee',
81                'division' => 'getDossierDivision',
82                'collectivite' => 'getDossierServiceOrCollectivite',
83          ),          ),
84          "arrete" => array(          "arrete" => array(
85              "numArrete" => "getNumArrete",              "numArrete" => "getNumArrete",
# Line 85  class instruction extends instruction_ge Line 96  class instruction extends instruction_ge
96              "ap_ville" => "getAp_ville",              "ap_ville" => "getAp_ville",
97              "activite" => "getActivite",              "activite" => "getActivite",
98              "dateControleLegalite" => "getDateControleLegalite",              "dateControleLegalite" => "getDateControleLegalite",
99          ),          )
100      );      );
101    
102        /**
103         * Flag pour identifier la reprise de l'instruction d'un dossier.
104         * Le statut de l'état passe de "cloture" à "encours".
105         *
106         * @var boolean
107         */
108        var $di_reopened = null;
109    
110      // {{{ Gestion de la confidentialité des données spécifiques      // {{{ Gestion de la confidentialité des données spécifiques
111            
112      /**      /**
# Line 109  class instruction extends instruction_ge Line 128  class instruction extends instruction_ge
128              "is_editable",              "is_editable",
129              "is_finalizable_without_bypass",              "is_finalizable_without_bypass",
130              "can_user_access_dossier_contexte_modification",              "can_user_access_dossier_contexte_modification",
131                "is_evenement_modifiable",
132          );          );
133          $this->class_actions[1]["portlet"]["libelle"] = _("Modifier");          $this->class_actions[1]["portlet"]["libelle"] = _("Modifier");
134                    
# Line 117  class instruction extends instruction_ge Line 137  class instruction extends instruction_ge
137          $this->class_actions[2]["condition"] = array(          $this->class_actions[2]["condition"] = array(
138              "is_deletable",              "is_deletable",
139              "is_finalizable_without_bypass",              "is_finalizable_without_bypass",
140              "can_user_access_dossier_contexte_modification"              "can_user_access_dossier_contexte_modification",
141                "is_evenement_supprimable",
142          );          );
143          $this->class_actions[2]["portlet"]["libelle"] = _("Supprimer");          $this->class_actions[2]["portlet"]["libelle"] = _("Supprimer");
144    
# Line 165  class instruction extends instruction_ge Line 186  class instruction extends instruction_ge
186                  "is_unfinalizable",                  "is_unfinalizable",
187                  "is_unfinalizable_without_bypass",                  "is_unfinalizable_without_bypass",
188                  "can_user_access_dossier_contexte_modification",                  "can_user_access_dossier_contexte_modification",
189                    "is_not_sent_for_signature",
190              ),              ),
191          );          );
192    
# Line 345  class instruction extends instruction_ge Line 367  class instruction extends instruction_ge
367              "view" => "view_evenement_has_an_edition_json",              "view" => "view_evenement_has_an_edition_json",
368              "permission_suffix" => "consulter",              "permission_suffix" => "consulter",
369          );          );
370    
371            // ACTION - 301 - evenement_has_a_commentaire
372            //
373            $this->class_actions[301] = array(
374                "identifier" => "evenement_has_a_commentaire_json",
375                "view" => "view_evenement_has_a_commentaire_json",
376                "permission_suffix" => "consulter",
377            );
378    
379            // ACTION - 400 - Envoyer en signature
380            // Cet évenement permet d'envoyer le document au parapheur pour signature
381            $this->class_actions[400] = array(
382                "identifier" => "envoyer_a_signature",
383                "portlet" => array(
384                    "libelle" => _("Envoyer à signature"),
385                    "type" => "action-direct-with-confirmation",
386                    "class" => "envoyer_a_signature-16",
387                ),
388                "view" => "formulaire",
389                "method" => "envoyer_a_signature_sans_relecture",
390                "condition" => array(
391                    "can_be_signed",
392                ),
393                "permission_suffix" => "envoyer_a_signature",
394            );
395    
396            // ACTION - 402 - Envoyer en signature avec relecture
397            // Cet évenement permet d'envoyer le document au parapheur pour signature
398            $this->class_actions[402] = array(
399                "identifier" => "envoyer_a_signature_relecture",
400                "portlet" => array(
401                    "libelle" => __("Envoyer à signature avec relecture"),
402                    "type" => "action-direct-with-confirmation",
403                    "class" => "envoyer_a_signature-16",
404                ),
405                "view" => "formulaire",
406                "method" => "envoyer_a_signature_avec_relecture",
407                "condition" => array(
408                    "can_be_signed",
409                    "is_parapheur_relecture_parameter_enabled"
410                ),
411                "permission_suffix" => "envoyer_a_signature",
412            );
413    
414            //
415            $this->class_actions[401] = array(
416                "identifier" => "preview_edition",
417                "view" => "formulaire",
418                "permission_suffix" => "tab",
419            );
420    
421            // ACTION - 410 - Notifier les pétitionnaires (mail ou autre)
422            $this->class_actions[410] = array(
423                "identifier" => "overlay_notification_manuelle",
424                "portlet" => array(
425                    "libelle" => __("Notifier les pétitionnaires"),
426                    "type" => "action-self",
427                    "class" => "notifier_commune-16",
428                ),
429                "condition" => array(
430                    "is_notifiable_by_task_manual",
431                    "is_not_portail_notification_sans_annexe"
432                ),
433                "view" => "view_overlay_notification_manuelle",
434                "permission_suffix" => "modifier",
435            );
436    
437            // ACTION - 410 - Notifier les pétitionnaires (portail citoyen)
438            $this->class_actions[411] = array(
439                "identifier" => "notification_manuelle_portal",
440                "portlet" => array(
441                    "libelle" => __("Notifier les pétitionnaires"),
442                    "type" => "action-direct-with-confirmation",
443                    "class" => "notifier_commune-16",
444                ),
445                "condition" => array(
446                    "is_notifiable_by_task_manual",
447                    "is_portail_notification_sans_annexe"
448                ),
449                "method" => "notifier_demandeur_principal",
450                "permission_suffix" => "modifier",
451            );
452    
453            //
454            $this->class_actions[403] = array(
455                "identifier" => "envoyer_au_controle_de_legalite",
456                "portlet" => array(
457                    "libelle" => __("Envoyer au contrôle de légalité"),
458                    "type" => "action-direct-with-confirmation",
459                    "class" => "envoyer_au_controle_de_legalite-16",
460                ),
461                "view" => "formulaire",
462                "method" => "envoyer_au_controle_de_legalite",
463                "condition" => array(
464                    "can_be_sended_to_cl"
465                ),
466                "permission_suffix" => "envoyer_au_controle_de_legalite",
467            );
468    
469            //
470            $this->class_actions[998] = array(
471                "identifier" => "json_data",
472                "view" => "view_json_data",
473                "permission_suffix" => "consulter",
474            );
475      }      }
476    
477      /**      /**
# Line 357  class instruction extends instruction_ge Line 484  class instruction extends instruction_ge
484              "instruction",              "instruction",
485              "destinataire",              "destinataire",
486              "instruction.evenement",              "instruction.evenement",
487                "instruction.commentaire",
488              "date_evenement",              "date_evenement",
489              "instruction.lettretype",              "instruction.lettretype",
490              "signataire_arrete",              "signataire_arrete",
# Line 415  class instruction extends instruction_ge Line 543  class instruction extends instruction_ge
543              "archive_date_chantier",              "archive_date_chantier",
544              "archive_date_dernier_depot",              "archive_date_dernier_depot",
545              "date_depot",              "date_depot",
546                "date_depot_mairie",
547              "complement5_om_html",              "complement5_om_html",
548              "'' as bible5",              "'' as bible5",
549              "complement6_om_html",              "complement6_om_html",
# Line 458  class instruction extends instruction_ge Line 587  class instruction extends instruction_ge
587              "archive_date_transmission_parquet",              "archive_date_transmission_parquet",
588              "archive_dossier_instruction_type",              "archive_dossier_instruction_type",
589              "archive_date_affichage",              "archive_date_affichage",
590                "pec_metier",
591                "archive_pec_metier",
592                "archive_a_qualifier",
593                "id_parapheur_signature",
594                "statut_signature",
595                "commentaire_signature",
596                "historique_signature",
597                "'' as suivi_notification",
598    
599    
600                "'' as preview_edition",
601                "envoye_cl_platau",
602          );          );
603      }      }
604    
# Line 499  class instruction extends instruction_ge Line 640  class instruction extends instruction_ge
640      }      }
641    
642      /**      /**
643         * CONDITION - is_option_parapheur_relecture_enabled
644         *
645         * Vérifie que l'option de relecture lors de l'envoi en signature est activée.
646         *
647         * @return boolean
648         */
649        function is_parapheur_relecture_parameter_enabled() {
650            //Instanciation de la classe electronicsignature
651            $inst_es = $this->get_electronicsignature_instance();
652            if ($inst_es === false) {
653                return false;
654            }
655    
656            if ($inst_es->get_conf('is_forced_view_files') !== 'true' && $inst_es->get_conf('is_forced_view_files') !== true) {
657                return false;
658            }
659    
660            return true;
661        }
662    
663    
664        /**
665         * CONDITION - is_sent_for_signature
666         *
667         * Vérifie que l'instruction a été envoyé à signature
668         *
669         * @return boolean
670         */
671        function is_sent_for_signature() {
672            // Si un parapheur a été configuré
673            // et que le champ id_parapheur_signature n'est pas vide
674            // que le status est différent de "canceled" ou "expired"
675            // alors l'évènement a été envoyé en signature
676            if ($this->has_connector_electronicsignature() === true
677                && empty($this->getVal("id_parapheur_signature")) === false
678                && ($this->getVal("statut_signature") != "canceled"
679                || $this->getVal("statut_signature") != "expired"
680                || $this->getVal("statut_signature") != "finished")) {
681                //
682                return true;
683            }
684    
685            return false;
686        }
687    
688        /**
689         * CONDITION - is_not_sent_for_signature
690         *
691         * Vérifie que l'instruction n'a pas été envoyé à signature
692         *
693         * @return boolean
694         */
695        function is_not_sent_for_signature() {
696            // Contrôle si l'utilisateur possède un bypass
697            $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_definaliser_bypass");
698            if ($bypass == true) {
699                return true;
700            }
701    
702            return !$this->is_sent_for_signature();
703        }
704    
705    
706        /**
707         * CONDITION - is_signed
708         *
709         * Vérifie que l'instruction a été signé
710         *
711         * @return boolean
712         */
713        function is_signed() {
714            // Si un parapheur a été configuré
715            // et que le champ id_parapheur_signature n'est pas vide
716            //  et que le statut est égal à "finished"
717            // alors le document de l'instruciton à été signé
718            if ($this->has_connector_electronicsignature() === true
719                && empty($this->getVal("id_parapheur_signature")) === false
720                && $this->getVal("statut_signature") == "finished") {
721                //
722                return true;
723            }
724    
725            return false;
726        }
727    
728        function is_sent_to_cl() {
729            // Si l'instruction a une édition
730            // et que l'événement est paramétré pour envoyer le contrôle de légalité
731            // par Plat'AU
732            // et que la date de retour signature est renseignée
733            // et que la date d'envoi au contrôle légalité n'est pas renseignée
734            // et qu'il n'existe pas de task envoi_CL en cours (!= done ou canceled)
735            if ($this->has_an_edition() === true) {
736                $inst_evenement = $this->get_inst_evenement($this->getVal('evenement'));
737                if ($inst_evenement->getVal('envoi_cl_platau') === 't'
738                    || $this->getVal('envoye_cl_platau') === 't') {
739                    //
740                    return true;
741                }
742            }
743            //
744            return false;
745        }
746    
747        /**
748         * CONDITION - is_portail_notification
749         *
750         * Vérifie si la notification est une notification de catégorie portail
751         *
752         * @return boolean
753         */
754        function is_portail_notification_sans_annexe() {
755            $collectiviteDi = $this->get_dossier_instruction_om_collectivite();
756            $ev = $this->get_inst_evenement($this->getVal('evenement'));
757            if (($this->f->get_param_option_notification($collectiviteDi) === null ||
758                $this->f->get_param_option_notification($collectiviteDi) === 'portal')
759                && $ev->getVal('notification') != 'notification_manuelle_annexe'
760                && $ev->getVal('notification') != 'notification_manuelle_annexe_signature_requise'
761            ) {
762                return true;
763            }
764            return false;
765        }
766    
767        /**
768         * CONDITION - is_not_portail_notification
769         *
770         * Vérifie si la notification n'est pas une notification de catégorie portail
771         *
772         * @return boolean
773         */
774        function is_not_portail_notification_sans_annexe() {
775            return (! $this->is_portail_notification_sans_annexe());
776        }
777    
778        /**
779         * CONDITION - can_be_signed
780         *
781         * Vérifie que le document de l'instruction peut être envoyé au parapheur pour signature
782         *
783         * @return boolean
784         */
785        function can_be_signed() {
786            // Instanciation de l'objet signataire_arrete
787            $inst_signataire_arrete = $this->f->get_inst__om_dbform(array(
788                "obj" => "signataire_arrete",
789                "idx" => $this->getVal("signataire_arrete"),
790            ));
791            // Si un parapheur a été configuré, que le document est finalisé, que le signataire
792            // possède une adresse email, on vérifie le champ id_parapheur_signature
793            // S'il est vide l'évènement peut être envoyé en signature
794            // S'il ne l'est pas, alors on vérifie le champ statut_signature
795            // Si la valeur de ce champ est égal à "canceled" ou "expired"
796            // alors l'évènement peut être envoyé en signature
797            if ($this->has_connector_electronicsignature() === true
798                && $this->getVal("om_final_instruction") == 't'
799                && empty($inst_signataire_arrete->getVal('email')) === false) {
800                //
801                if (empty($this->getVal("id_parapheur_signature")) === true
802                    || $this->getVal("statut_signature") == "canceled"
803                    || $this->getVal("statut_signature") == "expired") {
804                    //
805                    return true;
806                }
807            }
808    
809            $this->addToLog(__METHOD__."() has_connector_electronicsignature: ".var_export($this->has_connector_electronicsignature(), true), EXTRA_VERBOSE_MODE);
810            $this->addToLog(__METHOD__."() om_final_instruction: ".var_export($this->getVal("om_final_instruction"), true), EXTRA_VERBOSE_MODE);
811            $this->addToLog(__METHOD__."() email: ".var_export($inst_signataire_arrete->getVal('email'), true), EXTRA_VERBOSE_MODE);
812            $this->addToLog(__METHOD__."() id_parapheur_signature: ".var_export($this->getVal("id_parapheur_signature"), true), EXTRA_VERBOSE_MODE);
813            $this->addToLog(__METHOD__."() statut_signature: ".var_export($this->getVal("statut_signature"), true), EXTRA_VERBOSE_MODE);
814    
815            return false;
816        }
817    
818        /**
819         * CONDITION - has_connector_electronicsignature
820         *
821         * Vérifie qu'un parapheur est paramétré
822         *
823         * @return boolean
824         */
825        function has_connector_electronicsignature() {
826            $inst_es = $this->get_electronicsignature_instance(false);
827            if ($inst_es === false) {
828                return false;
829            }
830            return true;
831        }
832    
833        /**
834         * CONDITION - can_display_parapheur
835         *
836         * Vérifie que le fieldset "Suivi Parapheur" soit affichable
837         *
838         * @return boolean
839         */
840        function can_display_parapheur() {
841            $evenement_id = $this->getVal("evenement");
842            $inst_evenement = $this->get_inst_evenement($evenement_id);
843            if ($this->has_connector_electronicsignature() === true
844                && $inst_evenement->getVal('lettretype') !== ''
845                && $inst_evenement->getVal('lettretype') !== null
846                && (empty($this->getVal("id_parapheur_signature")) === false
847                    || empty($this->getVal("historique_signature")) === false)) {
848                //
849                return true;
850            }
851    
852            return false;
853        }
854    
855        /**
856         * CONDITION - can_display_notification
857         *
858         * Vérifie que le fieldset "Suivi notification" soit affichable
859         *
860         * @return boolean
861         */
862        function can_display_notification() {
863            // Le suivi des notification est affiché si l'événement est notifiable
864            // et si des notifications ont été envoyées
865            $evenement_id = $this->getVal("evenement");
866            $inst_evenement = $this->get_inst_evenement($evenement_id);
867            if ($inst_evenement->getVal('notification') != null &&
868                $inst_evenement->getVal('notification') != '') {
869                // Des notifications ont été envoyé si il existe au moins une notification
870                // liées à l'instruction
871                $idsNotifs = $this->get_instruction_notification($this->getVal($this->clePrimaire));
872                if (isset($idsNotifs) && $idsNotifs !== array()) {
873                    return true;
874                }
875            }
876            return false;
877        }
878    
879        /**
880       * TREATMENT - disable_edition_integrale.       * TREATMENT - disable_edition_integrale.
881       *       *
882       * Cette methode permet de passer la consultation en "lu"       * Cette methode permet de passer la consultation en "lu"
# Line 631  class instruction extends instruction_ge Line 1009  class instruction extends instruction_ge
1009              $form->setType($value, 'hidden');              $form->setType($value, 'hidden');
1010          }          }
1011    
1012            // Les champs historique_signature et statut_signature ne sont pas saisissable dans tous les cas
1013            if ($this->can_display_parapheur() === true && $maj == 3) {
1014                $form->setType('statut_signature', 'selectstatic');
1015                $form->setType('historique_signature', 'jsontotab');
1016                if ($this->getVal('commentaire_signature') == null) {
1017                    $form->setType('commentaire_signature', 'hidden');
1018                } else {
1019                    $form->setType('commentaire_signature', 'hiddenstatic');
1020                }
1021            }
1022    
1023            // Le champ de suivi des notifications n'est pas affichable dans tous les cas
1024            if ($this->can_display_notification() === true && $maj == 3) {
1025                $form->setType('suivi_notification', 'jsontotab');
1026            }
1027    
1028          // MODE AJOUTER          // MODE AJOUTER
1029          if ($this->getParameter('maj') == 0) {          if ($this->getParameter('maj') == 0) {
1030              $form->setType("date_evenement", "date");              $form->setType('commentaire', 'textareahidden');
1031                // Si l'option est active passage du champ date en lecture seule
1032                if ($this->f->is_option_date_evenement_instruction_lecture_seule($collectivite_di) === true) {
1033                    $form->setType("date_evenement", "hiddenstaticdate");
1034                } else {
1035                    $form->setType("date_evenement", "date");
1036                }
1037              if ($this->is_in_context_of_foreign_key("evenement", $this->getParameter("retourformulaire"))) {              if ($this->is_in_context_of_foreign_key("evenement", $this->getParameter("retourformulaire"))) {
1038                  $form->setType("evenement", "selecthiddenstatic");                  $form->setType("evenement", "selecthiddenstatic");
1039              } else {              } else {
# Line 651  class instruction extends instruction_ge Line 1051  class instruction extends instruction_ge
1051    
1052          // MODE MODIFIER          // MODE MODIFIER
1053          if ($this->getParameter('maj') == 1) {          if ($this->getParameter('maj') == 1) {
1054              $form->setType("date_evenement", "date");              // Si l'option est active passage du champ date en lecture seule
1055                if ($this->f->is_option_date_evenement_instruction_lecture_seule($collectivite_di) === true) {
1056                    $form->setType("date_evenement", "hiddenstaticdate");
1057                } else {
1058                    $form->setType("date_evenement", "date");
1059                }
1060              $form->setType("evenement", "selecthiddenstatic");              $form->setType("evenement", "selecthiddenstatic");
1061              if ($this->has_an_edition() === true) {              if ($this->has_an_edition() === true) {
1062                  $form->setType('lettretype', 'hiddenstatic');                  $form->setType('lettretype', 'hiddenstatic');
# Line 679  class instruction extends instruction_ge Line 1084  class instruction extends instruction_ge
1084                      $form->setType('btn_refresh', 'httpclickbutton');                      $form->setType('btn_refresh', 'httpclickbutton');
1085                      $form->setType('btn_preview', 'httpclickbutton');                      $form->setType('btn_preview', 'httpclickbutton');
1086                      $form->setType('btn_redaction', 'httpclickbutton');                      $form->setType('btn_redaction', 'httpclickbutton');
1087                      $form->setType('live_preview', 'pdf');                      $form->setType('live_preview', 'previsualiser_pdf');
1088                  }                  }
1089    
1090                  // necessaire pour calcul de date en modification                  // necessaire pour calcul de date en modification
# Line 693  class instruction extends instruction_ge Line 1098  class instruction extends instruction_ge
1098                      //                      //
1099                      $form->setType('date_envoi_signature', 'date');                      $form->setType('date_envoi_signature', 'date');
1100                      $form->setType('date_retour_signature', 'date');                      $form->setType('date_retour_signature', 'date');
1101                        if ($this->is_sent_for_signature() === true
1102                            && $this->is_signed() === true) {
1103                            //
1104                            $form->setType("date_envoi_signature", "datereadonly");
1105                            $form->setType("date_retour_signature", "datereadonly");
1106                        }
1107                      $form->setType('date_envoi_rar', 'date');                      $form->setType('date_envoi_rar', 'date');
1108                      $form->setType('date_retour_rar', 'date');                      $form->setType('date_retour_rar', 'date');
1109                      $form->setType('date_envoi_controle_legalite', 'date');                      $form->setType('date_envoi_controle_legalite', 'date');
1110                        if ($this->is_sent_to_cl() === true) {
1111                            $form->setType("date_envoi_controle_legalite", "datereadonly");
1112                        }
1113                      $form->setType('date_retour_controle_legalite', 'date');                      $form->setType('date_retour_controle_legalite', 'date');
1114                      $form->setType('date_finalisation_courrier', 'date');                      $form->setType('date_finalisation_courrier', 'date');
1115                  }                  }
1116              }              }
1117          }          }
1118    
1119          // MODE CONSULTER + SUPPRIMER + SUIVI DES DATES 125          // MODE CONSULTER + SUPPRIMER + SUIVI DES DATES 125 + NOTIFICATION MANUELLE
1120          if ($this->getParameter('maj') == 3          if ($this->getParameter('maj') == 3
1121              || $this->getParameter('maj') == 2              || $this->getParameter('maj') == 2
1122              || $this->getParameter('maj') == 125) {              || $this->getParameter('maj') == 125
1123                || $this->getParameter('maj') == 410) {
1124              //              //
1125              $form->setType("date_evenement", "datestatic");              $form->setType("date_evenement", "datestatic");
1126              $form->setType("evenement", "selecthiddenstatic");              $form->setType("evenement", "selecthiddenstatic");
# Line 718  class instruction extends instruction_ge Line 1133  class instruction extends instruction_ge
1133                      $form->setType('om_final_instruction_utilisateur', 'hidden');                      $form->setType('om_final_instruction_utilisateur', 'hidden');
1134                  }                  }
1135              }              }
1136                if ($this->evenement_has_a_commentaire($this->getVal('evenement')) === true ) {
1137                    $form->setType('commentaire', 'textareastatic');
1138                }
1139          }          }
1140    
1141          // MODE CONSULTER + SUPPRIMER          // MODE CONSULTER + SUPPRIMER + NOTIFICATION MANUELLE
1142          if ($this->getParameter('maj') == 3 || $this->getParameter('maj') == 2) {          if ($this->getParameter('maj') == 3
1143                || $this->getParameter('maj') == 2
1144                || $this->getParameter('maj') == 410) {
1145                // Si il n'y a pas de lettre type (edition) associé à l'événement
1146                // les dates de suivi ne sont pas affichée
1147              if ($this->has_an_edition() === true) {              if ($this->has_an_edition() === true) {
1148                    $form->setType('date_envoi_signature', 'datestatic');
1149                    $form->setType('date_retour_signature', 'datestatic');
1150                    $form->setType('date_envoi_rar', 'datestatic');
1151                    $form->setType('date_retour_rar', 'datestatic');
1152                    $form->setType('date_envoi_controle_legalite', 'datestatic');
1153                    $form->setType('date_retour_controle_legalite', 'datestatic');
1154                    $form->setType('date_finalisation_courrier', 'datestatic');
1155                  if ($this->getVal("flag_edition_integrale") == "t") {                  if ($this->getVal("flag_edition_integrale") == "t") {
1156                      $form->setType("titre_om_htmletat", "htmlstatic");                      $form->setType("titre_om_htmletat", "htmlstatic");
1157                      $form->setType("corps_om_htmletatex", "htmlstatic");                      $form->setType("corps_om_htmletatex", "htmlstatic");
# Line 733  class instruction extends instruction_ge Line 1162  class instruction extends instruction_ge
1162                      $form->setType("complement4_om_html", "htmlstatic");                      $form->setType("complement4_om_html", "htmlstatic");
1163                  }                  }
1164              }              }
             $form->setType('date_envoi_signature', 'datestatic');  
             $form->setType('date_retour_signature', 'datestatic');  
             $form->setType('date_envoi_rar', 'datestatic');  
             $form->setType('date_retour_rar', 'datestatic');  
             $form->setType('date_envoi_controle_legalite', 'datestatic');  
             $form->setType('date_retour_controle_legalite', 'datestatic');  
             $form->setType('date_finalisation_courrier', 'datestatic');  
1165          }          }
1166    
1167          // MODE SUIVI DES DATES 125          // MODE SUIVI DES DATES 125
# Line 748  class instruction extends instruction_ge Line 1170  class instruction extends instruction_ge
1170              $form->setType('om_final_instruction_utilisateur', 'hiddenstatic');              $form->setType('om_final_instruction_utilisateur', 'hiddenstatic');
1171              $form->setType('date_envoi_signature', 'date');              $form->setType('date_envoi_signature', 'date');
1172              $form->setType('date_retour_signature', 'date');              $form->setType('date_retour_signature', 'date');
1173                if ($this->is_sent_for_signature() === true
1174                    || $this->is_signed() === true) {
1175                    //
1176                    $form->setType("date_envoi_signature", "datereadonly");
1177                    $form->setType("date_retour_signature", "datereadonly");
1178                }
1179              $form->setType('date_envoi_rar', 'date');              $form->setType('date_envoi_rar', 'date');
1180              $form->setType('date_retour_rar', 'date');              $form->setType('date_retour_rar', 'date');
1181              $form->setType('date_envoi_controle_legalite', 'date');              $form->setType('date_envoi_controle_legalite', 'date');
1182                if ($this->is_sent_to_cl() === true) {
1183                    $form->setType("date_envoi_controle_legalite", "datereadonly");
1184                }
1185              $form->setType('date_retour_controle_legalite', 'date');              $form->setType('date_retour_controle_legalite', 'date');
1186              $form->setType('date_finalisation_courrier', 'date');              $form->setType('date_finalisation_courrier', 'date');
1187          }          }
1188    
1189            if ($maj == 401) {
1190                foreach ($this->champs as $champ) {
1191                    $form->setType($champ, 'hidden');
1192                }
1193                $form->setType('preview_edition', 'previsualiser');
1194            }
1195      }      }
1196    
1197      function setOnchange(&$form,$maj){      function setOnchange(&$form,$maj){
# Line 761  class instruction extends instruction_ge Line 1199  class instruction extends instruction_ge
1199    
1200          // MODE AJOUTER          // MODE AJOUTER
1201          if ($this->getParameter('maj') == 0) {          if ($this->getParameter('maj') == 0) {
1202              $form->setOnchange("evenement", "manage_instruction_evenement_lettretype(this.value, '".addslashes($this->getParameter('idxformulaire'))."');");              $form->setOnchange(
1203                    "evenement",
1204                    "manage_instruction_evenement_lettretype(this.value, '".addslashes($this->getParameter('idxformulaire'))."');
1205                    manage_instruction_evenement_commentaire(this.value, '".addslashes($this->getParameter('idxformulaire'))."');"
1206                );
1207          }          }
1208      }      }
1209    
# Line 782  class instruction extends instruction_ge Line 1224  class instruction extends instruction_ge
1224          echo json_encode($json_return);          echo json_encode($json_return);
1225      }      }
1226    
1227        function evenement_has_a_commentaire($evenement_id) {
1228            $evenement = $this->get_inst_evenement($evenement_id);
1229            return $this->get_boolean_from_pgsql_value($evenement->getVal('commentaire'));
1230        }
1231    
1232        function view_evenement_has_a_commentaire_json() {
1233            $json_return = array(
1234                "commentaire" => $this->evenement_has_a_commentaire($this->f->get_submitted_get_value('evenement_id'))
1235            );
1236            echo json_encode($json_return);
1237        }
1238    
1239    
1240        /**
1241         * CONDITION - can_be_sended_to_cl
1242         *
1243         * Vérifie que le contrôle de légalité est disponible
1244         *
1245         * @return boolean
1246         */
1247        function can_be_sended_to_cl() {
1248            // Si l'instruction a une édition
1249            // et que l'événement est paramétré pour envoyer le contrôle de légalité
1250            // par Plat'AU
1251            // et que la date de retour signature est renseignée
1252            // et que la date d'envoi au contrôle légalité n'est pas renseignée
1253            // et qu'il n'existe pas de task envoi_CL en cours (!= done ou canceled)
1254            if ($this->has_an_edition() === true) {
1255                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
1256                $inst_evenement = $this->get_inst_evenement($this->getVal('evenement'));
1257                if ($inst_evenement->getVal('envoi_cl_platau') === 't'
1258                    && empty($this->getVal('date_retour_signature')) === false
1259                    && empty($this->getVal('date_envoi_controle_legalite')) === true
1260                    && $this->getVal('envoye_cl_platau') === 'f'
1261                    && $this->f->is_type_dossier_platau($inst_di->getVal('dossier_autorisation')) === true
1262                    && $inst_di->getVal('etat_transmission_platau') !== 'jamais_transmissible') {
1263                    //
1264                    return true;
1265                }
1266            }
1267            //
1268            return false;
1269        }
1270    
1271      /**      /**
1272       *       *
1273       * @return string       * @return string
# Line 789  class instruction extends instruction_ge Line 1275  class instruction extends instruction_ge
1275      function get_var_sql_forminc__sql_signataire_arrete() {      function get_var_sql_forminc__sql_signataire_arrete() {
1276          return "SELECT          return "SELECT
1277              signataire_arrete.signataire_arrete,              signataire_arrete.signataire_arrete,
1278              CONCAT(signataire_arrete.prenom, ' ', signataire_arrete.nom)              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1279              FROM ".DB_PREFIXE."signataire_arrete              FROM ".DB_PREFIXE."signataire_arrete
1280              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)))              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1281              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";
# Line 802  class instruction extends instruction_ge Line 1288  class instruction extends instruction_ge
1288      function get_var_sql_forminc__sql_signataire_arrete_by_id() {      function get_var_sql_forminc__sql_signataire_arrete_by_id() {
1289          return "SELECT          return "SELECT
1290              signataire_arrete.signataire_arrete,              signataire_arrete.signataire_arrete,
1291              CONCAT(signataire_arrete.prenom, ' ', signataire_arrete.nom)              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1292              FROM ".DB_PREFIXE."signataire_arrete              FROM ".DB_PREFIXE."signataire_arrete
1293              WHERE signataire_arrete.signataire_arrete = <idx>";              WHERE signataire_arrete.signataire_arrete = <idx>";
1294      }      }
# Line 814  class instruction extends instruction_ge Line 1300  class instruction extends instruction_ge
1300      function get_var_sql_forminc__sql_signataire_arrete_by_di() {      function get_var_sql_forminc__sql_signataire_arrete_by_di() {
1301          return "SELECT          return "SELECT
1302              signataire_arrete.signataire_arrete,              signataire_arrete.signataire_arrete,
1303              CONCAT(signataire_arrete.prenom, ' ', signataire_arrete.nom)              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1304              FROM ".DB_PREFIXE."signataire_arrete              FROM ".DB_PREFIXE."signataire_arrete
1305              LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite              LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1306              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)))              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
# Line 829  class instruction extends instruction_ge Line 1315  class instruction extends instruction_ge
1315      function get_var_sql_forminc__sql_signataire_arrete_defaut() {      function get_var_sql_forminc__sql_signataire_arrete_defaut() {
1316          return "SELECT          return "SELECT
1317              signataire_arrete.signataire_arrete,              signataire_arrete.signataire_arrete,
1318              CONCAT(signataire_arrete.prenom, ' ', signataire_arrete.nom)              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1319              FROM ".DB_PREFIXE."signataire_arrete              FROM ".DB_PREFIXE."signataire_arrete
1320              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE))) AND signataire_arrete.defaut IS TRUE              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE))) AND signataire_arrete.defaut IS TRUE
1321              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";
# Line 842  class instruction extends instruction_ge Line 1328  class instruction extends instruction_ge
1328      function get_var_sql_forminc__sql_signataire_arrete_defaut_by_di() {      function get_var_sql_forminc__sql_signataire_arrete_defaut_by_di() {
1329          return "SELECT          return "SELECT
1330              signataire_arrete.signataire_arrete,              signataire_arrete.signataire_arrete,
1331              CONCAT(signataire_arrete.prenom, ' ', signataire_arrete.nom)              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1332              FROM ".DB_PREFIXE."signataire_arrete              FROM ".DB_PREFIXE."signataire_arrete
1333              LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite              LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1334              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE))) AND signataire_arrete.defaut IS TRUE              WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE))) AND signataire_arrete.defaut IS TRUE
# Line 1027  class instruction extends instruction_ge Line 1513  class instruction extends instruction_ge
1513              1 => array(_('Rédaction par compléments'), _('Rédaction libre'), ),              1 => array(_('Rédaction par compléments'), _('Rédaction libre'), ),
1514          );          );
1515          $form->setSelect('flag_edition_integrale', $content);          $form->setSelect('flag_edition_integrale', $content);
1516    
1517            $contenu = array();
1518            foreach(array('waiting', 'in_progress', 'canceled', 'expired', 'finished') as $value) {
1519                $contenu[0][] = $value;
1520                $contenu[1][] = $this->get_trad_for_statut($value);
1521            }
1522            $form->setSelect('statut_signature', $contenu);
1523    
1524    
1525            if ($maj == 401) {
1526                $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));
1527                $form->setSelect('preview_edition', array(
1528                    'base64' => base64_encode($file['file_content']),
1529                    'mimetype' => $file['metadata']['mimetype'],
1530                    'label' => 'instruction_'.$this->getVal($this->clePrimaire),
1531                    'href' => sprintf(
1532                        '../app/index.php?module=form&snippet=file&obj=instruction&champ=om_fichier_instruction&id=%1$s',
1533                        $this->getVal($this->clePrimaire)
1534                    )
1535                ));
1536            }
1537      }      }
1538    
1539      function cleSecondaire($id, &$dnu1 = null, $val = array(), $dnu2 = null) {      function cleSecondaire($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
1540          //          //
1541          parent::cleSecondaire($id, $dnu1, $val);          // Vérifie uniquementla cle secondaire : demande
1542            $this->rechercheTable($this->f->db, "demande", "instruction_recepisse", $id);
1543                    
1544          $id = $this->getVal($this->clePrimaire);          $id = $this->getVal($this->clePrimaire);
1545    
# Line 1226  class instruction extends instruction_ge Line 1734  class instruction extends instruction_ge
1734              $form->setVal("btn_preview", "show_instr_preview()");              $form->setVal("btn_preview", "show_instr_preview()");
1735              $form->setVal("btn_redaction", "show_instr_redaction()");              $form->setVal("btn_redaction", "show_instr_redaction()");
1736          }          }
1737    
1738            if ($maj == 3
1739                && $this->can_display_notification()
1740            ) {
1741                $form->setVal("suivi_notification", $this->get_json_suivi_notification());
1742            }
1743      }      }
1744    
1745      function setLayout(&$form, $maj){      function setLayout(&$form, $maj){
# Line 1248  class instruction extends instruction_ge Line 1762  class instruction extends instruction_ge
1762                    
1763          $form->setBloc('date_retour_controle_legalite','F');          $form->setBloc('date_retour_controle_legalite','F');
1764    
1765            $form->setBloc('statut_signature','D');
1766            $form->setFieldset('statut_signature','D','Suivi Parapheur');
1767            $form->setBloc('commentaire_signature','F');
1768            $form->setBloc('historique_signature','D');
1769            $form->setFieldset('historique_signature', 'DF', __("Historique"), "collapsible, startClosed");
1770            $form->setBloc('historique_signature','F');
1771            $form->setFieldset('historique_signature','F');
1772    
1773            $form->setFieldset('suivi_notification', 'D', __("Suivi notification"), "collapsible");
1774            $form->setFieldset('suivi_notification','F');
1775    
1776          if ($maj == 1) {          if ($maj == 1) {
1777              // Récupère la collectivité du dossier d'instruction              // Récupère la collectivité du dossier d'instruction
1778              $collectivite_di = $this->get_dossier_instruction_om_collectivite();              $collectivite_di = $this->get_dossier_instruction_om_collectivite();
# Line 1324  class instruction extends instruction_ge Line 1849  class instruction extends instruction_ge
1849          $form->setLib('om_final_instruction_utilisateur', _("finalise par"));          $form->setLib('om_final_instruction_utilisateur', _("finalise par"));
1850          $form->setLib('date_envoi_rar', __("date_envoi_ar"));          $form->setLib('date_envoi_rar', __("date_envoi_ar"));
1851          $form->setLib('date_retour_rar', __("date_notification"));          $form->setLib('date_retour_rar', __("date_notification"));
1852            $form->setLib('statut_signature', __("statut"));
1853            $form->setLib('commentaire_signature', __("commentaire"));
1854            $form->setLib('historique_signature', '');
1855            $form->setLib('suivi_notification', '');
1856            $form->setLib('preview_edition', "");
1857    
1858          // Ajout d'une infobulle d'aide lorsque le formulaire est en mode          // Ajout d'une infobulle d'aide lorsque le formulaire est en mode
1859          // ajout et que l'option de rédaction libre est activée sur la          // ajout et que l'option de rédaction libre est activée sur la
# Line 1370  class instruction extends instruction_ge Line 1900  class instruction extends instruction_ge
1900           * - delai_notification           * - delai_notification
1901           * - lettretype           * - lettretype
1902           * - autorite_competente           * - autorite_competente
1903             * - pec_metier
1904           * - complement_om_html           * - complement_om_html
1905           * - complement2_om_html           * - complement2_om_html
1906           * - complement3_om_html           * - complement3_om_html
# Line 1432  class instruction extends instruction_ge Line 1963  class instruction extends instruction_ge
1963              }              }
1964              // Récupération de la valeur de la lettre type              // Récupération de la valeur de la lettre type
1965              $this->valF['lettretype']=$row['lettretype'];              $this->valF['lettretype']=$row['lettretype'];
1966                // Récupération de la valeur de la prise en compte métier
1967                // si la prise en compte métier est paramétrée dans l'événement
1968                $this->valF['pec_metier'] = NULL;
1969                if(isset($row['pec_metier']) === true and empty($row['pec_metier']) === false) {
1970                    $this->valF['pec_metier'] = $row['pec_metier'];
1971                }
1972          }          }
1973          // Récupération de toutes les valeurs du dossier d'instruction en cours          // Récupération de toutes les valeurs du dossier d'instruction en cours
1974          $sql = "SELECT * FROM ".DB_PREFIXE."dossier          $sql = "SELECT * FROM ".DB_PREFIXE."dossier
# Line 1781  class instruction extends instruction_ge Line 2318  class instruction extends instruction_ge
2318          );          );
2319          // Tableau des champs de type booléen          // Tableau des champs de type booléen
2320          $rule_type_bool = array(          $rule_type_bool = array(
2321                "regle_a_qualifier",
2322                "regle_incompletude",
2323                "regle_incomplet_notifie",
2324                "regle_evenement_suivant_tacite_incompletude",
2325          );          );
2326          // Tableau des champs spécifiques          // Tableau des champs spécifiques
2327          $rule_type_specific = array(          $rule_type_specific = array(
# Line 1788  class instruction extends instruction_ge Line 2329  class instruction extends instruction_ge
2329              "regle_etat",              "regle_etat",
2330              "regle_accord_tacite",              "regle_accord_tacite",
2331              "regle_avis",              "regle_avis",
2332                "regle_pec_metier",
2333                "regle_etat_pendant_incompletude",
2334          );          );
2335          // Tableau des champs de données techniques          // Tableau des champs de données techniques
2336          $rule_type_technical_data = array(          $rule_type_technical_data = array(
# Line 1827  class instruction extends instruction_ge Line 2370  class instruction extends instruction_ge
2370    
2371          // Si c'est un type spécifique ou booléen alors il n'a qu'un opérande          // Si c'est un type spécifique ou booléen alors il n'a qu'un opérande
2372          // Récupère directement la valeur de l'opérande          // Récupère directement la valeur de l'opérande
2373          if ($type === 'specific' || $type === 'bool') {          if ($type === 'specific') {
2374              //              //
2375              return $this->get_value_for_rule($rule);              return $this->get_value_for_rule($rule);
2376          }          }
# Line 1902  class instruction extends instruction_ge Line 2445  class instruction extends instruction_ge
2445              // Retourne la chaîne de caractère              // Retourne la chaîne de caractère
2446              return $res_text;              return $res_text;
2447          }          }
2448          if ($type === 'simple') {          if ($type === 'simple' || $type === 'bool') {
2449              // Retourne la valeur du champs rule              // Retourne la valeur du champs rule
2450              return $rule;              return $rule;
2451          }          }
# Line 1995  class instruction extends instruction_ge Line 2538  class instruction extends instruction_ge
2538          $inst_di = $this->get_inst_dossier($this->valF['dossier']);          $inst_di = $this->get_inst_dossier($this->valF['dossier']);
2539          // Instance de la classe evenement          // Instance de la classe evenement
2540          $inst_evenement = $this->get_inst_evenement($this->valF['evenement']);          $inst_evenement = $this->get_inst_evenement($this->valF['evenement']);
2541            // Instance de l'état courant du dossier d'instruction
2542            $inst_current_etat = $this->f->get_inst__om_dbform(array(
2543                "obj" => "etat",
2544                "idx" => $inst_di->get_id_etat(),
2545            ));
2546    
2547          /**          /**
2548           * Mise à jour des valeurs du dossier en fonction des valeurs calculées           * Mise à jour des valeurs du dossier en fonction des valeurs calculées
# Line 2002  class instruction extends instruction_ge Line 2550  class instruction extends instruction_ge
2550           */           */
2551          // état de complétude actuel du dossier          // état de complétude actuel du dossier
2552          $incompletude = ($inst_di->getVal('incompletude') == 't' ? true : false);          $incompletude = ($inst_di->getVal('incompletude') == 't' ? true : false);
2553            // L'événement suivant tacite paramétré est destiné à la gestion de l'incomplétude
2554            $ev_suiv_tacite_incompletude = false;
2555          // Initialisation          // Initialisation
2556          $valF = "";          $valF = array();
2557          $valF_dt = "";          $valF_dt = array();
2558          //          //
         if($incompletude === FALSE) {  
             // Si l'événement d'instruction est de type incompletude  
             if($inst_evenement->getVal('type') == "incompletude") {  
                 // On marque le dossier en incomplétude pour application des actions  
                 $incompletude = TRUE;  
                 // Set du flag incomplétude de la table dossier  
                 $valF['incompletude'] = TRUE;  
                 // Enregistrement de l'état dans la variable provisoire  
                 $valF['etat_pendant_incompletude'] = $this->valF['archive_etat'];  
             }  
         } else {  
             // Si l'evenement d'instruction est de type retour ou contient une  
             // decision, on sort d'incomplétude  
             if($inst_evenement->getVal('type') == "retour" OR  
                $inst_evenement->getVal('avis_decision') != NULL) {  
                 // On enlève la marque d'incomplétude pour application des actions  
                 $incompletude = FALSE;  
                 // On enlève le flag d'incomplétude sur l'enregistrement de la table dossier  
                 $valF['incompletude'] = FALSE;  
                 $valF['incomplet_notifie'] = FALSE;  
                  // Restauration de l'état depuis l'état provisoire  
                 $valF['etat'] = $this->valF['archive_etat_pendant_incompletude'];  
                 // On vide la variable provisoire ainsi que le délai de complétude  
                 // et la date limite de complétude  
                 $valF['etat_pendant_incompletude'] = NULL;  
                 $valF['delai_incompletude'] = NULL;  
                 $valF['date_limite_incompletude'] = NULL;  
                 $valF['evenement_suivant_tacite_incompletude'] = NULL;  
             }  
         }  
2559          // Récupération des paramètres de l'action          // Récupération des paramètres de l'action
2560          $sql = "SELECT * FROM ".DB_PREFIXE."action          $sql = "SELECT * FROM ".DB_PREFIXE."action
2561          WHERE action='".$this->valF['action']."'";          WHERE action='".$this->valF['action']."'";
# Line 2096  class instruction extends instruction_ge Line 2616  class instruction extends instruction_ge
2616                  $valF['autorite_competente'] = $this->regle($row['regle_autorite_competente'], 'regle_autorite_competente');                  $valF['autorite_competente'] = $this->regle($row['regle_autorite_competente'], 'regle_autorite_competente');
2617              }              }
2618              if ($row['regle_etat'] != '') {              if ($row['regle_etat'] != '') {
2619                  // Si on est dans le cas général ou qu'on est en incomplétude et                  $valF['etat'] = $this->regle($row['regle_etat'], 'regle_etat');
                 // qu'on a un événement de type incomplétude alors : on stocke  
                 // l'état dans la variable courante  
                 if ($incompletude == FALSE OR $inst_evenement->getVal('type') == "incompletude") {  
                     $valF['etat'] = $this->regle($row['regle_etat'], 'regle_etat');  
                 } else {  
                     $valF['etat_pendant_incompletude'] = $this->regle($row['regle_etat'], 'regle_etat');  
                 }  
2620              }              }
2621              if ($row['regle_date_cloture_instruction'] !== '') {              if ($row['regle_date_cloture_instruction'] !== '') {
2622                  $valF['date_cloture_instruction'] = $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');                  $valF['date_cloture_instruction'] = $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');
# Line 2152  class instruction extends instruction_ge Line 2665  class instruction extends instruction_ge
2665                  //                  //
2666                  $valF['date_affichage'] = $this->regle($row['regle_date_affichage'], 'regle_date_affichage');                  $valF['date_affichage'] = $this->regle($row['regle_date_affichage'], 'regle_date_affichage');
2667              }              }
2668                //
2669                if ($row['regle_pec_metier'] != '') {
2670                    $valF['pec_metier'] = $this->regle($row['regle_pec_metier'], 'regle_pec_metier');
2671                }
2672                if ($row['regle_a_qualifier'] != '') {
2673                    $valF['a_qualifier'] = $this->regle($row['regle_a_qualifier'], 'regle_a_qualifier');
2674                }
2675                //
2676                if ($row['regle_incompletude'] != '') {
2677                    $valF['incompletude'] = $this->regle($row['regle_incompletude'], 'regle_incompletude');
2678                }
2679                if ($row['regle_incomplet_notifie'] != '') {
2680                    $valF['incomplet_notifie'] = $this->regle($row['regle_incomplet_notifie'], 'regle_incomplet_notifie');
2681                }
2682                if ($row['regle_etat_pendant_incompletude'] != '') {
2683                    $valF['etat_pendant_incompletude'] = $this->regle($row['regle_etat_pendant_incompletude'], 'regle_etat_pendant_incompletude');
2684                }
2685                if ($row['regle_evenement_suivant_tacite_incompletude'] != '') {
2686                    $resti = $this->regle($row['regle_evenement_suivant_tacite_incompletude'], 'regle_evenement_suivant_tacite_incompletude');
2687                    if (strtolower($resti) === 't' || strtolower($resti) === 'true') {
2688                        $ev_suiv_tacite_incompletude = true;
2689                    }
2690                }
2691          }          }
2692    
2693          // Si l'événement a un événement suivant tacite          // Si l'événement a un événement suivant tacite
2694          if($inst_evenement->getVal('evenement_suivant_tacite') != '') {          if($inst_evenement->getVal('evenement_suivant_tacite') != '') {
2695              // Si le DI n'est pas en incomplétude, l'événement tacite est stocké              // En fonction de l'action de l'événement, l'événement suivant tacite ne sera
2696              // dans le champ evenement_suivant_tacite du dossier              // pas associé de le même façon au dossier d'instruction
2697              if ($incompletude == false OR $inst_evenement->getVal('type') != "incompletude") {              if ($ev_suiv_tacite_incompletude === false) {
                 //  
2698                  $valF['evenement_suivant_tacite'] = $inst_evenement->getVal('evenement_suivant_tacite');                  $valF['evenement_suivant_tacite'] = $inst_evenement->getVal('evenement_suivant_tacite');
2699              } else {              }
2700                  // Sinon l'événement tacite est stocké dans le champ              if ($ev_suiv_tacite_incompletude === true) {
                 // evenement_suivant_tacite_incompletude du dossier  
2701                  $valF['evenement_suivant_tacite_incompletude'] = $inst_evenement->getVal('evenement_suivant_tacite');                  $valF['evenement_suivant_tacite_incompletude'] = $inst_evenement->getVal('evenement_suivant_tacite');
2702              }              }
2703          }          }
2704          // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement          // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement
2705          if ($valF_dt != "") {          if (count($valF_dt) > 0) {
2706              $dt_id = $this->getDonneesTechniques();              $dt_id = $this->getDonneesTechniques();
2707              // On met à jour le dossier              // On met à jour le dossier
2708              $cle = " donnees_techniques='".$dt_id."'";              $cle = " donnees_techniques='".$dt_id."'";
# Line 2181  class instruction extends instruction_ge Line 2715  class instruction extends instruction_ge
2715              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
2716          }          }
2717          // Si des valeurs ont été calculées alors on met à jour l'enregistrement          // Si des valeurs ont été calculées alors on met à jour l'enregistrement
2718          if ($valF != "") {          if (count($valF) > 0) {
2719              // On met à jour le dossier              //
2720              $cle = " dossier='".$this->valF['dossier']."'";              $inst_dossier = $this->f->get_inst__om_dbform(array(
2721              $res1 = $this->f->db->autoExecute(DB_PREFIXE.'dossier', $valF, DB_AUTOQUERY_UPDATE, $cle);                  "obj" => "dossier",
2722              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE."dossier\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);                  "idx" => $this->valF['dossier'],
2723              if (database::isError($res1)) {              ));
2724                  die($res->getMessage());              $valF['instruction'] = $id;
2725                $valF['crud'] = 'create';
2726                $update_by_instruction = $inst_dossier->update_by_instruction($valF);
2727                if ($update_by_instruction === false) {
2728                    $this->cleanMessage();
2729                    $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
2730                    return false;
2731              }              }
2732              // Affichage d'informations à l'utilisateur              // Affichage d'informations à l'utilisateur
2733              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
# Line 2337  class instruction extends instruction_ge Line 2877  class instruction extends instruction_ge
2877          }          }
2878    
2879          /**          /**
2880             * Mise à jour de la version de clôture *version_clos* du dossier si et
2881             * seulement si l'instruction met à jour l'état du dossier.
2882             */
2883            if (isset($valF['etat']) === true
2884                && $valF['etat'] !== null
2885                && $valF['etat'] !== '') {
2886                // Instanciation de l'état appliqué sur le dossier par l'instruction
2887                $inst_etat = $this->f->get_inst__om_dbform(array(
2888                    "obj" => "etat",
2889                    "idx" => $valF['etat'],
2890                ));
2891                //
2892                $update_version_clos = null;
2893                // En cas d'instruction qui clôture le dossier
2894                if ($inst_etat->getVal('statut') === 'cloture') {
2895                    $update_version_clos = $inst_di->update_version_clos('up');
2896                }
2897                // En cas d'instruction qui rouvre le dossier
2898                if ($inst_current_etat->getVal('statut') === 'cloture'
2899                    && $inst_etat->getVal('statut') !== 'cloture') {
2900                    //
2901                    $update_version_clos = $inst_di->update_version_clos('down');
2902                    //
2903                    $params = array(
2904                        'di_reopened' => true,
2905                    );
2906                }
2907                //
2908                if ($update_version_clos === false) {
2909                    $this->f->addToLog(sprintf(
2910                        "%s() : ERREUR - %s %s",
2911                        __METHOD__,
2912                        sprintf(
2913                            __("Impossible de mettre à jour la version de clôture du dossier d'instruction %s."),
2914                            $inst_di->getVal($inst_di->clePrimaire)
2915                        ),
2916                        sprintf(
2917                            __("L'instruction tente d'appliquer l'état %s."),
2918                            $inst_etat->getVal($inst_etat->clePrimaire)
2919                        )
2920                    ));
2921                    $this->addToMessage(sprintf(
2922                        "%s %s",
2923                        __("Erreur lors de la mise à jour de la version de clôture du dossier d'instruction."),
2924                        __("Veuillez contacter votre administrateur.")
2925                    ));
2926                    return false;
2927                }
2928            }
2929    
2930            /**
2931             * Notification automatique
2932             */
2933            // Notification automatique à l'ajout de l'instruction si la notification
2934            // automatique est choisie et qu'il n'y a pas de lettretype associée à l'événement
2935            if ($inst_evenement->getVal('notification') === 'notification_automatique' &&
2936                ($inst_evenement->getVal('lettretype') === null ||
2937                $inst_evenement->getVal('lettretype') === '')) {
2938                // Récupération de la liste des demandeurs à notifier et de la catégorie
2939                $categorie = $this->f->get_param_option_notification($collectivite_di);
2940                $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
2941                $demandeursANotifie = $this->get_demandeurs_notifiable(
2942                    $this->valF['dossier'],
2943                    $isPortal
2944                );
2945    
2946                // Création d'une notification et d'une tâche pour chaque demandeur à notifier
2947                foreach ($demandeursANotifie as $demandeur) {
2948                    // Ajout de la notif et récupération de son id
2949                    $idNotif = $this->ajouter_notification(
2950                        $this->valF[$this->clePrimaire],
2951                        $this->f->get_connected_user_login_name(),
2952                        $demandeur,
2953                        $collectivite_di,
2954                        true
2955                    );
2956                    if ($idNotif === false) {
2957                        return false;
2958                    }
2959                    // Création de la tache en lui donnant l'id de la notification
2960                    $notification_by_task = $this->notification_by_task(
2961                        $idNotif,
2962                        $this->valF['dossier'],
2963                        $categorie
2964                    );
2965                    if ($notification_by_task === false) {
2966                        $this->addToMessage(
2967                            __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
2968                        );
2969                        return false;
2970                    }
2971                }
2972                $this->addToMessage($message = sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
2973            }
2974    
2975            /**
2976           * Mise à jour de la date de dernière modification du dossier           * Mise à jour de la date de dernière modification du dossier
2977           */           */
2978          $inst_di->update_last_modification_date();          $inst_di->update_last_modification_date();
# Line 2345  class instruction extends instruction_ge Line 2981  class instruction extends instruction_ge
2981           * Mise à jour des données du DA.           * Mise à jour des données du DA.
2982           */           */
2983          $inst_da = $inst_di->get_inst_dossier_autorisation();          $inst_da = $inst_di->get_inst_dossier_autorisation();
2984          $params = array(          $params['di_id'] = $this->valF['dossier'];
             'di_id' => $this->valF['dossier'],  
         );  
2985          if ($inst_da->majDossierAutorisation($params) === false) {          if ($inst_da->majDossierAutorisation($params) === false) {
2986              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));
2987              $this->correct = false;              $this->correct = false;
# Line 2361  class instruction extends instruction_ge Line 2995  class instruction extends instruction_ge
2995          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));
2996      }      }
2997    
2998        public function is_notifiable_by_task_manual() {
2999            $ev = $this->get_inst_evenement($this->getVal('evenement'));
3000    
3001            // Si l'instruction a une édition non finalisé quel que soit
3002            // le type de notification, il n'est pas notifiable
3003            if ($this->has_an_edition() === true) {
3004                if ($this->is_unfinalizable_without_bypass() === false) {
3005                    return false;
3006                }
3007            }
3008    
3009            // Gestion des différents cas selon la valeur du champs notification
3010            switch ($ev->getVal('notification')) {
3011                case 'notification_manuelle':
3012                    return true;
3013                case 'notification_manuelle_annexe':
3014                    return true;
3015                case 'notification_automatique':
3016                    return false;
3017                case 'notification_auto_signature_requise':
3018                    return false;
3019                case 'notification_manuelle_signature_requise':
3020                    // Si il y a une date de retour de signature la notification est possible
3021                    if ($this->getVal('date_retour_signature') === null
3022                        || $this->getVal('date_retour_signature') === '') {
3023                        return false;
3024                    }
3025                    return true;
3026                case 'notification_manuelle_annexe_signature_requise':
3027                    // Si il y a une date de retour de signature la notification est possible
3028                    if ($this->getVal('date_retour_signature') === null
3029                        || $this->getVal('date_retour_signature') === '') {
3030                        return false;
3031                    }
3032                    return true;
3033                default:
3034                    return false;
3035            }
3036        }
3037    
3038        /**
3039         * Crée une instance et une tache de notification pour le demandeur
3040         * principal.
3041         *
3042         * @return boolean true si le traitement à réussi
3043         */
3044        protected function notifier_demandeur_principal() {
3045            $this->begin_treatment(__METHOD__);
3046            $message = '';
3047            // Récupération des informations concernant le demandeur
3048            $dossier = $this->getVal('dossier');
3049            $collectivite_di = $this->get_dossier_instruction_om_collectivite($dossier);
3050            $demandeur = $this->get_demandeurs_notifiable(
3051                $dossier,
3052                true
3053            );
3054            if ($demandeur !== array()) {
3055                $destinataire = array_values($demandeur);
3056                // Ajout de la notif et récupération de son id
3057                $idNotification = $this->ajouter_notification(
3058                    $this->getVal($this->clePrimaire),
3059                    $this->f->get_connected_user_login_name(),
3060                    $destinataire[0],
3061                    $collectivite_di,
3062                    true
3063                );
3064                if ($idNotification === false) {
3065                    return $this->end_treatment(__METHOD__, false);
3066                }
3067                // Création de la tâche en lui donnant l'id de la notification
3068                $notification_by_task = $this->notification_by_task($idNotification, $dossier);
3069                if ($notification_by_task === false) {
3070                    $this->addToMessage(
3071                        __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
3072                    );
3073                    return $this->end_treatment(__METHOD__, false);
3074                }
3075                $this->addToMessage($message .= sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
3076                return $this->end_treatment(__METHOD__, true);
3077            }
3078            $this->addToMessage( __("Le demandeur principal n'est pas notifiable."));
3079            return $this->end_treatment(__METHOD__, true);
3080        }
3081    
3082        public function notification_by_task($object_id, $dossier, $category = null, $type = null) {
3083            // Par défaut le type est portal
3084            if ($category === null) {
3085                $category = 'portal';
3086            }
3087            // Si le type n'est pas correctement spécifié, alors il est calculé
3088            if ($type === null
3089                || $type !== 'notification_recepisse'
3090                || $type !== 'notification_instruction'
3091                || $type !== 'notification_decision') {
3092                //
3093                $type = 'notification_instruction';
3094                // Vérifie si l'instruction est un récépissé
3095                $trace = debug_backtrace();
3096                foreach ($trace as $key => $value) {
3097                    if (isset($trace[$key]['class']) === true
3098                        && empty($trace[$key]['class']) === false) {
3099                        //
3100                        if (strtolower($trace[$key]['class']) === 'demande') {
3101                            $type = 'notification_recepisse';
3102                        }
3103                    }
3104                }
3105                // Vérifie si l'instruction est une décision
3106                if ($type !== 'notification_recepisse') {
3107                    $avis_decision = $this->getVal('avis_decision') !== null ? $this->getVal('avis_decision') : $this->valF['avis_decision'];
3108                    if ($avis_decision !== null && $avis_decision !== '') {
3109                        $type = 'notification_decision';
3110                    }
3111                }
3112            }
3113            // Préparation de la tache de notification
3114            $inst_task = $this->f->get_inst__om_dbform(array(
3115                "obj" => "task",
3116                "idx" => 0,
3117            ));
3118            $task_val = array(
3119                'type' => $type,
3120                'object_id' => $object_id,
3121                'dossier' => $dossier,
3122                'category' => $category,
3123            );
3124    
3125            $add_task = $inst_task->add_task(array('val' => $task_val));
3126            if ($add_task === false) {
3127                return false;
3128            }
3129    
3130            return true;
3131        }
3132    
3133        /**
3134         * A partir des informations passée en argument ajoute un nouvel élément
3135         * dans la table instruction_notification.
3136         * Avant l'ajout vérifie en utilisant l'id de la collectivité passée en
3137         * paramètre si le paramétrage attendus est ok.
3138         * Ajoute également un nouvel élement dans instruction_notification_document
3139         * si l'instruction possède une lettretype.
3140         * Si un identifiant d'une instruction annexe est donnée ajoute un deuxième
3141         * élement dans la table instruction_notification_document qui correspondra
3142         * à l'annexe de la notification.
3143         *
3144         * @param integer identifiant de l'instruction notifiée
3145         * @param string information concernant l'emetteur
3146         * @param array tableau contenant 2 entrées
3147         *  - destinatire : nom, prenom ou raison sociale, dénomination et courriel
3148         *  - courriel : adresse mail de la personne à notifier
3149         * @param integer identifiant de la collectivité permettant de récupèrer les
3150         * paramètres à valider
3151         * @param boolean indique si la notification est automatique ou manuelle
3152         * @param integer identifiant d'une instruction dont l'édition sera annexé
3153         * à la notification
3154         *
3155         * @return integer|boolean identifiant de la notification créée si le traitement
3156         * a réussie, false sinon.
3157         */
3158        protected function ajouter_notification(
3159            $idInstruction,
3160            $emetteur,
3161            $destinataire,
3162            $collectiviteId,
3163            $demandeAuto = false,
3164            $idInstrDocAnnexe = null
3165        ) {
3166            // Vérification que les paramètres nécessaires à l'envoi de la notification existe avant
3167            // de créer la notification
3168            if (! $this->is_parametrage_notification_correct($collectiviteId)) {
3169                $this->addToMessage(__("Erreur de paramétrage. L'url d'accès au(x) document(s) notifié(s) n'est pas paramétrée."));
3170                return false;
3171            }
3172            // Préparation de la notification
3173            $inst_notif = $this->f->get_inst__om_dbform(array(
3174                "obj" => "instruction_notification",
3175                "idx" => "]",
3176            ));
3177            $notif_val = array(
3178                'instruction_notification' => null,
3179                'instruction' => $idInstruction,
3180                'automatique' => $demandeAuto,
3181                'emetteur' => $emetteur,
3182                'date_envoi' => null,
3183                'destinataire' => $destinataire['destinataire'],
3184                'courriel' => $destinataire['courriel'],
3185                'date_premier_acces' => null,
3186                'statut' => 'en cours d\'envoi',
3187                'commentaire' => 'Notification en cours de traitement'
3188            );
3189    
3190            // Création de la notification
3191            $add_notif = $inst_notif->ajouter($notif_val);
3192            if ($add_notif === false) {
3193                $this->addToMessage(__("Erreur lors de la génération de la notification au(x) pétitionnaire(s)."));
3194                return false;
3195            }
3196    
3197            // Si il y a une lettretype finalisé stockage de la clé d'accès au documents
3198            if ($this->evenement_has_an_edition($this->getVal('evenement')) === true) {
3199                $add_notif_doc = $this->ajouter_notification_document(
3200                    $this->getVal($this->clePrimaire),
3201                    $inst_notif->getVal($inst_notif->clePrimaire)
3202                );
3203                if ($add_notif_doc === false) {
3204                    $this->addToMessage(__("Erreur lors de la génération de la notification du document."));
3205                    return false;
3206                }
3207            }
3208            // Si une annexe a été choisie stockage de la clé d'accès à l'annexe
3209            if ($idInstrDocAnnexe != null || $idInstrDocAnnexe != '') {
3210                $add_notif_annexe = $this->ajouter_notification_document(
3211                    $idInstrDocAnnexe,
3212                    $inst_notif->getVal($inst_notif->clePrimaire),
3213                    true
3214                );
3215                if ($add_notif_annexe === false) {
3216                    $this->addToMessage(__("Erreur lors de la génération de la notification de l'annexe."));
3217                    return false;
3218                }
3219            }
3220    
3221            // Renvoie l'id de la nouvelle instance de instruction_notification
3222            return $inst_notif->getVal($inst_notif->clePrimaire);
3223        }
3224    
3225        /**
3226         * Vérifie si le paramétrage de la notification des demandeurs est correct.
3227         *
3228         * @param integer identifiant de la collectivité
3229         * @return boolean
3230         */
3231        protected function is_parametrage_notification_correct($collectiviteId) {
3232            $categorie = $this->f->get_param_option_notification($collectiviteId);
3233            $urlAccesNotif = $this->f->get_parametre_notification_url_acces($collectiviteId);
3234            if ($categorie == 'mail' && $urlAccesNotif == null) {
3235                return false;
3236            }
3237            return true;
3238        }
3239    
3240        /**
3241         * Ajoute un élément dans la table instruction_notification_document.
3242         *
3243         * @param integer $idInstruction : id de l'instruction à laquelle est rattaché le document
3244         * @param integer $idNotification : id de la notification à laquelle on associe le document
3245         * @param boolean $isAnnexe : indique si le document est une annexe ou pas
3246         *
3247         * @return boolean indique si le traitement a réussi
3248         */
3249        protected function ajouter_notification_document($idInstruction, $idNotification, $isAnnexe = false) {
3250            $inst_notif_doc = $this->f->get_inst__om_dbform(array(
3251                "obj" => "instruction_notification_document",
3252                "idx" => "]",
3253            ));
3254            $notif_doc_val = array(
3255                'instruction_notification_document' => null,
3256                'instruction_notification' => $idNotification,
3257                'instruction' => $idInstruction,
3258                'cle' => $this->getCleAccesDocument(),
3259                'annexe' => $isAnnexe
3260            );
3261    
3262            $add_notif_doc = $inst_notif_doc->ajouter($notif_doc_val);
3263            if ($add_notif_doc === false) {
3264                return false;
3265            }
3266            return true;
3267        }
3268        
3269      /**      /**
3270       * TRIGGER - triggermodifierapres.       * TRIGGER - triggermodifierapres.
3271       *       *
# Line 2368  class instruction extends instruction_ge Line 3273  class instruction extends instruction_ge
3273       */       */
3274      function triggermodifierapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {      function triggermodifierapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
3275          $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);          $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
3276            $collectivite_di = $this->get_dossier_instruction_om_collectivite($val['dossier']);
3277            $message = '';
3278          /**          /**
3279           * L'objectif ici est d'effectuer les recalculs de date dans le dossier           * L'objectif ici est d'effectuer les recalculs de date dans le dossier
3280           * si la date de l'evenement est modifiee           * si la date de l'evenement est modifiee
3281           */           */
3282          // Initialisation          // Initialisation
3283          $valF = "";          $valF = array();
3284          $valF_dt = "";          $valF_dt = array();
3285          // Initialisation du type d'événement          // Initialisation du type d'événement
3286          $type_evmt = "";          $type_evmt = "";
3287          // Récupération de l'action correspondante à l'événement          // Récupération de l'action correspondante à l'événement
# Line 2468  class instruction extends instruction_ge Line 3375  class instruction extends instruction_ge
3375              }              }
3376          }          }
3377          // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement          // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement
3378          if ($valF_dt != "") {          if (count($valF_dt) > 0) {
3379              $dt_id = $this->getDonneesTechniques();              $dt_id = $this->getDonneesTechniques();
3380              // On met à jour le dossier              // On met à jour le dossier
3381              $cle = " donnees_techniques='".$dt_id."'";              $cle = " donnees_techniques='".$dt_id."'";
# Line 2481  class instruction extends instruction_ge Line 3388  class instruction extends instruction_ge
3388              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
3389          }          }
3390          // Si des valeurs ont été calculées alors on met à jour l'enregistrement          // Si des valeurs ont été calculées alors on met à jour l'enregistrement
3391          if ($valF != "") {          if (count($valF) > 0) {
3392              // On met à jour le dossier              //
3393              $cle = " dossier='".$this->valF['dossier']."'";              $inst_dossier = $this->f->get_inst__om_dbform(array(
3394              $res1 = $this->f->db->autoExecute(DB_PREFIXE.'dossier', $valF, DB_AUTOQUERY_UPDATE, $cle);                  "obj" => "dossier",
3395              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE."dossier\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);                  "idx" => $this->valF['dossier'],
3396              if (database::isError($res1)) {              ));
3397                  die($res->getMessage());              $valF['instruction'] = $id;
3398                $valF['crud'] = 'update';
3399                $update_by_instruction = $inst_dossier->update_by_instruction($valF);
3400                if ($update_by_instruction === false) {
3401                    $this->cleanMessage();
3402                    $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
3403                    return false;
3404              }              }
3405              // Affichage d'informations à l'utilisateur              // Affichage d'informations à l'utilisateur
3406              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
# Line 2598  class instruction extends instruction_ge Line 3511  class instruction extends instruction_ge
3511                              return false;                              return false;
3512                          }                          }
3513                      }                      }
                     // Mise à jour du flag incomplet_notifie dans dossier si la  
                     // date limite d'instruction n'est pas dépassée  
                     if($row['type']=='incompletude' &&  
                         ($this->valF['archive_date_notification_delai'] >= $this->valF['date_retour_rar'] ||  
                         $this->valF['archive_date_notification_delai'] == "")) {  
                         $valFIncomp['incomplet_notifie'] = true;  
                         $cle = " dossier='".$val['dossier']."'";  
                         $resIncomp = $this->f->db->autoExecute(  
                             DB_PREFIXE.'dossier',  
                             $valFIncomp,  
                             DB_AUTOQUERY_UPDATE,  
                             $cle  
                         );  
                         $this->addToLog(  
                             __METHOD__."(): db->autoexecute(\"".  
                                 DB_PREFIXE."dossier\", ".print_r($valFIncomp, true).  
                                 ", DB_AUTOQUERY_UPDATE, \"".$cle."\");",  
                             VERBOSE_MODE  
                         );  
                         if (database::isError($resIncomp)) {  
                             die($resIncomp->getMessage());  
                         }  
                     }  
3514                  }                  }
3515              }              }
3516          }          }
# Line 2646  class instruction extends instruction_ge Line 3536  class instruction extends instruction_ge
3536              return false;              return false;
3537          }          }
3538    
3539            // mise à jour des métadonnées issues des dates de suivi
3540            $dateRetourSignatureModified = ($this->valF['date_retour_signature'] != $this->getVal('date_retour_signature'));
3541            $dateRetourRARModified = ($this->valF['date_retour_rar'] != $this->getVal('date_retour_rar'));
3542            if ($dateRetourSignatureModified || $dateRetourRARModified) {
3543    
3544                // Calculs des nouvelles métadonnées
3545                $metadata = $this->getMetadata("om_fichier_instruction");
3546    
3547                // On vérifie si l'instruction à finaliser a un événement de type arrete
3548                $sql = "SELECT type FROM ".DB_PREFIXE."evenement WHERE evenement = ".$this->getVal("evenement");
3549                $typeEvenement = $this->f->db->getOne($sql);
3550                $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
3551                if ($this->f->isDatabaseError($typeEvenement, true) === true) {
3552                    $this->correct = false;
3553                    $this->addToMessage(__("Erreur de traitement de fichier."));
3554                    $this->addToLog(__METHOD__."() erreur BDD: ".var_export($typeEvenement->getMessage(), true), DEBUG_MODE);
3555                    return false;
3556                }
3557    
3558                // Si l'événement est de type arrete, on ajoute les métadonnées spécifiques
3559                if ($typeEvenement == 'arrete'){
3560                    $metadata = array_merge($metadata, $this->getMetadata("arrete"));
3561                }
3562    
3563                // Filtre pour conserver uniquement les métadonnées liées aux dates
3564                $metadataToKeep = array(
3565                    "statutAutorisation",
3566                    "dateEvenementDocument",
3567                    'date_cloture_metier',
3568                    "NotificationArrete",
3569                    "dateNotificationArrete",
3570                    "controleLegalite",
3571                    "dateSignature",
3572                    "nomSignataire",
3573                    "qualiteSignataire",
3574                    "dateControleLegalite",
3575                );
3576                $metadata = array_filter(
3577                    $metadata,
3578                    function($key) use ($metadataToKeep) { return in_array($key, $metadataToKeep); },
3579                    ARRAY_FILTER_USE_KEY
3580                );
3581    
3582                // Mise à jour des métadonnées du document en GED
3583                $docUid = $this->getVal("om_fichier_instruction");
3584                $operationOrUID = $this->f->storage->update_metadata($docUid, $metadata);
3585                if ($operationOrUID == 'OP_FAILURE') {
3586                    $this->correct = false;
3587                    $this->addToMessage(__("Erreur de traitement de fichier."));
3588                    $this->addToLog(__METHOD__."() failed to update metadata: ".var_export($operationOrUID, true), DEBUG_MODE);
3589                    return false;
3590                }
3591    
3592                // mise à jour de l'UID du document en BDD
3593                else {
3594                    $valF = array('om_fichier_instruction' => $operationOrUID);
3595                    $res = $this->f->db->autoExecute(DB_PREFIXE.$this->table, $valF, DB_AUTOQUERY_UPDATE, $this->getCle($id));
3596                    $this->addToLog(__METHOD__.'() : db->autoExecute("'.DB_PREFIXE.$this->table.'", '.print_r($valF, true).', DB_AUTOQUERY_UPDATE, "'.$this->getCle($id).'")', VERBOSE_MODE);
3597                    if ($this->f->isDatabaseError($res, true) === true) {
3598                        $this->correct = false;
3599                        $this->addToMessage(__("Erreur de traitement de fichier."));
3600                        $this->addToLog(__METHOD__."() erreur BDD: ".var_export($res->getMessage(), true), DEBUG_MODE);
3601                        return false;
3602                    }
3603                    $this->addToMessage(__("La mise a jour du document s'est effectuee avec succes."));
3604                }
3605            }
3606    
3607            // Notification auto des demandeurs
3608            if ($dateRetourSignatureModified === true
3609                && $this->valF['date_retour_signature'] !== ''
3610                && $this->valF['date_retour_signature'] !== null) {
3611                //
3612                $ev = $this->get_inst_evenement($this->valF['evenement']);
3613                if ($ev->getVal('notification') === 'notification_auto_signature_requise') {
3614                    // Récupération de la liste des demandeurs à notifier et de la catégorie
3615                    $categorie = $this->f->get_param_option_notification($collectivite_di);
3616                    $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
3617                    $demandeursANotifie = $this->get_demandeurs_notifiable(
3618                        $this->valF['dossier'],
3619                        $isPortal
3620                    );
3621    
3622                    // Création d'une notification et d'une tâche pour chaque demandeur à notifier
3623                    foreach ($demandeursANotifie as $demandeur) {
3624                        // Ajout de la notif et récupération de son id
3625                        $idNotif = $this->ajouter_notification(
3626                            $this->valF[$this->clePrimaire],
3627                            $this->f->get_connected_user_login_name(),
3628                            $demandeur,
3629                            $collectivite_di,
3630                            true
3631                        );
3632                        if ($idNotif === false) {
3633                            return false;
3634                        }
3635                        // Création de la tache en lui donnant l'id de la notification
3636                        $notification_by_task = $this->notification_by_task(
3637                            $idNotif,
3638                            $this->valF['dossier'],
3639                            $categorie
3640                        );
3641                        if ($notification_by_task === false) {
3642                            $this->addToMessage(
3643                                __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
3644                            );
3645                            return false;
3646                        }
3647                    }
3648                    $this->addToMessage($message .= sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
3649                }
3650            }
3651    
3652          return $this->add_log_to_dossier($id, $val);          return $this->add_log_to_dossier($id, $val);
3653      }      }
3654    
# Line 2659  class instruction extends instruction_ge Line 3662  class instruction extends instruction_ge
3662          /**          /**
3663           * L'objectif ici est de repositionner les valeurs récupérées en           * L'objectif ici est de repositionner les valeurs récupérées en
3664           * archive dans le dossier d'instruction avant de supprimer l'événement           * archive dans le dossier d'instruction avant de supprimer l'événement
3665           * d'instruction           * d'instruction si les valeurs du dossier sont différentes
3666           */           */
3667                    $valF = array();
3668          // Mise à jour des 4 valeurs modifiées par l'action          $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
3669          $valF['delai'] = $val['archive_delai'];          foreach ($inst_di->champs as $key => $champ) {
3670          $valF['accord_tacite'] = $val['archive_accord_tacite'];              // Si le champ du DI à une archive dans l'instruction
3671          $valF['etat'] = $val['archive_etat'];              if (isset($val[sprintf('archive_%s', $champ)]) === true) {
3672          if ($val['archive_avis'] != '') {                  // Si la valeur entre le champ du DI et son archive dans instruction
3673              $valF['avis_decision'] = $val['archive_avis'];                  // est différente
3674          } else {                  if ($inst_di->getVal($champ) !== $val[sprintf('archive_%s', $champ)]) {
3675              $valF['avis_decision'] = null;                      $val[sprintf('archive_%s', $champ)] === '' ? $valF[$champ] = null : $valF[$champ] = $val[sprintf('archive_%s', $champ)];
3676          }                  }
3677          // Mise à jour des dates avec la valeur présente dans le formulaire              }
         // de suppression. Si la valeur de la date est vide alors on fixe  
         // à la valeur null  
         if ($val['archive_date_complet'] != '') {  
             $valF['date_complet'] = $val['archive_date_complet'];  
         } else {  
             $valF['date_complet'] = null;  
         }  
         if ($val['archive_date_dernier_depot'] != '') {  
             $valF['date_dernier_depot'] = $val['archive_date_dernier_depot'];  
         } else {  
             $valF['date_dernier_depot'] = null;  
         }  
         if ($val['archive_date_rejet'] != '') {  
             $valF['date_rejet'] = $val['archive_date_rejet'];  
         } else {  
             $valF['date_rejet'] = null;  
         }  
         if ($val['archive_date_limite'] != '') {  
             $valF['date_limite'] = $val['archive_date_limite'];  
         } else {  
             $valF['date_limite'] = null;  
         }  
         if ($val['archive_date_notification_delai'] != '') {  
             $valF['date_notification_delai'] = $val['archive_date_notification_delai'];  
         } else {  
             $valF['date_notification_delai'] = null;  
         }  
         if ($val['archive_date_decision'] != '') {  
             $valF['date_decision'] = $val['archive_date_decision'];  
         } else {  
             $valF['date_decision'] = null;  
         }  
         if ($val['archive_date_validite'] != '') {  
             $valF['date_validite'] = $val['archive_date_validite'];  
         } else {  
             $valF['date_validite'] = null;  
         }  
         if ($val['archive_date_achevement'] != '') {  
             $valF['date_achevement'] = $val['archive_date_achevement'];  
         } else {  
             $valF['date_achevement'] = null;  
         }  
         if ($val['archive_date_chantier'] != '') {  
             $valF['date_chantier'] = $val['archive_date_chantier'];  
         } else {  
             $valF['date_chantier'] = null;  
         }  
         if ($val['archive_date_conformite'] != '') {  
             $valF['date_conformite'] = $val['archive_date_conformite'];  
         } else {  
             $valF['date_conformite'] = null;  
         }  
         if ($val['archive_incompletude'] != '') {  
             $valF['incompletude'] = $val['archive_incompletude'];  
         } else {  
             $valF['incompletude'] = null;  
         }  
         if ($val['archive_incomplet_notifie'] != '') {  
             $valF['incomplet_notifie'] = $val['archive_incomplet_notifie'];  
         } else {  
             $valF['incomplet_notifie'] = null;  
         }  
         if ($val['archive_evenement_suivant_tacite'] != '') {  
             $valF['evenement_suivant_tacite'] = $val['archive_evenement_suivant_tacite'];  
         } else {  
             $valF['evenement_suivant_tacite'] = null;  
         }  
         if ($val['archive_evenement_suivant_tacite_incompletude'] != '') {  
             $valF['evenement_suivant_tacite_incompletude'] = $val['archive_evenement_suivant_tacite_incompletude'];  
         } else {  
             $valF['evenement_suivant_tacite_incompletude'] = null;  
         }  
         if ($val['archive_etat_pendant_incompletude'] != '') {  
             $valF['etat_pendant_incompletude'] = $val['archive_etat_pendant_incompletude'];  
         } else {  
             $valF['etat_pendant_incompletude'] = null;  
         }  
         if ($val['archive_date_limite_incompletude'] != '') {  
             $valF['date_limite_incompletude'] = $val['archive_date_limite_incompletude'];  
         } else {  
             $valF['date_limite_incompletude'] = null;  
         }  
         if ($val['archive_delai_incompletude'] != '') {  
             $valF['delai_incompletude'] = $val['archive_delai_incompletude'];  
         } else {  
             $valF['delai_incompletude'] = null;  
         }  
         if ($val['archive_autorite_competente'] != '') {  
             $valF['autorite_competente'] = $val['archive_autorite_competente'];  
         } else {  
             $valF['autorite_competente'] = null;  
3678          }          }
3679          $valF['date_cloture_instruction'] = null;          // Spécificité du champ avis_decision dont le champ archive est nommé
3680          if ($val['archive_date_cloture_instruction'] !== '') {          // différemment
3681              $valF['date_cloture_instruction'] = $val['archive_date_cloture_instruction'];          if ($inst_di->getVal('avis_decision') !== $val['archive_avis']) {
3682                $val['archive_avis'] === '' ? $valF['avis_decision'] = null : $valF['avis_decision'] = $val['archive_avis'];
3683            }
3684            // Spécificité de la date d'affichage dont la valeur n'ai jamais modifiée
3685            // par l'archive
3686            unset($valF['date_affichage']);
3687    
3688            /**
3689             * Mise à jour de la version de clôture *version_clos* du dossier si et
3690             * seulement si l'instruction met à jour l'état du dossier.
3691             */
3692            if (isset($valF['etat']) === true
3693                && $valF['etat'] !== null
3694                && $valF['etat'] !== '') {
3695                // Récupère l'état actuel du dossier d'instruction
3696                $inst_current_etat = $this->f->get_inst__om_dbform(array(
3697                    "obj" => "etat",
3698                    "idx" => $inst_di->get_id_etat(),
3699                ));
3700                // Instanciation de l'état archivé appliqué sur le dossier
3701                $inst_etat = $this->f->get_inst__om_dbform(array(
3702                    "obj" => "etat",
3703                    "idx" => $valF['etat'],
3704                ));
3705                //
3706                $update_version_clos = null;
3707                // En cas de clôture du dossier par l'état archivé
3708                if ($inst_etat->getVal('statut') === 'cloture') {
3709                    $update_version_clos = $inst_di->update_version_clos('up');
3710                }
3711                // En cas de réouverture du dossier par l'état archivé
3712                if ($inst_current_etat->getVal('statut') === 'cloture'
3713                    && $inst_etat->getVal('statut') !== 'cloture') {
3714                    //
3715                    $update_version_clos = $inst_di->update_version_clos('down');
3716                    //
3717                    $this->set_att_di_reopened(true);
3718                }
3719                //
3720                if ($update_version_clos === false) {
3721                    $this->f->addToLog(sprintf(
3722                        "%s() : ERREUR - %s %s",
3723                        __METHOD__,
3724                        sprintf(
3725                            __("Impossible de mettre à jour la version de clôture du dossier d'instruction %s."),
3726                            $inst_di->getVal($inst_di->clePrimaire)
3727                        ),
3728                        sprintf(
3729                            __("L'instruction tente d'appliquer l'état %s."),
3730                            $inst_etat->getVal($inst_etat->clePrimaire)
3731                        )
3732                    ));
3733                    $this->addToMessage(sprintf(
3734                        "%s %s",
3735                        __("Erreur lors de la mise à jour de la version de clôture du dossier d'instruction."),
3736                        __("Veuillez contacter votre administrateur.")
3737                    ));
3738                    return false;
3739                }
3740          }          }
3741          // Dates concernant les dossiers contentieux          // On supprime toutes les notications liées à l'instruction
3742          // Date de première visite          $notifASupprimer = $this->get_instruction_notification($this->getVal($this->clePrimaire));
3743          $valF['date_premiere_visite'] = null;          foreach ($notifASupprimer as $idNotif) {
3744          if ($val['archive_date_premiere_visite'] !== '') {              $inst_notif = $this->f->get_inst__om_dbform(array(
3745              $valF['date_premiere_visite'] = $val['archive_date_premiere_visite'];                  "obj" => "instruction_notification",
3746          }                  "idx" => $idNotif,
3747          // Date de dernière visite              ));
3748          $valF['date_derniere_visite'] = null;              $val_notif = array();
3749          if ($val['archive_date_derniere_visite'] !== '') {              foreach ($inst_notif->champs as $champ) {
3750              $valF['date_derniere_visite'] = $val['archive_date_derniere_visite'];                  $val_notif[$champ] = $inst_notif->getVal($champ);
3751          }              }
3752          // Date contradictoire              // La suppression des notifications entrainera la suppression des tâches qui y sont
3753          $valF['date_contradictoire'] = null;              // liées
3754          if ($val['archive_date_contradictoire'] !== '') {              $supprNotif = $inst_notif->supprimer($val_notif);
3755              $valF['date_contradictoire'] = $val['archive_date_contradictoire'];              if ($supprNotif == false) {
3756          }                  $this->addToMessage(sprintf(
3757          // Date de retour contradictoire                      "%s %s",
3758          $valF['date_retour_contradictoire'] = null;                      __("Erreur lors de la suppression des notifications de l'instruction."),
3759          if ($val['archive_date_retour_contradictoire'] !== '') {                      __("Veuillez contacter votre administrateur.")
3760              $valF['date_retour_contradictoire'] = $val['archive_date_retour_contradictoire'];                  ));
3761          }                  return false;
3762          // Date de l'AIT              }
         $valF['date_ait'] = null;  
         if ($val['archive_date_ait'] !== '') {  
             $valF['date_ait'] = $val['archive_date_ait'];  
         }  
         // Date de transmission au parquet  
         $valF['date_transmission_parquet'] = null;  
         if ($val['archive_date_transmission_parquet'] !== '') {  
             $valF['date_transmission_parquet'] = $val['archive_date_transmission_parquet'];  
         }  
         // Type du dossier d'instruction  
         if ($val['archive_dossier_instruction_type'] !== '' && $val['archive_dossier_instruction_type'] !== null) {  
             $valF['dossier_instruction_type'] = $val['archive_dossier_instruction_type'];  
3763          }          }
         // Spécificité de la date d'affichage, la valeur du champ du dossier  
         // n'est pas remplacée par celle de l'archive de l'instruction.  
3764    
3765          // On met à jour le dossier          // On met à jour le dossier
3766          $cle = " dossier='".$val['dossier']."'";          $valF['instruction'] = $id;
3767          $res = $this->f->db->autoExecute(DB_PREFIXE.'dossier', $valF, DB_AUTOQUERY_UPDATE, $cle);          $valF['crud'] = 'delete';
3768          $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE."dossier\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);          $update_by_instruction = $inst_di->update_by_instruction($valF);
3769          if (database::isError($res)) {          if ($update_by_instruction === false) {
3770              die($res->getMessage());              $this->cleanMessage();
3771                $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
3772                return false;
3773          }          }
3774    
3775          // Affichage d'informations à l'utilisateur          // Affichage d'informations à l'utilisateur
3776          $this->addToMessage(_("Suppression de l'instruction")." [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");          $this->addToMessage(_("Suppression de l'instruction")." [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
3777    
# Line 2842  class instruction extends instruction_ge Line 3801  class instruction extends instruction_ge
3801          ));          ));
3802          $params = array(          $params = array(
3803              'di_id' => $this->getVal('dossier'),              'di_id' => $this->getVal('dossier'),
3804                'di_reopened' => $this->get_att_di_reopened(),
3805          );          );
3806          if($da->majDossierAutorisation($params) === false) {          if($da->majDossierAutorisation($params) === false) {
3807              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));
# Line 2849  class instruction extends instruction_ge Line 3809  class instruction extends instruction_ge
3809              return false;              return false;
3810          }          }
3811    
3812            /**
3813             * Gestion des tâches pour la dématérialisation
3814             */
3815            $inst_task_empty = $this->f->get_inst__om_dbform(array(
3816                "obj" => "task",
3817                "idx" => 0,
3818            ));
3819            foreach ($inst_di->task_types as $task_type) {
3820                $task_exists = $inst_task_empty->task_exists($task_type, $id);
3821                if ($task_exists !== false) {
3822                    $inst_task = $this->f->get_inst__om_dbform(array(
3823                        "obj" => "task",
3824                        "idx" => $task_exists,
3825                    ));
3826                    if ($inst_task->getVal('state') === $inst_task::STATUS_NEW || $inst_task->getVal('state') === $inst_task::STATUS_DRAFT) {
3827                        $task_val = array(
3828                            'state' => $inst_task::STATUS_CANCELED,
3829                        );
3830                        $update_task = $inst_task->update_task(array('val' => $task_val));
3831                        if ($update_task === false) {
3832                            $this->addToMessage(sprintf('%s %s',
3833                                sprintf(__("Une erreur s'est produite lors de la modification de la tâche %."), $inst_task->getVal($inst_task->clePrimaire)),
3834                                __("Veuillez contacter votre administrateur.")
3835                            ));
3836                            $this->correct = false;
3837                            return false;
3838                        }
3839                    }
3840                }
3841            }
3842    
3843          //          //
3844          $val['evenement'] = $this->getVal('evenement');          $val['evenement'] = $this->getVal('evenement');
3845          return $this->add_log_to_dossier($id, $val);          return $this->add_log_to_dossier($id, $val);
3846      }      }
3847    
3848      /**      /**
3849         * Permet de mettre la valeur passée en paramètre dans l'attribut de classe
3850         * "di_reopened".
3851         *
3852         * @param boolean $val
3853         */
3854        function set_att_di_reopened($val) {
3855            $this->di_reopened = $val;
3856        }
3857    
3858        /**
3859         * Permet de récupérer la valeur de l'attribut de classe "di_reopened".
3860         *
3861         * @return boolean
3862         */
3863        function get_att_di_reopened() {
3864            return $this->di_reopened;
3865        }
3866    
3867        /**
3868       * Permet de composer un message d'erreur sur restriction non valide en       * Permet de composer un message d'erreur sur restriction non valide en
3869       * fonction du contexte.       * fonction du contexte.
3870       *       *
# Line 3025  class instruction extends instruction_ge Line 4035  class instruction extends instruction_ge
4035              // Génération du PDF              // Génération du PDF
4036              $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);              $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
4037              $pdf_output = $result['pdf_output'];              $pdf_output = $result['pdf_output'];
4038                
4039              //Métadonnées du document              //Métadonnées du document
4040              $metadata = array(              $metadata = array(
4041                  'filename' => 'instruction_'.$id_inst.'.pdf',                  'filename' => 'instruction_'.$id_inst.'.pdf',
# Line 3057  class instruction extends instruction_ge Line 4067  class instruction extends instruction_ge
4067    
4068              $metadata = array_merge($metadata, $spe_metadata, $arrete_metadata);              $metadata = array_merge($metadata, $spe_metadata, $arrete_metadata);
4069    
4070                /*
4071                // transforme le tableau de métadonnées en objet
4072                $mdf = new MetadataFactory();
4073                $md = $mdf->build('Instruction', $metadata);
4074                */
4075    
4076              // Si le document a déjà été finalisé on le met à jour              // Si le document a déjà été finalisé on le met à jour
4077              // en conservant son UID              // en conservant son UID
4078              if ($this->getVal("om_fichier_instruction") != ''){              if ($this->getVal("om_fichier_instruction") != ''){
# Line 3065  class instruction extends instruction_ge Line 4081  class instruction extends instruction_ge
4081              }              }
4082              // Sinon on crée un nouveau document et dont on récupère l'UID              // Sinon on crée un nouveau document et dont on récupère l'UID
4083              else {              else {
4084                  $uid = $this->f->storage->create($pdf_output, $metadata);                  $uid = $this->f->storage->create($pdf_output, $metadata, "from_content", $this->table.".om_fichier_instruction");
4085              }              }
4086          }          }
4087    
# Line 3186  class instruction extends instruction_ge Line 4202  class instruction extends instruction_ge
4202       * Récupération du numéro de dossier d'instruction à ajouter aux métadonnées       * Récupération du numéro de dossier d'instruction à ajouter aux métadonnées
4203       * @return string numéro de dossier d'instruction       * @return string numéro de dossier d'instruction
4204       */       */
4205      protected function getDossier() {      protected function getDossier($champ = null) {
4206          if(empty($this->specificMetadata)) {          if(empty($this->specificMetadata)) {
4207              $this->getSpecificMetadata();              $this->getSpecificMetadata();
4208          }          }
# Line 3449  class instruction extends instruction_ge Line 4465  class instruction extends instruction_ge
4465              $return['archive_dossier_instruction_type'] = $row['dossier_instruction_type'];              $return['archive_dossier_instruction_type'] = $row['dossier_instruction_type'];
4466              $return['duree_validite'] = $row['duree_validite'];              $return['duree_validite'] = $row['duree_validite'];
4467              $return['date_depot'] = $row['date_depot'];              $return['date_depot'] = $row['date_depot'];
4468                $return['date_depot_mairie'] = $row['date_depot_mairie'];
4469              $return['archive_date_cloture_instruction'] = $row['date_cloture_instruction'];              $return['archive_date_cloture_instruction'] = $row['date_cloture_instruction'];
4470              $return['archive_date_premiere_visite'] = $row['date_premiere_visite'];              $return['archive_date_premiere_visite'] = $row['date_premiere_visite'];
4471              $return['archive_date_derniere_visite'] = $row['date_derniere_visite'];              $return['archive_date_derniere_visite'] = $row['date_derniere_visite'];
# Line 3457  class instruction extends instruction_ge Line 4474  class instruction extends instruction_ge
4474              $return['archive_date_ait'] = $row['date_ait'];              $return['archive_date_ait'] = $row['date_ait'];
4475              $return['archive_date_transmission_parquet'] = $row['date_transmission_parquet'];              $return['archive_date_transmission_parquet'] = $row['date_transmission_parquet'];
4476              $return['archive_date_affichage'] = $row['date_affichage'];              $return['archive_date_affichage'] = $row['date_affichage'];
4477                $return['archive_pec_metier'] = $row['pec_metier'];
4478                $return['archive_a_qualifier'] = $row['a_qualifier'];
4479          }          }
4480    
4481          // Retour de la fonction          // Retour de la fonction
# Line 3572  class instruction extends instruction_ge Line 4591  class instruction extends instruction_ge
4591          if ($row['date_depot'] != '') {          if ($row['date_depot'] != '') {
4592              $this->valF['date_depot']= $row['date_depot'];                $this->valF['date_depot']= $row['date_depot'];  
4593          }          }
4594            if ($row['date_depot_mairie'] != '') {
4595                $this->valF['date_depot_mairie']= $row['date_depot_mairie'];  
4596            }
4597          // Dates concernant les dossiers contentieux          // Dates concernant les dossiers contentieux
4598          if ($row['date_cloture_instruction'] != '') {          if ($row['date_cloture_instruction'] != '') {
4599              $this->valF['archive_date_cloture_instruction']= $row['date_cloture_instruction'];                $this->valF['archive_date_cloture_instruction']= $row['date_cloture_instruction'];  
# Line 3601  class instruction extends instruction_ge Line 4623  class instruction extends instruction_ge
4623          if ($row['date_affichage'] != '') {          if ($row['date_affichage'] != '') {
4624              $this->valF['archive_date_affichage']= $row['date_affichage'];                $this->valF['archive_date_affichage']= $row['date_affichage'];  
4625          }          }
4626            if (isset($row['pec_metier']) === true && $row['pec_metier'] != '') {
4627                $this->valF['archive_pec_metier']= $row['pec_metier'];  
4628            }
4629            if (isset($row['a_qualifier']) === true && $row['a_qualifier'] != '') {
4630                $this->valF['archive_a_qualifier']= $row['a_qualifier'];  
4631            }
4632      }      }
4633    
4634      // {{{      // {{{
# Line 3732  class instruction extends instruction_ge Line 4760  class instruction extends instruction_ge
4760          "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",          "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",
4761          "ap_codepostal"=>"", "ap_ville"=>"");          "ap_codepostal"=>"", "ap_ville"=>"");
4762    
4763          $sqlArrete = "SELECT    signataire_arrete.nom as \"nomsignataire\",          $sqlArrete = "SELECT
4764                    signataire_arrete.prenom || ' ' ||signataire_arrete.nom as \"nomsignataire\",
4765                  signataire_arrete.qualite as \"qualitesignataire\",                  signataire_arrete.qualite as \"qualitesignataire\",
4766                  instruction.etat as \"decisionarrete\",                  instruction.etat as \"decisionarrete\",
4767                  instruction.date_retour_rar as \"datenotification\",                  instruction.date_retour_rar as \"datenotification\",
# Line 3780  class instruction extends instruction_ge Line 4809  class instruction extends instruction_ge
4809      }      }
4810    
4811      /**      /**
4812         * CONDITION - is_modifiable.
4813         *
4814         * Controle si l'évenement est modifiable.
4815         *
4816         * @return boolean
4817         */
4818        function is_evenement_modifiable() {
4819            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
4820            return ! $this->get_boolean_from_pgsql_value($evenement->getVal('non_modifiable'));
4821        }
4822    
4823        /**
4824       * CONDITION - is_editable.       * CONDITION - is_editable.
4825       *       *
4826       * Condition pour la modification.       * Condition pour la modification.
# Line 3787  class instruction extends instruction_ge Line 4828  class instruction extends instruction_ge
4828       * @return boolean       * @return boolean
4829       */       */
4830      function is_editable() {      function is_editable() {
4831    
4832            // XXX
4833            // Identifier si l'instruction est lié à une tâche depuis le champ object_id (mais aussi voir le log car object_id peut être modifié)
4834            // Si cette tâche identifiée est DONE alors la suppression/modification de cette intruction est impossible
4835    
4836          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
4837          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_modifier_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_modifier_bypass");
4838          //          //
# Line 3823  class instruction extends instruction_ge Line 4869  class instruction extends instruction_ge
4869      }      }
4870    
4871      /**      /**
4872         * Vérifie si l'événement est supprimable ou pas.
4873         *
4874         * @return boolean
4875         */
4876        function is_evenement_supprimable() {
4877            // Controle si l'évenement est supprimable
4878            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
4879            return ! $this->get_boolean_from_pgsql_value($evenement->getVal('non_supprimable'));
4880        }
4881    
4882        /**
4883       * CONDITION - is_deletable.       * CONDITION - is_deletable.
4884       *       *
4885       * Condition pour la suppression.       * Condition pour la suppression.
# Line 3830  class instruction extends instruction_ge Line 4887  class instruction extends instruction_ge
4887       * @return boolean       * @return boolean
4888       */       */
4889      function is_deletable() {      function is_deletable() {
4890    
4891            // XXX
4892            // Identifier si l'instruction est lié à une tâche depuis le champ object_id (mais aussi voir le log car object_id peut être modifié)
4893            // Si cette tâche identifiée est DONE alors la suppression/modification de cette intruction est impossible
4894    
4895          // Contrôle si l'utilisateur possède un bypass intégral          // Contrôle si l'utilisateur possède un bypass intégral
4896          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_supprimer_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_supprimer_bypass");
4897          //          //
# Line 4221  class instruction extends instruction_ge Line 5283  class instruction extends instruction_ge
5283          // Cette méthode permet d'exécuter une routine en début des méthodes          // Cette méthode permet d'exécuter une routine en début des méthodes
5284          // dites de TREATMENT.          // dites de TREATMENT.
5285          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
5286            $message = '';
5287    
5288          // Traitement de la finalisation          // Traitement de la finalisation
5289          $ret = $this->manage_finalizing("finalize", $val);          $ret = $this->manage_finalizing("finalize", $val);
# Line 4232  class instruction extends instruction_ge Line 5295  class instruction extends instruction_ge
5295              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
5296          }          }
5297    
5298            // Envoi des notifications aux demandeurs si la notification est automatique
5299            // et que la signature n'est pas requise
5300            $ev = $this->get_inst_evenement($this->getVal('evenement'));
5301            if ($ev->getVal('notification') === 'notification_automatique') {
5302                // Récupération de la catégorie et envoie des notifications au(x) demandeur(s)
5303                $collectivite_di = $this->get_dossier_instruction_om_collectivite($this->getVal('dossier'));
5304                // Récupération de la liste des demandeurs à notifier et de la catégorie
5305                $categorie = $this->f->get_param_option_notification($collectivite_di);
5306                $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
5307                $demandeursANotifie = $this->get_demandeurs_notifiable(
5308                    $this->getVal('dossier'),
5309                    $isPortal
5310                );
5311    
5312                // Création d'une notification et d'une tâche pour chaque demandeur à notifier
5313                if (count($demandeursANotifie) > 0) {
5314                    foreach ($demandeursANotifie as $demandeur) {
5315                        // Ajout de la notif et récupération de son id
5316                        $idNotif = $this->ajouter_notification(
5317                            $this->getVal($this->clePrimaire),
5318                            $this->f->get_connected_user_login_name(),
5319                            $demandeur,
5320                            $collectivite_di,
5321                            true
5322                        );
5323                        if ($idNotif === false) {
5324                            // Termine le traitement
5325                            return $this->end_treatment(__METHOD__, false);
5326                        }
5327                        $notification_by_task = $this->notification_by_task(
5328                            $idNotif,
5329                            $this->getVal('dossier'),
5330                            $categorie
5331                        );
5332                        if ($notification_by_task === false) {
5333                            $this->addToMessage(
5334                                __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
5335                            );
5336                            // Termine le traitement
5337                            return $this->end_treatment(__METHOD__, false);
5338                        }
5339                    }
5340                    $this->addToMessage($message .= sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
5341                }
5342            }
5343    
5344          // Termine le traitement          // Termine le traitement
5345          return $this->end_treatment(__METHOD__, true);          return $this->end_treatment(__METHOD__, true);
5346      }      }
# Line 5339  class instruction extends instruction_ge Line 6448  class instruction extends instruction_ge
6448    
6449                  if($res->numrows() == 1) {                  if($res->numrows() == 1) {
6450                      $liste_champs = explode(";", $type_mise_a_jour);                      $liste_champs = explode(";", $type_mise_a_jour);
6451                        $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);
6452                        $instr = $this->f->get_inst__om_dbform(array(
6453                            "obj" => "instruction",
6454                            "idx" => $row['instruction'],
6455                        ));
6456                      // Mise à jour des dates après l'écran de verification                      // Mise à jour des dates après l'écran de verification
6457                      if($this->f->get_submitted_post_value('is_valid') !== null and $this->f->get_submitted_post_value('is_valid') == "true") {                      if($this->f->get_submitted_post_value('is_valid') !== null and $this->f->get_submitted_post_value('is_valid') == "true") {
                         $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);  
                         $instr = $this->f->get_inst__om_dbform(array(  
                             "obj" => "instruction",  
                             "idx" => $row['instruction'],  
                         ));  
6458                          $valF = array();                          $valF = array();
6459                          foreach($instr->champs as $id => $champ) {                          foreach($instr->champs as $id => $champ) {
6460                              $valF[$champ] = $instr->val[$id];                              $valF[$champ] = $instr->val[$id];
# Line 5450  class instruction extends instruction_ge Line 6559  class instruction extends instruction_ge
6559    
6560                          // Vérification de la non modification des dates de suivi                          // Vérification de la non modification des dates de suivi
6561                          foreach(explode(";", $type_mise_a_jour) as $champ) {                          foreach(explode(";", $type_mise_a_jour) as $champ) {
6562                                if ($champ === 'date_envoi_controle_legalite') {
6563                                    if ($instr->is_sent_to_cl() === true) {
6564                                        $error = __("Les dates de suivis ne peuvent etre modifiees");
6565                                        $date_error = true;
6566                                        break;
6567                                    }
6568                                }
6569                              if($infos[$champ] != "" AND $infos[$champ] != $date) {                              if($infos[$champ] != "" AND $infos[$champ] != $date) {
6570                                  $error = _("Les dates de suivis ne peuvent etre modifiees");                                  $error = _("Les dates de suivis ne peuvent etre modifiees");
6571                                  $date_error = true;                                  $date_error = true;
6572                                    break;
6573                              }                              }
6574                          }                          }
6575                      }                      }
# Line 5686  class instruction extends instruction_ge Line 6803  class instruction extends instruction_ge
6803                          break;                          break;
6804                      case 'ADS':                      case 'ADS':
6805                      case 'DPC':                      case 'DPC':
6806                        case 'CONSULTATION ENTRANTE':
6807                      default:                      default:
6808                          $sql_demandeur = "((lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='petitionnaire') OR demandeur.type_demandeur='delegataire')";                          $sql_demandeur = "((lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='petitionnaire') OR demandeur.type_demandeur='delegataire')";
6809                          break;                          break;
# Line 5994  class instruction extends instruction_ge Line 7112  class instruction extends instruction_ge
7112      }      }
7113    
7114      /**      /**
7115         * VIEW - view_rapport_instruction.
7116         *
7117         * Ouvre le sous-formulaire en ajaxIt dans un overlay.
7118         * Cette action est bindée pour utiliser la fonction popUpIt.
7119         *
7120         * @return void
7121         */
7122        function view_overlay_notification_manuelle() {
7123    
7124            // Vérification de l'accessibilité sur l'élément
7125            $this->checkAccessibility();
7126    
7127            printf(
7128                '<script type="text/javascript" >
7129                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=411&idx=%3$s\', 1);
7130                </script>',
7131                'instruction_notification_manuelle',
7132                OM_ROUTE_SOUSFORM,
7133                $this->getVal($this->clePrimaire),
7134                $this->getVal('dossier')
7135            );
7136        }
7137    
7138        /**
7139       * Retourne l'événement d'instruction dont on donne le code-barres, avec un filtre       * Retourne l'événement d'instruction dont on donne le code-barres, avec un filtre
7140       * pour exclure les dossiers du groupe contentieux.       * pour exclure les dossiers du groupe contentieux.
7141       *       *
# Line 6476  class instruction extends instruction_ge Line 7618  class instruction extends instruction_ge
7618      }      }
7619    
7620      /**      /**
7621         * TREATMENT - envoyer_a_signature_sans_relecture
7622         *
7623         * Permet d'envoyer le document de l'instruction au parapheur pour signature sans relecture
7624         *
7625         * @return boolean true si l'envoi a été effectué avec succès false sinon
7626         */
7627        function envoyer_a_signature_sans_relecture() {
7628            return $this->envoyer_a_signature();
7629        }
7630    
7631        /**
7632         * TREATMENT - envoyer_a_signature_avec_relecture
7633         *
7634         * Permet d'envoyer le document de l'instruction au parapheur pour signature avec relecture
7635         *
7636         * @return boolean true si l'envoi a été effectué avec succès false sinon
7637         */
7638        function envoyer_a_signature_avec_relecture() {
7639            $is_forced_view_files = true;
7640            return $this->envoyer_a_signature($is_forced_view_files);
7641        }
7642    
7643        /**
7644         * TREATMENT - envoyer_a_signature
7645         *
7646         * Permet d'envoyer le document de l'instruction au parapheur pour signature
7647         *
7648         * @param  boolean  $is_forced_view_files  Indique si il y a une relecture (true) ou non (false)
7649         *
7650         * @return boolean true si l'envoi a été effectué avec succès false sinon
7651         */
7652        function envoyer_a_signature($is_forced_view_files = false) {
7653            $this->begin_treatment(__METHOD__);
7654            $this->correct = true;
7655    
7656            // Instanciation de l'objet signataire_arrete
7657            $inst_signataire_arrete = $this->f->get_inst__om_dbform(array(
7658                'obj' => 'signataire_arrete',
7659                'idx' => $this->getVal('signataire_arrete'),
7660            ));
7661    
7662            // Instanciation de l'objet dossier
7663            $inst_dossier = $this->f->get_inst__om_dbform(array(
7664                'obj' => 'dossier',
7665                'idx' => $this->getVal('dossier'),
7666            ));
7667    
7668            // Récupération du document à signer
7669            $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));
7670            if ($file === OP_FAILURE) {
7671                $this->correct = false;
7672                $this->addToMessage(__("Une erreur est survenue lors de la récupération du contenu du document de l'instruction."));
7673                // Termine le traitement
7674                return $this->end_treatment(__METHOD__, false);
7675            }
7676    
7677            // Initialisation des paramètre à passer pour l'envoi en signature
7678            $data = array(
7679                "om_utilisateur_email" => $this->f->om_utilisateur['email'],
7680                "om_utilisateur_nom" => $this->f->om_utilisateur['nom'],
7681                "signataire_arrete_email" => $inst_signataire_arrete->getVal('email'),
7682                "signataire_arrete_nom" => $inst_signataire_arrete->getVal('nom'),
7683                "signataire_arrete_prenom" => $inst_signataire_arrete->getVal('prenom'),
7684                "date_limite_instruction" => $inst_dossier->getVal('incomplet_notifie') === 't' ? $inst_dossier->getVal('date_limite_incompletude') : $inst_dossier->getVal('date_limite'),
7685                "dossier" => $this->getVal('dossier'),
7686                "is_forced_view_files" => $is_forced_view_files,
7687                'commentaire_signature' => $is_forced_view_files === true ? __('relecture demandee.') : null
7688            );
7689    
7690            // Initialisation des métadonnées
7691            $metadonnee_dossier = $file['metadata'];
7692            // récupération de l'extension du fichier
7693            $extension = substr($metadonnee_dossier['filename'], strrpos($metadonnee_dossier['filename'], '.'));
7694            // Modification du libellé du document transmis au parapheur
7695            // pour le mettre sous la forme : instruction_xxx_libelle_lettretype.extension
7696            $metadonnee_dossier['filename'] = $this->getDocumentLibelle().$extension;
7697            $metadonnee_dossier['titre_document'] = $this->getDocumentTitre();
7698    
7699            $metadonnee_dossier['url_di'] = sprintf(
7700                '%sapp/index.php?module=form&direct_link=true&obj=dossier_instruction&action=3&direct_field=dossier&direct_form=instruction&direct_action=3&direct_idx=%s',
7701                $this->f->get_param_base_path_metadata_url_di() !== null ? $this->f->get_param_base_path_metadata_url_di() : PATH_BASE_URL,
7702                $this->getVal($this->clePrimaire)
7703            );
7704    
7705            $optional_data = null;
7706            // Si il y a des paramètres supplémentaire spécifié dans le signataire alors on les récupère
7707            if ($inst_signataire_arrete->getVal('parametre_parapheur') !== null && $inst_signataire_arrete->getVal('parametre_parapheur') !== '') {
7708                $optional_data = json_decode($inst_signataire_arrete->getVal('parametre_parapheur'), true);
7709                if (json_last_error() !== JSON_ERROR_NONE) {
7710                    $this->correct = false;
7711                    $this->addToMessage(__("Les paramètres supplémentaires envoyés au parapheur ne sont pas au bon format."));
7712                    $this->addToLog(__METHOD__."(): ".
7713                        __("Erreur lors du décodage du format json des paramètres supplémentaires envoyé au parapheur.
7714                            Tableau : ").var_export($inst_signataire_arrete->getVal('parametre_parapheur'), true)
7715                    );
7716                    // Termine le traitement
7717                    return $this->end_treatment(__METHOD__, false);
7718                }
7719            }
7720    
7721            //Instanciation de la classe electronicsignature
7722            $inst_es = $this->get_electronicsignature_instance();
7723            if ($inst_es === false) {
7724                $this->correct = false;
7725                return $this->end_treatment(__METHOD__, false);
7726            }
7727    
7728            // Appel de la méthode de l'abstracteur send_for_signature()
7729            // Cette méthode doit retourner un tableau de valeur
7730            try {
7731                $result = $inst_es->send_for_signature($data, $file['file_content'], $metadonnee_dossier, $optional_data);
7732            }  catch (electronicsignature_exception $e) {
7733                $this->handle_electronicsignature_exception($e);
7734                return $this->end_treatment(__METHOD__, false);
7735            }
7736    
7737            // Après avoir reçu le résultat du parapheur, il faut mettre à jour les champs
7738            $valF = array();
7739    
7740            // Pour appeler la fonction modifier il faut traiter tous les champs de l'objet
7741            foreach($this->champs as $identifiant => $champ) {
7742                $valF[$champ] = $this->val[$identifiant];
7743            }
7744            // On fait ensuite nos modifications spécifiques
7745            $valF['id_parapheur_signature'] = $result['id_parapheur_signature'];
7746            $valF['statut_signature'] = $result['statut'];
7747            $valF['commentaire_signature'] = isset($result['commentaire_signature']) == true ? $result['commentaire_signature'] : null;
7748            $valF['date_envoi_signature'] = date("Y-m-d", strtotime($result['date_envoi_signature']));
7749            $valF['historique_signature'] = $this->get_updated_historique_signature($result);
7750    
7751            $ret = $this->modifier($valF);
7752    
7753            if ($ret === false) {
7754                $this->correct = false;
7755                $this->addToMessage(__("Une erreur est survenue lors de la mise à jour des champs."));
7756                // Termine le traitement
7757                return $this->end_treatment(__METHOD__, false);
7758            }
7759    
7760            // Message
7761            $this->addToMessage(__("Le document a été envoyé pour signature dans le parapheur."));
7762            if (array_key_exists('signature_page_url', $result) === true) {
7763                $this->addToMessage(sprintf(
7764                    '<br> > <a href="%1$s" title="%2$s" target="_blank">%2$s</a>',
7765                    $result['signature_page_url'],
7766                    __("Signez directement le document")
7767                ));
7768            }
7769    
7770            // Tout s'est bien passé, on termine le traitement
7771            return $this->end_treatment(__METHOD__, true);
7772        }
7773    
7774        /**
7775         * Permet de récupérer la traduction de la valeur de statut_signature
7776         *
7777         * @return string la valeur de statut_signature traduite | false
7778         */
7779        function get_trad_for_statut($value_to_trad){
7780            $statut_signature_tab = array(
7781                'waiting' => __('en préparation'),
7782                'in_progress' => __('en cours de signature'),
7783                'canceled' => __('signature annulée'),
7784                'expired' => __('délai de signature expiré'),
7785                'finished' => __('signé')
7786            );
7787            if (array_key_exists($value_to_trad, $statut_signature_tab) === true) {
7788                return $statut_signature_tab[$value_to_trad];
7789            }
7790    
7791            return false;
7792        }
7793    
7794        /**
7795         * Permet de mettre à jour le tableau json sotcké dans le champ historique_signature
7796         *
7797         * @return string (json) la valeur de historique_signature mis à jour | false
7798         */
7799        function get_updated_historique_signature($historique_signature_values) {
7800            
7801            $historique_signature_value_tab = $this->get_historique_signature_decoded();
7802    
7803            if ($historique_signature_value_tab === false) {
7804                $this->addToLog(__METHOD__."(): erreur historique signature", DEBUG_MODE);
7805                return false;
7806            }
7807    
7808            $last_val_historique_signature = array();
7809    
7810            // Si la tableau récupéré n'est pas vide alors
7811            // on récupère la dernière ligne du tableau
7812            if (empty($historique_signature_value_tab) === false) {
7813                $last_val_historique_signature = end($historique_signature_value_tab);
7814            }
7815    
7816            $format_date = '';
7817            $format_date_hour = '';
7818            $date_converted=array();
7819    
7820            $date_to_convert = array(
7821                'date_envoi_signature' => $historique_signature_values['date_envoi_signature'],
7822                'date_limite_instruction' => $historique_signature_values['date_limite_instruction'],
7823                'date_retour_signature' => $historique_signature_values['date_retour_signature']
7824            );
7825    
7826            // Conversion des dates en fonction de leur format
7827            foreach ($date_to_convert as $key => $value) {
7828                $date_converted[$key] = null;
7829                if ($value != null) {
7830                    $format_date = 'd/m/Y';
7831                    $format_date_hour = 'd/m/Y H:i:s';
7832                    $date_converted[$key] = empty(date_parse($value)['hour']) === false ? date($format_date_hour, strtotime($value)) : date($format_date, strtotime($value));
7833                }
7834            }
7835    
7836            // Ce tableau permet de lister les colonnes de historique_signature et de les rendre traduisibles.
7837            // Il faut en effet mettre les gettext avec l'intitulé explicite au moins
7838            // une fois afin qu'il puisse être reconnu par le logiciel de traduction.
7839            $tab_for_columns_trad = array(
7840                __('entry_date'),
7841                __('id_parapheur_signature'),
7842                __('emetteur'),
7843                __('signataire'),
7844                __('date_envoi'),
7845                __('date_limite'),
7846                __('date_retour'),
7847                __('statut_signature'),
7848                __('commentaire_signature')
7849            );
7850    
7851            array_push($historique_signature_value_tab, array(
7852                'entry_date' => date('d/m/Y H:i:s'),
7853                'id_parapheur_signature' => $historique_signature_values['id_parapheur_signature'] == null ? (isset($last_val_historique_signature['id_parapheur_signature']) === true ? $last_val_historique_signature['id_parapheur_signature'] : null) : $historique_signature_values['id_parapheur_signature'],
7854                'emetteur' => $historique_signature_values['om_utilisateur_email'] == null ? (isset($last_val_historique_signature['emetteur']) === true ? $last_val_historique_signature['emetteur'] : null) : $historique_signature_values['om_utilisateur_email'],
7855                'signataire' => $historique_signature_values['signataire_arrete_email'] == null ? (isset($last_val_historique_signature['signataire']) === true ? $last_val_historique_signature['signataire'] : null) : $historique_signature_values['signataire_arrete_email'],
7856                'date_envoi' => $historique_signature_values['date_envoi_signature'] == null ? (isset($last_val_historique_signature['date_envoi']) === true ? $last_val_historique_signature['date_envoi'] : null) : $date_converted['date_envoi_signature'],
7857                'date_limite' => $historique_signature_values['date_limite_instruction'] == null ? (isset($last_val_historique_signature['date_limite']) === true ? $last_val_historique_signature['date_limite'] : null) : $date_converted['date_limite_instruction'],
7858                'date_retour' => $historique_signature_values['date_retour_signature'] == null ? (isset($last_val_historique_signature['date_retour']) === true ? $last_val_historique_signature['date_retour'] : null) : $date_converted['date_retour_signature'],
7859                'statut_signature' => $historique_signature_values['statut'] == null ? (isset($last_val_historique_signature['statut_signature']) === true ? $last_val_historique_signature['statut_signature'] : null) : $this->get_trad_for_statut($historique_signature_values['statut']),
7860                'commentaire_signature' => isset($historique_signature_values['commentaire_signature']) === false || $historique_signature_values['commentaire_signature'] == null ? null : $historique_signature_values['commentaire_signature'],
7861            ));
7862            
7863            return json_encode($historique_signature_value_tab, JSON_HEX_APOS);
7864        }
7865    
7866    
7867        /**
7868         * Récupère le contenu du champ historique_signature et le converti en tableau
7869         *
7870         * @return array sinon false en cas d'erreur
7871         */
7872        protected function get_historique_signature_decoded() {
7873            $val = $this->getVal('historique_signature');
7874            if ($val === '') {
7875                $val = json_encode(array());
7876            }
7877            if($this->isJson($val) === false) {
7878                return false;
7879            }
7880            return json_decode($val, true);
7881        }
7882    
7883        /**
7884         * Récupère les informations à afficher dans le tableau de suivi à l'aide
7885         * d'une requête sql. Stocke ces informations dans un tableau.
7886         * Converti le tableau au format json et renvoi le json obtenu
7887         *
7888         * @return json
7889         */
7890        protected function get_json_suivi_notification() {
7891            $valSuivi = array();
7892            // Liste des champs à afficher. Permet également la traduction des noms de colonnes.
7893            $listeChampsTrad = array(
7894                __('emetteur'),
7895                __('date_envoi'),
7896                __('destinataire'),
7897                __('date_premier_acces'),
7898                __('instruction'),
7899                __('statut'),
7900                __('commentaire')
7901            );
7902            $listeChamps = array(
7903                'emetteur',
7904                'date_envoi',
7905                'destinataire',
7906                'date_premier_acces',
7907                'instruction',
7908                'statut',
7909                'commentaire'
7910            );
7911    
7912            // Récupération des infos nécessaires à l'affichage du tableau
7913            $sql = sprintf(
7914                'SELECT
7915                    instruction_notification.instruction_notification,
7916                    CASE WHEN instruction_notification.automatique = TRUE
7917                        THEN TRIM(CONCAT(instruction_notification.emetteur, \' \', \'(automatique)\'))
7918                        ELSE instruction_notification.emetteur
7919                    END as emetteur,
7920                    date_envoi,
7921                    instruction_notification.destinataire,
7922                    instruction_notification.date_premier_acces,
7923                    evenement.libelle as instruction,
7924                    instruction_notification.statut,
7925                    instruction_notification.commentaire,
7926                    instruction_notification_document.instruction as instruction_annexe
7927                FROM
7928                    %1$sinstruction_notification
7929                    LEFT JOIN %1$sinstruction
7930                        ON instruction.instruction = instruction_notification.instruction
7931                    LEFT JOIN %1$sevenement
7932                        ON instruction.evenement = evenement.evenement
7933                    LEFT JOIN %1$sinstruction_notification_document
7934                        ON instruction_notification.instruction_notification = instruction_notification_document.instruction_notification
7935                        AND instruction_notification_document.annexe = true
7936                WHERE
7937                    instruction.instruction = %2$s
7938                ORDER BY
7939                    date_envoi ASC, instruction_notification.destinataire ASC',
7940                DB_PREFIXE,
7941                $this->getVal('instruction')
7942            );
7943            $res = $this->f->db->query($sql);
7944            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
7945            $this->f->isDatabaseError($res);
7946            // Stockage des infos de chaque notification dans un tableau
7947            while( $row =& $res->fetchrow(DB_FETCHMODE_ASSOC) ) {
7948                $valNotif = array();
7949                foreach($listeChamps as $champ) {
7950                    $valNotif[$champ] = $row[$champ];
7951                    if (($champ === 'date_envoi'
7952                        || $champ === 'date_premier_acces')
7953                        && $row[$champ] !== null
7954                        && $row[$champ] !== '') {
7955                        //
7956                        $valNotif[$champ] = date('d/m/Y H:i:s', strtotime($row[$champ]));
7957                    }
7958                }
7959                if ($row['instruction_annexe'] !== null && $row['instruction_annexe'] !== '') {
7960                    $inst_instruction = $this->f->get_inst__om_dbform(array(
7961                        "obj" => "instruction",
7962                        "idx" => $row['instruction_annexe'],
7963                    ));
7964                    $inst_evenement = $inst_instruction->get_inst_evenement();
7965                    $lienAnnexe = ' ('.$inst_evenement->getVal('libelle').')';
7966                    $valNotif['instruction'] .= $lienAnnexe;
7967                }
7968                array_push($valSuivi, $valNotif);
7969            }
7970    
7971            // Passage du tableau au format json
7972            return json_encode($valSuivi, JSON_HEX_APOS);
7973        }
7974    
7975        /**
7976         * Traitement des erreurs retournées par l'abstracteur electronicsignature.
7977         *
7978         * @param electronicsignature_exception $exception Exception retournée par l'abstracteur.
7979         *
7980         * @return void
7981         */
7982        public function handle_electronicsignature_exception(electronicsignature_exception $exception) {
7983            $this->f->displayMessage('error', $exception->getMessage());
7984        }
7985    
7986    
7987        /**
7988         * Retourne une instance du connecteur electronicsignature, et la créer si elle n'existe pas.
7989         *
7990         * @param  boolean $with_handle_error Flag pour afficher ou non le message d'erreur à l'utilisateur.
7991         * @return electronicsignature        Instance de l'abstracteur.
7992         */
7993        public function get_electronicsignature_instance($with_handle_error = true) {
7994            if(isset($this->electronicsignature_instance)) {
7995                return $this->electronicsignature_instance;
7996            }
7997            // Instanciation du connecteur electronicsignature
7998            try {
7999                require_once "electronicsignature.class.php";
8000                $collectivites = array("collectivite_idx" => $this->get_dossier_instruction_om_collectivite(), "collectivite_multi_idx" => $this->f->get_idx_collectivite_multi());
8001                $this->electronicsignature_instance = new electronicsignature($collectivites);
8002            } catch (electronicsignature_exception $e) {
8003                if ($with_handle_error === true) {
8004                    $this->handle_electronicsignature_exception($e);
8005                }
8006                return false;
8007            }
8008            return $this->electronicsignature_instance;
8009        }
8010    
8011        /**
8012         * TREATMENT - envoyer_au_controle_de_legalite
8013         *
8014         * Ajoute la tâche envoi_CL.
8015         * C'est le traitement de la tâche qui mettra à jour la date d'envoi au contrôle de légalité.
8016         *
8017         * @return [type] [description]
8018         */
8019        function envoyer_au_controle_de_legalite() {
8020            $this->begin_treatment(__METHOD__);
8021            $this->correct = true;
8022    
8023            //
8024            if ($this->can_be_sended_to_cl() === true) {
8025                // Création de la task 'envoi_CL'
8026                $inst_task = $this->f->get_inst__om_dbform(array(
8027                    "obj" => "task",
8028                    "idx" => 0,
8029                ));
8030                $task_val = array(
8031                    'type' => 'envoi_CL',
8032                    'object_id' => $this->getVal('instruction'),
8033                    'dossier' => $this->getVal('dossier'),
8034                );
8035                // Change l'état de la tâche de notification en fonction de l'état de
8036                // transmission du dossier d'instruction
8037                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
8038                if ($this->f->is_option_mode_service_consulte_enabled() === false
8039                    && ($inst_di->getVal('etat_transmission_platau') == 'non_transmissible'
8040                    || $inst_di->getVal('etat_transmission_platau') == 'transmis_mais_non_transmissible')) {
8041                    //
8042                    $task_val['state'] = $inst_task::STATUS_DRAFT;
8043                }
8044                $add_task = $inst_task->add_task(array('val' => $task_val));
8045                if ($add_task === false) {
8046                    $this->addToMessage(sprintf('%s %s',
8047                        __("Une erreur s'est produite lors de la création tâche."),
8048                        __("Veuillez contacter votre administrateur.")
8049                    ));
8050                    $this->correct = false;
8051                    return $this->end_treatment(__METHOD__, false);
8052                }
8053                // Mise à jour du champs 'envoye_cl_platau'
8054                $instr_val = array(
8055                    'envoye_cl_platau' => 't',
8056                );
8057                $res = $this->f->db->autoExecute(
8058                    DB_PREFIXE.$this->table,
8059                    $instr_val,
8060                    DB_AUTOQUERY_UPDATE,
8061                    $this->getCle($this->getVal($this->clePrimaire))
8062                );
8063                $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($instr_val, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($this->clePrimaire)."\");", DEBUG_MODE);
8064                if ($this->f->isDatabaseError($res, true) === true) {
8065                    $this->addToMessage(sprintf('%s %s',
8066                        __("Une erreur s'est produite lors de la mise à jour de l'instruction."),
8067                        __("Veuillez contacter votre administrateur.")
8068                    ));
8069                    $this->correct = false;
8070                    return $this->end_treatment(__METHOD__, false);
8071                }
8072                // Message de validation à l'utilisateur
8073                $this->addToMessage(__('Votre demande de transfert au contrôle de légalité à bien été prise en compte.'));
8074                $this->addToMessage(__("La date d'envoi au contrôle de légalité sera mise à jour ultérieurement."));
8075            }
8076            //
8077            return $this->end_treatment(__METHOD__, true);
8078        }
8079    
8080    
8081        /**
8082       * Retourne le lien de retour (VIEW formulaire et VIEW sousformulaire).       * Retourne le lien de retour (VIEW formulaire et VIEW sousformulaire).
8083       *       *
8084       * @param string $view Appel dans le contexte de la vue 'formulaire' ou de       * @param string $view Appel dans le contexte de la vue 'formulaire' ou de
# Line 6519  class instruction extends instruction_ge Line 8122  class instruction extends instruction_ge
8122          return $href;          return $href;
8123      }      }
8124    
8125        public function view_json_data() {
8126            $this->checkAccessibility();
8127            $this->f->disableLog();
8128            $view = $this->get_json_data();
8129            printf(json_encode($view));
8130        }
8131    
8132        public function get_json_data() {
8133            $val = array_combine($this->champs, $this->val);
8134            foreach ($val as $key => $value) {
8135                $val[$key] = strip_tags($value);
8136            }
8137            $val['tacite'] = 'f';
8138            $inst_ad = $this->f->get_inst__om_dbform(array(
8139                "obj" => "avis_decision",
8140                "idx" => $val['avis_decision'],
8141            ));
8142            if (preg_match('/[tT]acite/', $inst_ad->getVal('libelle')) === 1) {
8143                $val['tacite'] = 't';
8144            }
8145            return $val;
8146        }
8147    
8148        public function get_related_instructions_next($next_type = 'retour_signature', $instruction = null) {
8149            if (in_array($next_type, array('retour_signature', 'retour_ar', 'suivant_tacite', )) === false) {
8150                return false;
8151            }
8152            $result = array();
8153            $evenements = array();
8154            if ($instruction === null) {
8155                $instruction = $this->getVal($this->clePrimaire);
8156                $evenement = $this->getVal('evenement');
8157                $dossier = $this->getVal('dossier');
8158            } else {
8159                $inst = $this->f->get_inst__om_dbform(array(
8160                    "obj" => "instruction",
8161                    "idx" => $instruction,
8162                ));
8163                $evenement = $inst->getVal('evenement');
8164                $dossier = $inst->getVal('dossier');
8165            }
8166            //
8167            $query = sprintf('
8168                SELECT evenement_%3$s
8169                FROM %1$sevenement
8170                WHERE evenement = %2$s
8171                ',
8172                DB_PREFIXE,
8173                $evenement,
8174                $next_type
8175            );
8176            $res = $this->f->get_one_result_from_db_query($query, true);
8177            if ($res['code'] === 'KO') {
8178                return false;
8179            }
8180            $ev_next = $res['result'];
8181            //
8182            $query = sprintf('
8183                SELECT MAX(instruction.instruction) as instruction
8184                FROM %1$sinstruction
8185                WHERE dossier = \'%3$s\'
8186                    AND evenement = %2$s
8187                ',
8188                DB_PREFIXE,
8189                $ev_next,
8190                $dossier
8191            );
8192            $res = $this->f->get_one_result_from_db_query($query, true);
8193            if ($res['code'] === 'KO') {
8194                return false;
8195            }
8196            //
8197            return $res['result'];
8198        }
8199    
8200        public function get_related_instructions($instruction = null) {
8201            $result = array();
8202            $evenements = array();
8203            if ($instruction === null) {
8204                $instruction = $this->getVal($this->clePrimaire);
8205                $evenement = $this->getVal('evenement');
8206                $dossier = $this->getVal('dossier');
8207            } else {
8208                $inst = $this->f->get_inst__om_dbform(array(
8209                    "obj" => "instruction",
8210                    "idx" => $instruction,
8211                ));
8212                $evenement = $inst->getVal('evenement');
8213                $dossier = $inst->getVal('dossier');
8214            }
8215            //
8216            $query = sprintf('
8217                SELECT evenement
8218                FROM %1$sevenement
8219                WHERE evenement_retour_ar = %2$s
8220                    OR evenement_retour_signature = %2$s
8221                ',
8222                DB_PREFIXE,
8223                $evenement
8224            );
8225            $res = $this->f->get_one_result_from_db_query($query, true);
8226            if ($res['code'] === 'KO') {
8227                return false;
8228            }
8229            $ev_parent = $res['result'];
8230            //
8231            $query = sprintf('
8232                SELECT MAX(instruction.instruction) as instruction
8233                FROM %1$sinstruction
8234                WHERE dossier = \'%3$s\'
8235                    AND evenement = %2$s
8236                ',
8237                DB_PREFIXE,
8238                $ev_parent,
8239                $dossier
8240            );
8241            $res = $this->f->get_one_result_from_db_query($query, true);
8242            if ($res['code'] === 'KO') {
8243                return false;
8244            }
8245            $result[] = $res['result'];
8246            //
8247            $query = sprintf('
8248                SELECT evenement_retour_ar
8249                FROM %1$sevenement
8250                WHERE evenement = %2$s
8251                    AND evenement_retour_ar != %3$s
8252                ',
8253                DB_PREFIXE,
8254                $ev_parent,
8255                $evenement
8256            );
8257            $res = $this->f->get_one_result_from_db_query($query, true);
8258            if ($res['code'] === 'KO') {
8259                return false;
8260            }
8261            $evenements[] = $res['result'];
8262            //
8263            $query = sprintf('
8264                SELECT evenement_retour_signature
8265                FROM %1$sevenement
8266                WHERE evenement = %2$s
8267                    AND evenement_retour_signature != %3$s
8268                ',
8269                DB_PREFIXE,
8270                $ev_parent,
8271                $evenement
8272            );
8273            $res = $this->f->get_one_result_from_db_query($query, true);
8274            if ($res['code'] === 'KO') {
8275                return false;
8276            }
8277            $evenements[] = $res['result'];
8278            foreach ($evenements as $value) {
8279                if ($value !== null) {
8280                    $query = sprintf('
8281                        SELECT MAX(instruction.instruction) as instruction
8282                        FROM %1$sinstruction
8283                        WHERE dossier = \'%3$s\'
8284                            AND evenement = %2$s
8285                        ',
8286                        DB_PREFIXE,
8287                        $value,
8288                        $dossier
8289                    );
8290                    $res = $this->f->get_one_result_from_db_query($query, true);
8291                    if ($res['code'] === 'KO') {
8292                        return false;
8293                    }
8294                    $result[] = $res['result'];
8295                }
8296            }
8297            return $result;
8298        }
8299    
8300        protected function getDocumentType($champ = null) {
8301            $evenementId = $this->getVal('evenement');
8302            if (! empty($evenementId)) {
8303                $evenement = $this->f->findObjectById('evenement', $evenementId);
8304                if (! empty($evenement)) {
8305                    return __("Instruction").':'.$evenement->getVal('libelle');
8306                }
8307            }
8308            return parent::getDocumentType();
8309        }
8310    
8311        /**
8312         * Récupère à l'aide d'une requête sql la liste des demandeurs
8313         * pouvant être notifié. C'est à dire les demandeurs acceptant
8314         * les notifications et pour lesquels une adresse mail existe.
8315         *
8316         * Dans le cas, d'une notification pour le portail citoyen, seul
8317         * le pétitionnaire principal doit être notifier et uniquement si
8318         * il a une adress mail et qu'il accepte les notifications.
8319         *
8320         * @param string identifiant du dossier
8321         * @param boolean true si il faut récupérer la liste des demandeurs notifiable
8322         * pour une notification de categorie portail
8323         * @return array liste des demandeurs pouvant être notifié
8324        */
8325        protected function get_demandeurs_notifiable($idDossier = null, $portail = false) {
8326            if ($idDossier === null) {
8327                $idDossier = $this->getVal('dossier');
8328            }
8329            // Ajoute une condition sur le where pour ne récupérer que le pétitionnaire principal
8330            // pour une notification depuis le portail citoyen
8331            $sqlPetitionnairePrincipal = '';
8332            if ($portail === true) {
8333                $sqlPetitionnairePrincipal = 'AND lien_dossier_demandeur.petitionnaire_principal = true';
8334            }
8335    
8336            $listeDemandeursNotifiable = array();
8337    
8338            // Requête de récupération des demandeurs
8339            $sql = sprintf(
8340                'SELECT
8341                    demandeur.demandeur,
8342                    CASE
8343                        WHEN demandeur.qualite=\'particulier\'
8344                        THEN TRIM(CONCAT(demandeur.particulier_nom, \' \', demandeur.particulier_prenom, \' \', demandeur.courriel))
8345                    ELSE
8346                        TRIM(CONCAT(demandeur.personne_morale_raison_sociale, \' \', demandeur.personne_morale_denomination, \' \', demandeur.courriel))
8347                    END AS destinataire,
8348                    demandeur.courriel
8349                FROM
8350                    %1$sdossier
8351                    INNER JOIN %1$slien_dossier_demandeur
8352                        ON dossier.dossier = lien_dossier_demandeur.dossier
8353                    INNER JOIN %1$sdemandeur
8354                        ON lien_dossier_demandeur.demandeur = demandeur.demandeur
8355                WHERE
8356                    dossier.dossier = \'%2$s\' AND
8357                    notification = \'t\' AND
8358                    courriel IS NOT NULL
8359                    %3$s',
8360                DB_PREFIXE,
8361                $idDossier,
8362                $sqlPetitionnairePrincipal
8363            );
8364            $res = $this->f->db->query($sql);
8365            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
8366            $this->f->isDatabaseError($res);
8367            // Récupération des infos des demandeurs et stockage dans un tableau
8368            // ayant pour clé les id des demandeurs
8369            while($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {
8370                $listeDemandeursNotifiable[$row['demandeur']] = $row;
8371            }
8372    
8373            return $listeDemandeursNotifiable;
8374        }
8375    
8376        /**
8377         * Renvoie la liste des notifications liées à l'instruction
8378         *
8379         * @param integer id de l'instruction dont on cherche les notifications
8380         * @return array liste des instruction_notification liés à l'instruction
8381         */
8382        public function get_instruction_notification($id_instruction) {
8383            $listeInstrNotif = array();
8384            $sql = sprintf('
8385                SELECT
8386                    instruction_notification.instruction_notification
8387                FROM
8388                    %1$sinstruction_notification
8389                WHERE
8390                    instruction = %2$s',
8391                DB_PREFIXE,
8392                $id_instruction
8393            );
8394            $res = $this->f->db->query($sql);
8395            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
8396            $this->f->isDatabaseError($res);
8397            while ($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {
8398                $listeInstrNotif[] = $row['instruction_notification'];
8399            }
8400            return $listeInstrNotif;
8401        }
8402    
8403        /**
8404         * Crée une clé d'accès unique permettant à un utilisateur
8405         * anonyme de récupérer le document.
8406         *
8407         * @return string clé d'accès du document
8408         */
8409        protected function getCleAccesDocument() {
8410            // Initialisation d'un tableau
8411            $number_list = array();
8412    
8413            // Génération aléatoire d'un nombre sur 4 caractères, 4 fois
8414            for ($i = 0; $i < 4; $i++) {
8415                $number_list[] = str_pad(mt_rand(0, 9999), 4, 0, STR_PAD_LEFT);
8416            }
8417    
8418            // Transformation en chaîne tout en séparant les nombres par un "-"
8419            $result = implode('-', $number_list);
8420    
8421            // Vérifie si la clé existe déjà et si c'est le cas génére une nouvelle clé
8422            if ($this->getUidDocumentInstructionWithKey($result) != null) {
8423                return $this->getCleAccesDocument();
8424            }
8425    
8426            //
8427            return $result;
8428        }
8429    
8430        /**
8431         * Récupère une clé et renvoie l'uid du document liée à cette
8432         * clé. Si la clé n'existe pas renvoie null.
8433         *
8434         * @param string $cleGen clé dont on cherche l'instruction
8435         * @return integer|null
8436         */
8437        protected function getUidDocumentInstructionWithKey($cleGen) {
8438            $query = sprintf(
8439                'SELECT
8440                    instruction.om_fichier_instruction
8441                FROM
8442                    %1$sinstruction_notification_document
8443                    LEFT JOIN %1$sinstruction ON instruction_notification_document.instruction = instruction.instruction
8444                WHERE
8445                    instruction_notification_document.cle = \'%2$s\'',
8446                DB_PREFIXE,
8447                $this->f->db->escapeSimple($cleGen)
8448            );
8449    
8450            $res = $this->f->db->getOne($query);
8451            $this->addToLog(__METHOD__.": db->getOne(\"".$query."\");", VERBOSE_MODE);
8452            $this->f->isDatabaseError($res);
8453            return $res;
8454        }
8455    
8456        /**
8457         * Récupère une clé, fait une requête pour récupérer l'id de la notification liée a cette clé.
8458         * Récupère l'instance de instruction_notification dont l'id a été récupéré et la renvoie.
8459         *
8460         * @param string $cleGen
8461         * @return instruction_notification
8462         */
8463        protected function getInstanceNotificationWithKey($key) {
8464            $sql = sprintf(
8465                "SELECT
8466                    instruction_notification
8467                FROM
8468                    %1\$sinstruction_notification_document
8469                WHERE
8470                    cle = '%2\$s'",
8471                DB_PREFIXE,
8472                $this->f->db->escapeSimple($key)
8473            );
8474            $res = $this->f->db->getOne($sql);
8475            $this->addToLog(__METHOD__.": db->getOne(\"".$sql."\");", VERBOSE_MODE);
8476            $this->f->isDatabaseError($res);
8477    
8478            // Récupération de l'instance de notification
8479            $instNotif = $this->f->get_inst__om_dbform(array(
8480                "obj" => "instruction_notification",
8481                "idx" => $res,
8482            ));
8483            return $instNotif;
8484        }
8485    
8486    
8487        /**
8488         * Affiche la page de téléchargement du document de la notification.
8489         *
8490         * @param boolean $content_only Affiche le contenu seulement.
8491         *
8492         * @return void
8493         */
8494        public function view_telecharger_document_anonym() {
8495            // Par défaut on considère qu'on va afficher le formulaire
8496            $idx = 0;
8497            // Flag d'erreur
8498            $error = false;
8499            // Message d'erreur
8500            $message = '';
8501    
8502            // Paramètres GET : récupération de la clé d'accès
8503            $cle_acces_document = $this->f->get_submitted_get_value('key');
8504            $cle_acces_document = $this->f->db->escapeSimple($cle_acces_document);
8505            // Vérification de l'existence de la clé et récupération de l'uid du fichier
8506            $uidFichier = $this->getUidDocumentInstructionWithKey($cle_acces_document);
8507            if ($uidFichier != null) {
8508                // Récupération du document
8509                $file = $this->f->storage->get($uidFichier);
8510    
8511                // Headers
8512                header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
8513                header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date dans le passé
8514                header("Content-Type: ".$file['metadata']['mimetype']);
8515                header("Accept-Ranges: bytes");
8516                header("Content-Disposition: inline; filename=\"".$file['metadata']['filename']."\";" );
8517                // Affichage du document
8518                echo $file['file_content'];
8519    
8520                // Récupération de la date de premier accès et maj du suivi uniquement
8521                // si la date de 1er accès n'a pas encore été remplis
8522                $inst_notif = $this->getInstanceNotificationWithKey($cle_acces_document);
8523                if ($inst_notif->getVal('date_premier_acces') == null ||
8524                    $inst_notif->getVal('date_premier_acces') == '') {
8525                    $notif_val = array();
8526                    foreach ($inst_notif->champs as $champ) {
8527                        $notif_val[$champ] = $inst_notif->getVal($champ);
8528                    }
8529                    $notif_val['date_premier_acces'] = date("d/m/Y H:i:s");
8530                    $notif_val['statut'] = 'vu';
8531                    $notif_val['commentaire'] = 'Le document a été vu';
8532                    $suivi_notif = $inst_notif->modifier($notif_val);
8533                }
8534    
8535            } else {
8536                // Page vide 404
8537                printf('Ressource inexistante');
8538                header('HTTP/1.0 404 Not Found');
8539            }
8540        }
8541    
8542        /**
8543         * Récupère le titre du document envoyé au parapheur
8544         */
8545        protected function getDocumentTitre($champ = null) {
8546            $title = $this->getTitle();
8547            $dossier = $this->getDossier();
8548            return $dossier.' '.$title;
8549        }
8550    
8551        /**
8552         * Compose le nom du document à transmettre au parapheur.
8553         * Le nom ets composé de cette manière :
8554         * instruction_xxx_libelle_de_la_lettre_type_associee
8555         * ou xxx correspond au numéro de l'instruction
8556         */
8557        protected function getDocumentLibelle() {
8558            // Récupère le champ instruction
8559            $instruction = $this->getVal("instruction");
8560    
8561            // Requête sql servant à récupérer le titre du document
8562            // TO_CHAR() introduit un espace avant l'affichage du nombre
8563            // comme les espaces sont remplacé par des '_' dans le retour de la fonction
8564            // il n'est pas nécessaire de mettre un '_' après le mot instruction.
8565            $sql = sprintf(
8566                'SELECT
8567                    CONCAT(
8568                        \'instruction\',
8569                        TO_CHAR(instruction.instruction, \'000\'),
8570                        \'_\',
8571                        LOWER(om_lettretype.libelle)
8572                    ) as nom_fichier
8573                FROM
8574                    %1$sinstruction
8575                    LEFT JOIN %1$som_lettretype ON om_lettretype.id = instruction.lettretype
8576                WHERE
8577                    instruction = %2$s',
8578                DB_PREFIXE,
8579                $instruction
8580            );
8581            $documentLibelle = $this->f->db->getOne($sql);
8582            $this->addToLog("getDocumentTitre(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
8583            if (database::isError($documentLibelle)) {
8584                die();
8585            }
8586    
8587            // Transforamtion des ' ' en '_', des accents en lettres sans accents et des
8588            // caractères spéciaux en '_'
8589            // La méthode normalize_string est utilisé pour gérer les accents
8590            $documentLibelle = $this->f->normalize_string($documentLibelle);
8591            // TODO : comparer cette liste et celle de la méthode normalize_string
8592            // pour éviter les doublons + vérifier qu'il n'y a pas de doublons dans cette
8593            // liste
8594            $invalid = array('Œ'=>'oe', 'œ'=>'oe', 'Ÿ'=>'y', 'ü'=>'u',
8595                '¢' => '_', 'ß' => '_', '¥' => '_', '£' => '_', '™' => '_', '©' => '_',
8596                '®' => '_', 'ª' => '_', '×' => '_', '÷' => '_', '±' => '_', '²' => '_',
8597                '³' => '_', '¼' => '_', '½' => '_', '¾' => '_', 'µ' => '_', '¿' => '_',
8598                '¶' => '_', '·' => '_', '¸' => '_', 'º' => '_', '°' => '_', '¯' => '_',
8599                '§' => '_', '…' => '_', '¤' => '_', '¦' => '_', '≠' => '_', '¬' => '_',
8600                'ˆ' => '_', '¨' => '_', '‰' => '_', '¤' => '_', '€' => '_', '$' => '_',
8601                '«' => '_', '»' => '_', '‹' => '_', '›' => '_', 'ƒ' => '_', '¥' => '_',
8602                '‘‘' => '_', '‚' => '_', '!' => '_', '¡' => '_', '¢' => '_', '£' => '_',
8603                '?' => '_', '[' => '_', ']' => '_', '´' => '_', '`' => '_', '^' => '_',
8604                '~' => '_', '˜' => '_', '#' => '_', '*' => '_', '.' => '_', ':' => '_',
8605                ';' => '_', '•' => '_', '¯' => '_', '‾' => '_', '–' => '_', '–' => '_',
8606                '—' => '_', '_' => '_', '|' => '_', '¦‌' => '_', '‡' => '_', '§' => '_',
8607                '¶' => '_', '©' => '_', '®' => '_', '™' => '_', '&' => '_', '@' => '_',
8608                '/' => '_', '\\' => '_', '◊' => '_', '♠' => '_', '♣' => '_', '♥' => '_',
8609                '♦' => '_', '←' => '_', '↑' => '_', '→' => '_', '↓' => '_', '↔' => '_',
8610                '°' => '_', 'µ' => '_', '<' => '_', '>' => '_', '≤' => '_', '≥' => '_',
8611                '=' => '_', '≈' => '_', '≠' => '_', '≡' => '_', '±' => '_', '−' => '_',
8612                '+' => '_', '×' => '_', '÷' => '_', '⁄' => '_', '%' => '_', '‰' => '_',
8613                '¼' => '_', '½' => '_', '¾' => '_', '¹' => '_', '²' => '_', '³' => '_',
8614                '' => '_', 'º' => '_', 'ª' => '_', 'ƒ' => '_', '′' => '_', '″' => '_',
8615                '∂' => '_', '∏' => '_', '∑' => '_', '√' => '_', '∞' => '_', '¬' => '_',
8616                '∩' => '_', '∫' => '_', 'α' => '_', 'Α' => '_', 'β' => '_', 'Β' => '_',
8617                'γ' => '_', 'Γ' => '_', 'δ' => '_', 'Δ' => '_', 'ε' => '_', 'Ε' => '_',
8618                'ζ' => '_', 'Ζ' => '_', 'η' => '_', 'Η' => '_', 'θ' => '_', 'Θ' => '_',
8619                'ι' => '_', 'Ι' => '_', 'κ' => '_', 'Κ' => '_', 'λ' => '_', 'Λ' => '_',
8620                'μ' => '_', 'Μ' => '_', 'ν' => '_', 'Ν' => '_', 'ξ' => '_', 'Ξ' => '_',
8621                'ο' => '_', 'Ο' => '_', 'π' => '_', 'Π' => '_', 'ρ' => '_', 'Ρ' => '_',
8622                'σ' => '_', 'ς' => '_', 'Σ' => '_', 'τ' => '_', 'Τ' => '_', 'υ' => '_',
8623                'Υ' => '_', 'φ' => '_', 'Φ' => '_', 'χ' => '_', 'Χ' => '_', 'ψ' => '_',
8624                'Ψ' => '_', 'ω' => '_', 'Ω' => '_', ',' => '_', ' ' => '_'
8625            );
8626    
8627            return str_replace(array_keys($invalid), array_values($invalid), $documentLibelle);
8628        }
8629    
8630        /**
8631         * Surcharge permettant de ne pas afficher le fil d'Ariane dans
8632         * l'overlay de notification des demandeurs.
8633         */
8634        function getSubFormTitle($ent) {
8635            if ($this->getParameter('maj') == '411') {
8636                return '';
8637            }
8638            return parent::getSubFormTitle($ent);
8639        }
8640  }// fin classe  }// fin classe

Legend:
Removed from v.8989  
changed lines
  Added in v.11418

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26