/[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 11418 by softime, Mon Feb 7 14:59:54 2022 UTC revision 15218 by softime, Thu Jul 13 10:31:27 2023 UTC
# Line 190  class instruction extends instruction_ge Line 190  class instruction extends instruction_ge
190              ),              ),
191          );          );
192    
193            // ACTION - 115 - Modification d'un document généré par une instruction
194            // Permet à un instructeur de modifier un document généré par une instruction
195            $this->class_actions[115] = array(
196                "identifier" => "modale_selection_document_signe",
197                "portlet" => array(
198                    "type" => "action-self",
199                    "libelle" => _("Remplacer par le document signé"),
200                    "order" => 115,
201                    "class" => "selection-document-signé",
202                ),
203                "view" => "view_modale_selection_document_signe",
204                "permission_suffix" => "selection_document_signe",
205                "condition" => array(
206                    "is_finalized",
207                    "is_not_date_retour_signature_set",
208                ),
209            );
210    
211          // ACTION - 120 - edition          // ACTION - 120 - edition
212          // Affiche l'édition          // Affiche l'édition
213          $this->class_actions[120] = array(          $this->class_actions[120] = array(
# Line 260  class instruction extends instruction_ge Line 278  class instruction extends instruction_ge
278              "permission_suffix" => "consulter",              "permission_suffix" => "consulter",
279          );          );
280    
281            // ACTION - 175 - edit_by_notification_task
282            // Action à utiliser lors de la mise à jour des instructions par notification
283            $this->class_actions[175] = array(
284                "identifier" => "edit_by_notification_task",
285                "view" => "formulaire",
286                "permission_suffix" => "modifier",
287                "crud" => "update",
288            );
289    
290            // ACTION - 176 - add_by_evenement_retour_after_notification_task
291            // Action à utiliser lors de l'ajout des instructions par événement suivant
292            // suite à une notification par tâche (donc notification dématerialisée)
293            $this->class_actions[176] = array(
294                "identifier" => "add_by_evenement_retour_after_notification_task",
295                "view" => "formulaire",
296                "permission_suffix" => "ajouter",
297                "crud" => "create",
298            );
299    
300          // ACTION - 180 - pdf_lettre_rar          // ACTION - 180 - pdf_lettre_rar
301          // Génère PDF sur bordereaux de lettres AR          // Génère PDF sur bordereaux de lettres AR
302          $this->class_actions[180] = array(          $this->class_actions[180] = array(
# Line 411  class instruction extends instruction_ge Line 448  class instruction extends instruction_ge
448              "permission_suffix" => "envoyer_a_signature",              "permission_suffix" => "envoyer_a_signature",
449          );          );
450    
451            // ACTION - 404 - Annuler l'envoi en signature
452            // Cet évenement permet d'annuler l'envoi en signature du document au parapheur
453            $this->class_actions[404] = array(
454                "identifier" => "annuler_envoi_signature",
455                "portlet" => array(
456                    "libelle" => __("Annuler l'envoi en signature"),
457                    "type" => "action-direct-with-confirmation",
458                    "class" => "annuler_envoi_signature-16",
459                ),
460                "view" => "formulaire",
461                "method" => "annuler_envoi_en_signature",
462                "condition" => array(
463                    "is_sent_for_signature",
464                    "is_parapheur_annulation_parameter_enabled"
465                ),
466                "permission_suffix" => "envoyer_a_signature",
467            );
468    
469          //          //
470          $this->class_actions[401] = array(          $this->class_actions[401] = array(
471              "identifier" => "preview_edition",              "identifier" => "preview_edition",
# Line 434  class instruction extends instruction_ge Line 489  class instruction extends instruction_ge
489              "permission_suffix" => "modifier",              "permission_suffix" => "modifier",
490          );          );
491    
492          // ACTION - 410 - Notifier les pétitionnaires (portail citoyen)          // ACTION - 411 - Notifier les pétitionnaires (portail citoyen)
493          $this->class_actions[411] = array(          $this->class_actions[411] = array(
494              "identifier" => "notification_manuelle_portal",              "identifier" => "notification_manuelle_portal",
495              "portlet" => array(              "portlet" => array(
# Line 446  class instruction extends instruction_ge Line 501  class instruction extends instruction_ge
501                  "is_notifiable_by_task_manual",                  "is_notifiable_by_task_manual",
502                  "is_portail_notification_sans_annexe"                  "is_portail_notification_sans_annexe"
503              ),              ),
504              "method" => "notifier_demandeur_principal",              "method" => "notifier_demandeur_principal_via_portal",
505              "permission_suffix" => "modifier",              "permission_suffix" => "modifier",
506          );          );
507    
508            // ACTION - 420 - Notifier les services consultés (mail)
509            $this->class_actions[420] = array(
510                "identifier" => "overlay_notification_service_consulte",
511                "portlet" => array(
512                    "libelle" => __("Notifier les services consultés"),
513                    "type" => "action-self",
514                    "class" => "notifier_commune-16",
515                ),
516                "condition" => array(
517                    "is_service_notifiable"
518                ),
519                "view" => "view_overlay_notification_service_consulte",
520                "permission_suffix" => "tab",
521            );
522    
523            // ACTION - 430 - Notifier les tiers consultés (mail)
524            $this->class_actions[430] = array(
525                "identifier" => "overlay_notification_tiers_consulte",
526                "portlet" => array(
527                    "libelle" => __("Notifier les tiers consultés"),
528                    "type" => "action-self",
529                    "class" => "notifier_commune-16",
530                ),
531                "condition" => array(
532                    "is_tiers_notifiable"
533                ),
534                "view" => "view_overlay_notification_tiers_consulte",
535                "permission_suffix" => "tab",
536            );
537    
538          //          //
539          $this->class_actions[403] = array(          $this->class_actions[403] = array(
540              "identifier" => "envoyer_au_controle_de_legalite",              "identifier" => "envoyer_au_controle_de_legalite",
# Line 595  class instruction extends instruction_ge Line 680  class instruction extends instruction_ge
680              "commentaire_signature",              "commentaire_signature",
681              "historique_signature",              "historique_signature",
682              "'' as suivi_notification",              "'' as suivi_notification",
683                "'' as suivi_notification_service",
684                "'' as suivi_notification_tiers",
685                "'' as suivi_notification_commune",
686    
687              "'' as preview_edition",              "'' as preview_edition",
688              "envoye_cl_platau",              "envoye_cl_platau",
689                "'' as log_instruction",
690                "parapheur_lien_page_signature"
691          );          );
692      }      }
693    
# Line 660  class instruction extends instruction_ge Line 749  class instruction extends instruction_ge
749          return true;          return true;
750      }      }
751    
752        /**
753         * CONDITION - is_parapheur_annulation_parameter_enabled
754         *
755         * Vérifie que l'option d'annulation de l'envoi en signature est activée.
756         *
757         * @return boolean
758         */
759        function is_parapheur_annulation_parameter_enabled() {
760            //Instanciation de la classe electronicsignature
761            $inst_es = $this->get_electronicsignature_instance();
762            if ($inst_es === false) {
763                return false;
764            }
765    
766            if ($inst_es->get_conf('cancel_send') !== 'true' && $inst_es->get_conf('cancel_send') !== true) {
767                return false;
768            }
769    
770            return true;
771        }
772    
773    
774      /**      /**
775       * CONDITION - is_sent_for_signature       * CONDITION - is_sent_for_signature
# Line 676  class instruction extends instruction_ge Line 786  class instruction extends instruction_ge
786          if ($this->has_connector_electronicsignature() === true          if ($this->has_connector_electronicsignature() === true
787              && empty($this->getVal("id_parapheur_signature")) === false              && empty($this->getVal("id_parapheur_signature")) === false
788              && ($this->getVal("statut_signature") != "canceled"              && ($this->getVal("statut_signature") != "canceled"
789              || $this->getVal("statut_signature") != "expired"              && $this->getVal("statut_signature") != "expired"
790              || $this->getVal("statut_signature") != "finished")) {              && $this->getVal("statut_signature") != "finished")) {
791              //              //
792              return true;              return true;
793          }          }
# Line 725  class instruction extends instruction_ge Line 835  class instruction extends instruction_ge
835          return false;          return false;
836      }      }
837    
838    
839        /**
840         * is_sent_to_cl
841         *
842         * Vérifie que l'instruction a été envoyé au contrôle de légalité
843         *
844         * @return boolean
845         */
846      function is_sent_to_cl() {      function is_sent_to_cl() {
847          // Si l'instruction a une édition          // Si la case à cocher de l'instruction envoye_cl_platau est à "t"
848          // et que l'événement est paramétré pour envoyer le contrôle de légalité          if ($this->getVal('envoye_cl_platau') === 't') {
849          // par Plat'AU              //
850          // et que la date de retour signature est renseignée              return true;
         // et que la date d'envoi au contrôle légalité n'est pas renseignée  
         // et qu'il n'existe pas de task envoi_CL en cours (!= done ou canceled)  
         if ($this->has_an_edition() === true) {  
             $inst_evenement = $this->get_inst_evenement($this->getVal('evenement'));  
             if ($inst_evenement->getVal('envoi_cl_platau') === 't'  
                 || $this->getVal('envoye_cl_platau') === 't') {  
                 //  
                 return true;  
             }  
851          }          }
852          //          //
853          return false;          return false;
# Line 754  class instruction extends instruction_ge Line 863  class instruction extends instruction_ge
863      function is_portail_notification_sans_annexe() {      function is_portail_notification_sans_annexe() {
864          $collectiviteDi = $this->get_dossier_instruction_om_collectivite();          $collectiviteDi = $this->get_dossier_instruction_om_collectivite();
865          $ev = $this->get_inst_evenement($this->getVal('evenement'));          $ev = $this->get_inst_evenement($this->getVal('evenement'));
866          if (($this->f->get_param_option_notification($collectiviteDi) === null ||          if ($this->f->get_param_option_notification($collectiviteDi) === PORTAL
             $this->f->get_param_option_notification($collectiviteDi) === 'portal')  
867              && $ev->getVal('notification') != 'notification_manuelle_annexe'              && $ev->getVal('notification') != 'notification_manuelle_annexe'
868              && $ev->getVal('notification') != 'notification_manuelle_annexe_signature_requise'              && $ev->getVal('notification') != 'notification_manuelle_annexe_signature_requise'
869          ) {          ) {
# Line 855  class instruction extends instruction_ge Line 963  class instruction extends instruction_ge
963      /**      /**
964       * CONDITION - can_display_notification       * CONDITION - can_display_notification
965       *       *
966       * Vérifie que le fieldset "Suivi notification" soit affichable       * Vérifie que le champs "Suivi notification" est affichable
967       *       *
968       * @return boolean       * @return boolean
969       */       */
970      function can_display_notification() {      function can_display_notification_demandeur() {
971          // Le suivi des notification est affiché si l'événement est notifiable          // Le suivi des notification est affiché si l'événement est notifiable
972          // et si des notifications ont été envoyées          // et si des notifications ont été envoyées
973          $evenement_id = $this->getVal("evenement");          $evenement_id = $this->getVal("evenement");
# Line 868  class instruction extends instruction_ge Line 976  class instruction extends instruction_ge
976              $inst_evenement->getVal('notification') != '') {              $inst_evenement->getVal('notification') != '') {
977              // Des notifications ont été envoyé si il existe au moins une notification              // Des notifications ont été envoyé si il existe au moins une notification
978              // liées à l'instruction              // liées à l'instruction
979              $idsNotifs = $this->get_instruction_notification($this->getVal($this->clePrimaire));              $idsNotifs = $this->get_instruction_notification(
980                    $this->getVal($this->clePrimaire),
981                    array(
982                        'notification_recepisse',
983                        'notification_instruction',
984                        'notification_decision',
985                    ),
986                    true
987                );
988                if (isset($idsNotifs) && $idsNotifs !== array()) {
989                    return true;
990                }
991            }
992            return false;
993        }
994    
995        /**
996         * CONDITION - can_display_notification
997         *
998         * Vérifie que le champs "suivi_notification_service" est affichable
999         *
1000         * @return boolean
1001         */
1002        function can_display_notification_service() {
1003            // Le suivi des notification est affiché si l'événement est notifiable
1004            // et si des notifications ont été envoyées
1005            $evenement_id = $this->getVal("evenement");
1006            $inst_evenement = $this->get_inst_evenement($evenement_id);
1007            if ($this->get_boolean_from_pgsql_value($inst_evenement->getVal('notification_service')) == true) {
1008                // Des notifications ont été envoyé si il existe au moins une notification
1009                // de type notification_service_consulte liées à l'instruction
1010                $idsNotifs = $this->get_instruction_notification(
1011                    $this->getVal($this->clePrimaire),
1012                    'notification_service_consulte'
1013                );
1014                if (isset($idsNotifs) && $idsNotifs !== array()) {
1015                    return true;
1016                }
1017            }
1018            return false;
1019        }
1020    
1021    
1022        /**
1023         * CONDITION - can_display_notification_tiers
1024         *
1025         * Vérifie que le champs "suivi_notification_tiers" est affichable
1026         *
1027         * @return boolean
1028         */
1029        function can_display_notification_tiers() {
1030            // Le suivi des notification est affiché si l'événement est notifiable
1031            // et si des notifications ont été envoyées
1032            $evenement_id = $this->getVal("evenement");
1033            $inst_evenement = $this->get_inst_evenement($evenement_id);
1034            if (! empty($inst_evenement->getVal('notification_tiers'))) {
1035                // Des notifications ont été envoyé si il existe au moins une notification
1036                // de type notification_tiers_consulte liées à l'instruction
1037                $idsNotifs = $this->get_instruction_notification(
1038                    $this->getVal($this->clePrimaire),
1039                    'notification_tiers_consulte'
1040                );
1041              if (isset($idsNotifs) && $idsNotifs !== array()) {              if (isset($idsNotifs) && $idsNotifs !== array()) {
1042                  return true;                  return true;
1043              }              }
# Line 877  class instruction extends instruction_ge Line 1046  class instruction extends instruction_ge
1046      }      }
1047    
1048      /**      /**
1049         * CONDITION - can_display_notification_commune
1050         *
1051         * Vérifie que le champs "suivi_notification_commune" est affichable
1052         *
1053         * @return boolean
1054         */
1055        function can_display_notification_commune() {
1056            // Le suivi des notification si il existe au moins une notification
1057            // de type notification_depot_demat liées à l'instruction
1058            $idsNotifs = $this->get_instruction_notification(
1059                $this->getVal($this->clePrimaire),
1060                array('notification_depot_demat', 'notification_commune')
1061            );
1062            if (isset($idsNotifs) && $idsNotifs !== array()) {
1063                return true;
1064            }
1065            return false;
1066        }
1067    
1068        /**
1069       * TREATMENT - disable_edition_integrale.       * TREATMENT - disable_edition_integrale.
1070       *       *
1071       * Cette methode permet de passer la consultation en "lu"       * Cette methode permet de passer la consultation en "lu"
# Line 978  class instruction extends instruction_ge Line 1167  class instruction extends instruction_ge
1167      }      }
1168    
1169      /**      /**
1170       * Cette méthode permet de récupérer le dossier d'autorisation d'un dossier       * Cette méthode instancie le dossier à partir de l'identifiant passé
1171         * en paramètre et renvoie l'identifiant du dossier d'autorisation (DA)
1172         * associé au dossier.
1173         * Si l'identifiant du dossier n'est pas fourni alors cette méthode
1174         * renverra NULL
1175         *
1176         * @param string identifiant du dossier
1177         * @return null|string null ou identifiant du DA
1178       */       */
1179      function getNumDemandeAutorFromDossier($id) {      function getNumDemandeAutorFromDossier($id) {
         //  
1180          if (!isset($id)) {          if (!isset($id)) {
1181              return NULL;              return NULL;
1182          }          }
         //  
         $sql = "select dossier_autorisation from ".DB_PREFIXE."dossier ";  
         $sql .= " where dossier='".$id."'";  
         //  
         $dossier_autorisation = $this->f->db->getOne($sql);  
         $this->addToLog("getNumDemandeAutorFromDossier(): db->getone(\"".$sql."\")", VERBOSE_MODE);  
         database::isError($dossier_autorisation);  
         //  
         return $dossier_autorisation;  
     }  
1183    
1184      // }}}          $dossier = $this->f->get_inst__om_dbform(array(
1185                'obj' => 'dossier',
1186                'idx' => $id,
1187            ));
1188    
1189            return $dossier->getVal('dossier_autorisation');
1190        }
1191    
1192        
1193      function setType(&$form, $maj) {      function setType(&$form, $maj) {
1194          // Récupération du mode de l'action          // Récupération du mode de l'action
1195          $crud = $this->get_action_crud($maj);          $crud = $this->get_action_crud($maj);
# Line 1020  class instruction extends instruction_ge Line 1212  class instruction extends instruction_ge
1212              }              }
1213          }          }
1214    
1215          // Le champ de suivi des notifications n'est pas affichable dans tous les cas          // Le champ de suivi des notifications des demandeurs n'est pas affichable dans tous les cas
1216          if ($this->can_display_notification() === true && $maj == 3) {          if ($maj == 3 && $this->can_display_notification_demandeur() === true) {
1217              $form->setType('suivi_notification', 'jsontotab');              $form->setType('suivi_notification', 'jsontotab');
1218          }          }
1219            // Le champ de suivi des notifications des services n'est pas affichable dans tous les cas
1220            if ($maj == 3 && $this->can_display_notification_service() === true) {
1221                $form->setType('suivi_notification_service', 'jsontotab');
1222            }
1223            // Le champ de suivi des notifications des tiers n'est pas affichable dans tous les cas
1224            if ($maj == 3 && $this->can_display_notification_tiers() === true) {
1225                $form->setType('suivi_notification_tiers', 'jsontotab');
1226            }
1227            // Le champ de suivi des notifications des communes n'est pas affichable dans tous les cas
1228            if ($maj == 3 && $this->can_display_notification_commune() === true) {
1229                $form->setType('suivi_notification_commune', 'jsontotab');
1230            }
1231    
1232          // MODE AJOUTER          // MODE AJOUTER
1233          if ($this->getParameter('maj') == 0) {          if ($this->getParameter('maj') == 0) {
# Line 1084  class instruction extends instruction_ge Line 1288  class instruction extends instruction_ge
1288                      $form->setType('btn_refresh', 'httpclickbutton');                      $form->setType('btn_refresh', 'httpclickbutton');
1289                      $form->setType('btn_preview', 'httpclickbutton');                      $form->setType('btn_preview', 'httpclickbutton');
1290                      $form->setType('btn_redaction', 'httpclickbutton');                      $form->setType('btn_redaction', 'httpclickbutton');
1291                        // /!\ le type du champs est utilisé dans un selecteur dans le jscript.js
1292                        // pour identifiant le champ de prévisualisation et régler sa taille à
1293                        // l'affichage du champ. En cas de modification, le selecteur doit également
1294                        // être mis à jour
1295                      $form->setType('live_preview', 'previsualiser_pdf');                      $form->setType('live_preview', 'previsualiser_pdf');
1296                  }                  }
1297    
# Line 1108  class instruction extends instruction_ge Line 1316  class instruction extends instruction_ge
1316                      $form->setType('date_retour_rar', 'date');                      $form->setType('date_retour_rar', 'date');
1317                      $form->setType('date_envoi_controle_legalite', 'date');                      $form->setType('date_envoi_controle_legalite', 'date');
1318                      if ($this->is_sent_to_cl() === true) {                      if ($this->is_sent_to_cl() === true) {
1319                          $form->setType("date_envoi_controle_legalite", "datereadonly");                          $form->setType("date_envoi_controle_legalite", "datedisabled");
1320                      }                      }
1321                      $form->setType('date_retour_controle_legalite', 'date');                      $form->setType('date_retour_controle_legalite', 'date');
1322                      $form->setType('date_finalisation_courrier', 'date');                      $form->setType('date_finalisation_courrier', 'date');
# Line 1180  class instruction extends instruction_ge Line 1388  class instruction extends instruction_ge
1388              $form->setType('date_retour_rar', 'date');              $form->setType('date_retour_rar', 'date');
1389              $form->setType('date_envoi_controle_legalite', 'date');              $form->setType('date_envoi_controle_legalite', 'date');
1390              if ($this->is_sent_to_cl() === true) {              if ($this->is_sent_to_cl() === true) {
1391                  $form->setType("date_envoi_controle_legalite", "datereadonly");                  $form->setType("date_envoi_controle_legalite", "datedisabled");
1392              }              }
1393              $form->setType('date_retour_controle_legalite', 'date');              $form->setType('date_retour_controle_legalite', 'date');
1394              $form->setType('date_finalisation_courrier', 'date');              $form->setType('date_finalisation_courrier', 'date');
# Line 1192  class instruction extends instruction_ge Line 1400  class instruction extends instruction_ge
1400              }              }
1401              $form->setType('preview_edition', 'previsualiser');              $form->setType('preview_edition', 'previsualiser');
1402          }          }
1403    
1404            // Si l'instruction a été envoyé au contrôle de légalité et que la
1405            // tâche envoi_cl lié n'a pas encore été traité il faut indiquer à
1406            // l'utilisateur que l'envoi au cl est en cours de traitement.
1407            if ($this->is_sent_to_cl() === true
1408                && empty($this->getVal('date_envoi_controle_legalite'))
1409                && $maj == 3) {
1410                $form->setType("date_envoi_controle_legalite", "hiddenstatic");
1411            }
1412      }      }
1413    
1414      function setOnchange(&$form,$maj){      function setOnchange(&$form,$maj){
# Line 1273  class instruction extends instruction_ge Line 1490  class instruction extends instruction_ge
1490       * @return string       * @return string
1491       */       */
1492      function get_var_sql_forminc__sql_signataire_arrete() {      function get_var_sql_forminc__sql_signataire_arrete() {
1493          return "SELECT          return sprintf(
1494              signataire_arrete.signataire_arrete,              "SELECT
1495              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)                  signataire_arrete.signataire_arrete,
1496              FROM ".DB_PREFIXE."signataire_arrete                  CONCAT_WS(
1497              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)))                      ' - ',
1498              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";                      CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1499                        signataire_habilitation.libelle,
1500                        signataire_arrete.description
1501                    )
1502                FROM
1503                    %1\$ssignataire_arrete
1504                    LEFT JOIN %1\$ssignataire_habilitation
1505                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1506                WHERE
1507                    ((signataire_arrete.om_validite_debut IS NULL
1508                        AND (signataire_arrete.om_validite_fin IS NULL
1509                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1510                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1511                            AND (signataire_arrete.om_validite_fin IS NULL
1512                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1513                ORDER BY
1514                    signataire_arrete.prenom,
1515                    signataire_arrete.nom",
1516                DB_PREFIXE
1517            );
1518      }      }
1519    
1520      /**      /**
# Line 1286  class instruction extends instruction_ge Line 1522  class instruction extends instruction_ge
1522       * @return string       * @return string
1523       */       */
1524      function get_var_sql_forminc__sql_signataire_arrete_by_id() {      function get_var_sql_forminc__sql_signataire_arrete_by_id() {
1525          return "SELECT          return sprintf(
1526              signataire_arrete.signataire_arrete,              "SELECT
1527              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)                  signataire_arrete.signataire_arrete,
1528              FROM ".DB_PREFIXE."signataire_arrete                  CONCAT_WS(
1529              WHERE signataire_arrete.signataire_arrete = <idx>";                      ' - ',
1530                        CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1531                        signataire_habilitation.libelle,
1532                        signataire_arrete.description
1533                    )
1534                FROM
1535                    %1\$ssignataire_arrete
1536                    LEFT JOIN %1\$ssignataire_habilitation
1537                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1538                WHERE
1539                    signataire_arrete.signataire_arrete = <idx>",
1540                DB_PREFIXE
1541            );
1542      }      }
1543    
1544      /**      /**
# Line 1298  class instruction extends instruction_ge Line 1546  class instruction extends instruction_ge
1546       * @return string       * @return string
1547       */       */
1548      function get_var_sql_forminc__sql_signataire_arrete_by_di() {      function get_var_sql_forminc__sql_signataire_arrete_by_di() {
1549          return "SELECT          return sprintf(
1550              signataire_arrete.signataire_arrete,              "SELECT
1551              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)                  signataire_arrete.signataire_arrete,
1552              FROM ".DB_PREFIXE."signataire_arrete                  CONCAT_WS(
1553              LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite                      ' - ',
1554              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)))                      CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1555              AND (om_collectivite.niveau = '2' OR signataire_arrete.om_collectivite = <collectivite_di>)                      signataire_habilitation.libelle,
1556              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";                      signataire_arrete.description
1557                    )
1558                FROM
1559                    %1\$ssignataire_arrete
1560                    LEFT JOIN %1\$som_collectivite
1561                        ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1562                    LEFT JOIN %1\$ssignataire_habilitation
1563                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1564                WHERE
1565                    ((signataire_arrete.om_validite_debut IS NULL
1566                        AND (signataire_arrete.om_validite_fin IS NULL
1567                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1568                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1569                            AND (signataire_arrete.om_validite_fin IS NULL
1570                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1571                    AND (om_collectivite.niveau = '2'
1572                        OR signataire_arrete.om_collectivite = <collectivite_di>)
1573                ORDER BY
1574                    signataire_arrete.prenom, signataire_arrete.nom",
1575                DB_PREFIXE
1576            );
1577      }      }
1578    
1579      /**      /**
# Line 1313  class instruction extends instruction_ge Line 1581  class instruction extends instruction_ge
1581       * @return string       * @return string
1582       */       */
1583      function get_var_sql_forminc__sql_signataire_arrete_defaut() {      function get_var_sql_forminc__sql_signataire_arrete_defaut() {
1584          return "SELECT          return sprintf(
1585              signataire_arrete.signataire_arrete,              "SELECT
1586              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)                  signataire_arrete.signataire_arrete,
1587              FROM ".DB_PREFIXE."signataire_arrete                  CONCAT_WS(
1588              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                      ' - ',
1589              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";                      CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1590                        signataire_habilitation.libelle,
1591                        signataire_arrete.description
1592                    )
1593                FROM
1594                    %1\$ssignataire_arrete
1595                    LEFT JOIN %1\$ssignataire_habilitation
1596                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1597                WHERE
1598                    ((signataire_arrete.om_validite_debut IS NULL
1599                        AND (signataire_arrete.om_validite_fin IS NULL
1600                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1601                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1602                            AND (signataire_arrete.om_validite_fin IS NULL
1603                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1604                    AND signataire_arrete.defaut IS TRUE
1605                ORDER BY
1606                    signataire_arrete.prenom, signataire_arrete.nom",
1607                DB_PREFIXE
1608            );
1609      }      }
1610    
1611      /**      /**
# Line 1326  class instruction extends instruction_ge Line 1613  class instruction extends instruction_ge
1613       * @return string       * @return string
1614       */       */
1615      function get_var_sql_forminc__sql_signataire_arrete_defaut_by_di() {      function get_var_sql_forminc__sql_signataire_arrete_defaut_by_di() {
1616          return "SELECT          return sprintf(
1617              signataire_arrete.signataire_arrete,              "SELECT
1618              CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)                  signataire_arrete.signataire_arrete,
1619              FROM ".DB_PREFIXE."signataire_arrete                      CONCAT_WS(
1620              LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite                          ' - ',
1621              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                          CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1622              AND (om_collectivite.niveau = '2' OR signataire_arrete.om_collectivite = <collectivite_di>)                          signataire_habilitation.libelle,
1623              ORDER BY signataire_arrete.prenom, signataire_arrete.nom";                          signataire_arrete.description
1624                        )
1625                FROM
1626                    %1\$ssignataire_arrete
1627                    LEFT JOIN %1\$ssignataire_habilitation
1628                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1629                    LEFT JOIN %1\$som_collectivite
1630                        ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1631                WHERE
1632                    ((signataire_arrete.om_validite_debut IS NULL
1633                        AND (signataire_arrete.om_validite_fin IS NULL
1634                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1635                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1636                            AND (signataire_arrete.om_validite_fin IS NULL
1637                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1638                    AND signataire_arrete.defaut IS TRUE
1639                    AND (om_collectivite.niveau = '2'
1640                        OR signataire_arrete.om_collectivite = <collectivite_di>)
1641                ORDER BY
1642                    signataire_arrete.prenom,
1643                    signataire_arrete.nom",
1644                DB_PREFIXE
1645            );
1646        }
1647    
1648        /**
1649         * Renvoie sous la forme d'un tableau la liste des événements pouvant être ajoutés au dossier
1650         * dont l'identifiant a été passé en paramètre dans l'url.
1651         *
1652         * @return array
1653         */
1654        function get_var_sql_forminc__sql_evenement() {
1655            // Récupération du numéro de dossier
1656            $dossier = $this->getParameter("idxformulaire");
1657            // Si changement de décision par instructeur commune
1658            $filter = '';
1659            if ($this->f->isUserInstructeur() === true
1660                && $this->getDivisionFromDossier($dossier) != $_SESSION["division"]
1661                && $this->isInstrCanChangeDecision($dossier) === true) {
1662                $filter = "AND evenement.type IN ('arrete', 'changement_decision')";
1663            }
1664            // Récupération du libellé, de l'identifiant des évènement et d'un booléen permettant
1665            // de déterminer si il s'agit d'évènements suggérés.
1666            $qres = $this->f->get_all_results_from_db_query(
1667                sprintf(
1668                    'SELECT
1669                        DISTINCT(evenement.evenement),
1670                        evenement.libelle,
1671                        -- Si l evenement est suggérés alors il sera lié à la table des événements suggérés du dossier
1672                        CASE WHEN evenement_suggere_dossier.evenement IS NULL
1673                            THEN FALSE
1674                            ELSE TRUE
1675                        END AS is_suggested
1676                    FROM
1677                        -- Jointures permettant de récupérer la liste des évènements compatibles avec le dossier
1678                        -- selon le type de dossier et l état du dossier.
1679                        %1$sevenement
1680                        JOIN %1$slien_dossier_instruction_type_evenement
1681                            ON evenement.evenement = lien_dossier_instruction_type_evenement.evenement
1682                        JOIN %1$stransition
1683                            ON evenement.evenement = transition.evenement
1684                        JOIN %1$sdossier
1685                            ON lien_dossier_instruction_type_evenement.dossier_instruction_type = dossier.dossier_instruction_type
1686                                AND transition.etat = dossier.etat
1687                        -- Jointures avec une sous requêtes servant à récupérer la liste des évènements suggérés du dossier.
1688                        LEFT JOIN (
1689                            SELECT
1690                                lien_sig_contrainte_evenement.evenement,
1691                                dossier.dossier
1692                            FROM
1693                                %1$slien_sig_contrainte_evenement
1694                                JOIN %1$ssig_contrainte
1695                                    ON lien_sig_contrainte_evenement.sig_contrainte = sig_contrainte.sig_contrainte
1696                                JOIN %1$slien_sig_contrainte_dossier_instruction_type
1697                                    ON sig_contrainte.sig_contrainte = lien_sig_contrainte_dossier_instruction_type.sig_contrainte
1698                                JOIN %1$slien_sig_contrainte_om_collectivite
1699                                    ON sig_contrainte.sig_contrainte = lien_sig_contrainte_om_collectivite.sig_contrainte
1700                                JOIN %1$scontrainte
1701                                    ON sig_contrainte.libelle = contrainte.libelle
1702                                JOIN %1$sdossier_contrainte
1703                                    ON contrainte.contrainte = dossier_contrainte.contrainte
1704                                JOIN %1$sdossier
1705                                    ON dossier_contrainte.dossier = dossier.dossier
1706                                        AND lien_sig_contrainte_dossier_instruction_type.dossier_instruction_type = dossier.dossier_instruction_type
1707                                JOIN %1$som_collectivite
1708                                    ON lien_sig_contrainte_om_collectivite.om_collectivite = om_collectivite.om_collectivite
1709                                        AND (dossier.om_collectivite = om_collectivite.om_collectivite
1710                                            OR om_collectivite.niveau = \'2\')
1711                        ) AS evenement_suggere_dossier
1712                            ON evenement.evenement = evenement_suggere_dossier.evenement
1713                                AND dossier.dossier = evenement_suggere_dossier.dossier
1714                    WHERE
1715                        dossier.dossier = \'%2$s\'
1716                        %3$s
1717                    ORDER BY
1718                        is_suggested DESC,
1719                        evenement.libelle',
1720                    DB_PREFIXE,
1721                    $this->f->db->escapeSimple($dossier),
1722                    $filter
1723                ),
1724                array(
1725                    "origin" => __METHOD__
1726                )
1727            );
1728            return $qres['result'];
1729        }
1730    
1731        /**
1732         * Récupère un tableau contenant des évènements de la forme :
1733         * $events = array(
1734         *      1 => array(
1735         *         'libelle' => 'evenement_libelle',
1736         *         'evenement' => 'identifiant_evenement',
1737         *         'is_suggested' => true/false   -> booleen indiquant si c'est un événement suggéré
1738         *         ))
1739         * Et le transforme pour pouvoir l'utiliser pour le remplissage d'un select de formulaire.
1740         *
1741         * Le format de sorti est le suivant :
1742         * $select = array(
1743         *      0 => array( -> liste des id des événements
1744         *          '0' => '',
1745         *          '1' => array(
1746         *              '0' => array(), -> liste des id des événements suggérés
1747         *              '1' => array(), -> liste des libelles des événements suggérés
1748         *          ),
1749         *          ...,
1750         *          n => 'id_evenement_n'
1751         *      ),
1752         *      1 => array(
1753         *          '0' => '__('choisir')." ".__('evenement')',
1754         *          '1' => '💡 Suggestions',
1755         *          ...,
1756         *          'n' => 'libelle_evenement_n',
1757         *      )
1758         * )
1759         *
1760         * @param array tableau des événements
1761         * @return array
1762         */
1763        protected function convert_events_array_to_select_format($events) {
1764            // Remplissage du tableau du select en incluant le groupe des instructions suggérées.
1765            $contenu = array(
1766                0 => array("",),
1767                1 => array(__('choisir')." ".__('evenement'),)
1768            );
1769    
1770            if (! empty($events)) {
1771                // S'il y a des évènements suggérés extraction de ces événements et mise en place du groupe
1772                $suggested_event_group = array_filter($events, function($a) {
1773                        return $a['is_suggested'] === 't';
1774                });
1775                if (! empty($suggested_event_group)) {
1776                    // Prépare les données qui permettront d'afficher le groupe des événements
1777                    // suggérés.
1778                    $values = array();
1779                    $labels = array();
1780                    foreach ($suggested_event_group as $index => $suggested_event) {
1781                        $values[] = $suggested_event['evenement'];
1782                        $labels[] = $suggested_event['libelle'];
1783                        // Supprime les évènements suggérés de la liste des évènements
1784                        unset($events[$index]);
1785                    }
1786                    // Remplissage du select pour le groupe
1787                    $contenu[0][] = array($values, $labels);
1788                    $contenu[1][] = __('💡 Suggestions');
1789                }
1790        
1791                // Remplissage du select
1792                foreach ($events as $event) {
1793                    $contenu[0][] = $event['evenement'];
1794                    $contenu[1][] = $event['libelle'];
1795                }
1796            }
1797            return $contenu;
1798      }      }
1799    
1800      /**      /**
# Line 1373  class instruction extends instruction_ge Line 1834  class instruction extends instruction_ge
1834          // signataire_arrete          // signataire_arrete
1835          // si contexte DI          // si contexte DI
1836          if ($this->getParameter("retourformulaire") == "dossier"          if ($this->getParameter("retourformulaire") == "dossier"
1837                  || $this->getParameter("retourformulaire") == "dossier_instruction"                  || $this->f->contexte_dossier_instruction()) {
                 || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {  
1838              // on recupère les signataires de la multicollectivité et de celle du DI              // on recupère les signataires de la multicollectivité et de celle du DI
1839              $di = $this->f->get_inst__om_dbform(array(              $di = $this->f->get_inst__om_dbform(array(
1840                  "obj" => "dossier_instruction",                  "obj" => "dossier_instruction",
# Line 1422  class instruction extends instruction_ge Line 1875  class instruction extends instruction_ge
1875           * événements disponibles.           * événements disponibles.
1876           */           */
1877          if ($maj == 0) {          if ($maj == 0) {
1878              // Récupération des événements par une jointure entre la table dossier              $evenements = $this->get_var_sql_forminc__sql_evenement();
1879              // et la table transition et la table evenement et la table              $form->setSelect("evenement", $this->convert_events_array_to_select_format($evenements));
             // lien_dossier_instruction_type_evenement en fonction de l'identifiant  
             // du dossier d'instruction en cours  
             $sql = "SELECT  
             evenement.evenement,  
             evenement.libelle as lib  
             FROM ".DB_PREFIXE."dossier  
             INNER JOIN ".DB_PREFIXE."lien_dossier_instruction_type_evenement  
                 ON dossier.dossier_instruction_type=lien_dossier_instruction_type_evenement.dossier_instruction_type  
             INNER JOIN ".DB_PREFIXE."evenement  
                 ON evenement.evenement=lien_dossier_instruction_type_evenement.evenement  
             INNER JOIN ".DB_PREFIXE."transition  
                 ON evenement.evenement = transition.evenement  
                 AND dossier.etat=transition.etat  
             WHERE dossier.dossier='".$this->getParameter("idxformulaire")."' ";  
   
             // Si changement de décision par instructeur commune  
             if($this->f->isUserInstructeur() === true  
                 && $this->getDivisionFromDossier($this->getParameter("idxformulaire")) != $_SESSION["division"]  
                 && $this->isInstrCanChangeDecision($this->getParameter("idxformulaire")) === true) {  
                 $sql .= "AND evenement.type IN ('arrete', 'changement_decision') ";  
             }  
             $sql .= "ORDER BY evenement.libelle, evenement.action";  
             $res = $this->f->db->query($sql);  
             $this->addToLog("setSelect(): db->query(\"".$sql."\");", VERBOSE_MODE);  
             if (database::isError($res)) {  
                 die($res->getMessage());  
             }  
             // Remplissage du tableau du select  
             $contenu = array(  
                 0 => array("",),  
                 1 => array(_('choisir')." "._('evenement'),)  
             );  
             while ($row=& $res->fetchRow()) {  
                 $contenu[0][] = $row[0];  
                 $contenu[1][] = $row[1];  
             }  
             $form->setSelect("evenement", $contenu);  
   
1880          } else {          } else {
1881              $sql = "SELECT              // Instanciation de l'événement pour récupérer son libellé
1882              evenement.libelle as lib              $evenement = $this->f->get_inst__om_dbform(array(
1883              FROM ".DB_PREFIXE."evenement                  "obj" => "evenement",
1884              WHERE evenement.evenement=".$this->getVal("evenement")."";                  "idx" => $this->getVal("evenement"),
1885              $res = $this->f->db->getone($sql);              ));
1886              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);  
             if (database::isError($res)) {  
                 die($res->getMessage());  
             }  
             //  
1887              $contenu = array(              $contenu = array(
1888                  0 => array($this->getVal("evenement"),),                  0 => array($this->getVal("evenement"),),
1889                  1 => array($res,)                  1 => array($evenement->getVal('libelle'),)
1890              );              );
1891              $form->setSelect("evenement", $contenu);              $form->setSelect("evenement", $contenu);
1892          }          }
# Line 1543  class instruction extends instruction_ge Line 1954  class instruction extends instruction_ge
1954                    
1955          $id = $this->getVal($this->clePrimaire);          $id = $this->getVal($this->clePrimaire);
1956    
           
1957          //Requête de vérification que cet événement d'instruction n'est pas lié          //Requête de vérification que cet événement d'instruction n'est pas lié
1958          //à la création d'un dossier d'instruction          //à la création d'un dossier d'instruction
1959          $sql = "SELECT demande_type.dossier_instruction_type          $qres = $this->f->get_one_result_from_db_query(
1960              FROM ".DB_PREFIXE."demande_type              sprintf(
1961              LEFT JOIN ".DB_PREFIXE."demande                  'SELECT
1962              ON demande.demande_type = demande_type.demande_type                      demande_type.dossier_instruction_type
1963              WHERE demande.instruction_recepisse = ".$id;                  FROM
1964          $res = $this->f->db->getOne($sql);                      %1$sdemande_type
1965          $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);                      LEFT JOIN %1$sdemande
1966          if (database::isError($res)) {                          ON demande.demande_type = demande_type.demande_type
1967              die($res->getMessage());                  WHERE
1968          }                      demande.instruction_recepisse = \'%2$d\'',
1969                    DB_PREFIXE,
1970                    intval($id)
1971                ),
1972                array(
1973                    "origin" => __METHOD__,
1974                )
1975            );
1976    
1977          // Aucune clé secondaire n'a été trouvée ou c'est un événement sans          // Aucune clé secondaire n'a été trouvée ou c'est un événement sans
1978          //création de dossier d'instruction, l'événement d'instruction peut être          //création de dossier d'instruction, l'événement d'instruction peut être
1979          //supprimé          //supprimé
1980          if ( $this->correct !== false || $res == null || $res == ""){          if ( $this->correct !== false || $qres['result'] == null || $qres['result'] == ""){
   
1981              // Requête de vérification que cet événement d'instruction est lié              // Requête de vérification que cet événement d'instruction est lié
1982              // à une demande              // à une demande
1983              $sql = "SELECT demande              $qres = $this->f->get_one_result_from_db_query(
1984                  FROM ".DB_PREFIXE."demande                  sprintf(
1985                  WHERE instruction_recepisse = ".$id;                      'SELECT
1986              $res = $this->f->db->getOne($sql);                          demande
1987              $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);                      FROM
1988              if (database::isError($res)) {                          %1$sdemande
1989                  die($res->getMessage());                      WHERE
1990              }                          instruction_recepisse = \'%2$d\'',
1991                        DB_PREFIXE,
1992                        intval($id)
1993                    ),
1994                    array(
1995                        "origin" => __METHOD__,
1996                    )
1997                );
1998    
1999              //Si c'est un événement d'instruction lié à une demande              //Si c'est un événement d'instruction lié à une demande
2000              if ($res != null || $res != ""){              if ($qres['result'] != null || $qres['result'] != ""){
2001                  $demande = $this->f->get_inst__om_dbform(array(                  $demande = $this->f->get_inst__om_dbform(array(
2002                      "obj" => "demande",                      "obj" => "demande",
2003                      "idx" => $res,                      "idx" => $qres['result'],
2004                  ));                  ));
2005    
2006                  //On met à jour la demande en supprimant la liaison vers                  //On met à jour la demande en supprimant la liaison vers
2007                  //l'événement d'instruction                  //l'événement d'instruction
2008                  $demande->setParameter("maj", 1);                  $demande->setParameter("maj", 1);
2009                  $valF = array();                  $valF = array();
# Line 1596  class instruction extends instruction_ge Line 2019  class instruction extends instruction_ge
2019               * Vérification que l'élément supprimé est le dernier pour pouvoir               * Vérification que l'élément supprimé est le dernier pour pouvoir
2020               * remodifier les données de manière itérative.               * remodifier les données de manière itérative.
2021               */               */
2022              // Initialisation              $qres = $this->f->get_one_result_from_db_query(
2023              $dernierevenement = "";                  sprintf(
2024              // Récupération du dernier élément de la table d'instruction qui                      'SELECT
2025              // concerne le dossier en cours                          max(instruction)
2026              $sql = "SELECT max(instruction)                      FROM
2027              FROM ".DB_PREFIXE."instruction                          %1$sinstruction
2028              WHERE dossier ='".$this->getParameter("idxformulaire")."'";                      WHERE
2029              $dernierevenement = $this->f->db->getOne($sql);                          dossier = \'%2$s\'',
2030              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);                      DB_PREFIXE,
2031              if (database::isError($dernierevenement)) {                      $this->f->db->escapeSimple($this->getParameter("idxformulaire"))
2032                  die($dernierevenement->getMessage());                  ),
2033              }                  array(
2034                        "origin" => __METHOD__,
2035                    )
2036                );
2037    
2038              // Si on se trouve effectivement sur le dernier evenement d'instruction              // Si on se trouve effectivement sur le dernier evenement d'instruction
2039              if ($dernierevenement == $id) {              // alors on valide la suppression sinon on l'annule
2040                $this->correct = false;
2041                $message = __("Seul le dernier evenement d'instruction peut etre supprime.");
2042                if ($qres['result'] == $id) {
2043                  // Alors on valide la suppression                  // Alors on valide la suppression
2044                  $this->correct = true;                  $this->correct = true;
2045                  $this->addToMessage(_('Destruction_chronologique'));                  $message = __('Destruction_chronologique');
             } else {  
                 // Alors on annule la suppression  
                 $this->correct = false;  
                 $this->addToMessage(_("Seul le dernier evenement d'instruction peut etre supprime."));  
2046              }              }
2047                $this->addToMessage($message);
2048          }          }
2049      }      }
2050    
# Line 1629  class instruction extends instruction_ge Line 2056  class instruction extends instruction_ge
2056                    
2057          //Si le retourformulaire est "dossier_instruction"          //Si le retourformulaire est "dossier_instruction"
2058          if ($this->getParameter("retourformulaire") == "dossier"          if ($this->getParameter("retourformulaire") == "dossier"
2059                  || $this->getParameter("retourformulaire") == "dossier_instruction"                  || $this->f->contexte_dossier_instruction()) {
                 || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {  
2060    
2061              // Vérification de la possibilité de modifier les dates si déjà éditées              // Vérification de la possibilité de modifier les dates si déjà éditées
2062              if($this->valF[$champ] != "" AND !$this->f->user_is_admin) {              if($this->valF[$champ] != "" AND !$this->f->user_is_admin) {
# Line 1667  class instruction extends instruction_ge Line 2086  class instruction extends instruction_ge
2086              $form->setVal("destinataire", $this->getParameter("idxformulaire"));              $form->setVal("destinataire", $this->getParameter("idxformulaire"));
2087              $form->setVal("dossier", $this->getParameter("idxformulaire"));              $form->setVal("dossier", $this->getParameter("idxformulaire"));
2088          }          }
2089    
2090            // Si l'instruction a été envoyé au contrôle de légalité et que la
2091            // tâche envoi_cl lié n'a pas encore été traité il faut indiquer à
2092            // l'utilisateur que l'envoi au cl est en cours de traitement.
2093            if ($this->is_sent_to_cl() === true
2094                && empty($this->getVal('date_envoi_controle_legalite'))
2095                && $maj == 3) {
2096                $form->setVal("date_envoi_controle_legalite", __("En cours de traitement."));
2097            }
2098          //          //
2099          $this->set_form_default_values($form, $maj, $validation);          $this->set_form_default_values($form, $maj, $validation);
2100      }      }
# Line 1681  class instruction extends instruction_ge Line 2109  class instruction extends instruction_ge
2109          if ($maj == 0) {          if ($maj == 0) {
2110              // si contexte DI              // si contexte DI
2111              if ($this->getParameter("retourformulaire") == "dossier"              if ($this->getParameter("retourformulaire") == "dossier"
2112                  || $this->getParameter("retourformulaire") == "dossier_instruction"                  || $this->f->contexte_dossier_instruction()) {
                 || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"  
                 || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"  
                 || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {  
2113                  // on recupère les signataires de la multicollectivité et de celle du DI                  // on recupère les signataires de la multicollectivité et de celle du DI
2114                  $di = $this->f->get_inst__om_dbform(array(                  $di = $this->f->get_inst__om_dbform(array(
2115                      "obj" => "dossier_instruction",                      "obj" => "dossier_instruction",
# Line 1703  class instruction extends instruction_ge Line 2123  class instruction extends instruction_ge
2123              } else {              } else {
2124                  $sql = $this->get_var_sql_forminc__sql("signataire_arrete_defaut");                  $sql = $this->get_var_sql_forminc__sql("signataire_arrete_defaut");
2125              }              }
2126              $res = $this->f->db->query($sql);              
2127              $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);              $qres = $this->f->get_all_results_from_db_query($sql, array(
2128              $this->f->isDatabaseError($res);                      "origin" => __METHOD__));
2129              $row = $res->fetchrow(DB_FETCHMODE_ASSOC);              $row = array_shift($qres['result']);
2130              if (isset($row["signataire_arrete"])              if (isset($row["signataire_arrete"])
2131                  && is_numeric($row["signataire_arrete"])) {                  && is_numeric($row["signataire_arrete"])) {
2132                  //                  //
# Line 1735  class instruction extends instruction_ge Line 2155  class instruction extends instruction_ge
2155              $form->setVal("btn_redaction", "show_instr_redaction()");              $form->setVal("btn_redaction", "show_instr_redaction()");
2156          }          }
2157    
2158          if ($maj == 3          // Gestion de l'affichage des suivis de notification des demandeurs, des services, des tiers et
2159              && $this->can_display_notification()          // des communes
2160          ) {          if ($maj == 3) {
2161              $form->setVal("suivi_notification", $this->get_json_suivi_notification());              if ($this->can_display_notification_demandeur()) {
2162                    $typeNotification = array(
2163                        'notification_recepisse',
2164                        'notification_instruction',
2165                        'notification_decision',
2166                    );
2167                    $form->setVal("suivi_notification", $this->get_json_suivi_notification($typeNotification, true));
2168                }
2169                if ($this->can_display_notification_service()) {
2170                    $form->setVal("suivi_notification_service", $this->get_json_suivi_notification(array('notification_service_consulte')));
2171                }
2172                if ($this->can_display_notification_tiers()) {
2173                    $form->setVal("suivi_notification_tiers", $this->get_json_suivi_notification(array('notification_tiers_consulte')));
2174                }
2175                if ($this->can_display_notification_commune()) {
2176                    $form->setVal("suivi_notification_commune", $this->get_json_suivi_notification(array('notification_depot_demat', 'notification_commune')));
2177                }
2178          }          }
2179      }      }
2180    
2181      function setLayout(&$form, $maj){      function setLayout(&$form, $maj){
2182            // En consultation, pour les dossiers qui n'ont pas été transmis par le portail
2183            // citoyen, si la notification des demandeurs est activée sur l'évenement
2184            // d'instruction et que le paramétrage du demandeur principal n'est pas
2185            // correct alors un message a destination de l'instructeur est affiché.
2186            if ($maj == 3) {
2187                // Si le dossier n'a pas été déposé sur le portail citoyen (ou si
2188                // la requête permettant de savoir le type de demande à échouée) et si
2189                // la notification se fait par mail vérifie si il y a des erreurs de
2190                // paramétrage et si c'est le cas on affiche un message d'information
2191                $collectivite = $this->get_dossier_instruction_om_collectivite($this->getVal('dossier'));
2192                $categorieNotif = $this->f->get_param_option_notification($collectivite);
2193                if ($this->dossier_depose_sur_portail() == null || ! $this->dossier_depose_sur_portail()) {
2194                    $erreurParam = $this->get_info_notification_fail();
2195                    // Récupération de l'évenement d'instruction
2196                    $instEV = $this->get_inst_evenement();
2197                    if (! empty($instEV->getVal('notification')) && $erreurParam != array()) {
2198                        $class = 'text-info ui-state-highlight ui-state-info';
2199                        $message = __("Attention l'envoi de notification automatique n'est pas possible.");
2200                        $this->f->display_panel_information(
2201                            $class,
2202                            $message,
2203                            $erreurParam,
2204                            __('Veuillez corriger les informations suivantes.'),
2205                            'erreur_param_notif'
2206                        );
2207                    }
2208                }
2209            }
2210          $form->setBloc('evenement','D',"","sousform-instruction-action-".$maj);          $form->setBloc('evenement','D',"","sousform-instruction-action-".$maj);
2211    
2212          $form->setFieldset('evenement','D',_('Evenement'));          $form->setFieldset('evenement','D',_('Evenement'));
# Line 1772  class instruction extends instruction_ge Line 2236  class instruction extends instruction_ge
2236    
2237          $form->setFieldset('suivi_notification', 'D', __("Suivi notification"), "collapsible");          $form->setFieldset('suivi_notification', 'D', __("Suivi notification"), "collapsible");
2238          $form->setFieldset('suivi_notification','F');          $form->setFieldset('suivi_notification','F');
2239            $form->setFieldset('suivi_notification_service', 'D', __("Suivi notification service"), "collapsible");
2240            $form->setFieldset('suivi_notification_service','F');
2241            $form->setFieldset('suivi_notification_tiers', 'D', __("Suivi notification tiers"), "collapsible");
2242            $form->setFieldset('suivi_notification_tiers','F');
2243            $form->setFieldset('suivi_notification_commune', 'D', __("Suivi notification commune"), "collapsible");
2244            $form->setFieldset('suivi_notification_commune','F');
2245    
2246          if ($maj == 1) {          if ($maj == 1) {
2247              // Récupère la collectivité du dossier d'instruction              // Récupère la collectivité du dossier d'instruction
# Line 1853  class instruction extends instruction_ge Line 2323  class instruction extends instruction_ge
2323          $form->setLib('commentaire_signature', __("commentaire"));          $form->setLib('commentaire_signature', __("commentaire"));
2324          $form->setLib('historique_signature', '');          $form->setLib('historique_signature', '');
2325          $form->setLib('suivi_notification', '');          $form->setLib('suivi_notification', '');
2326            $form->setLib('suivi_notification_service', '');
2327            $form->setLib('suivi_notification_tiers', '');
2328            $form->setLib('suivi_notification_commune', '');
2329          $form->setLib('preview_edition', "");          $form->setLib('preview_edition', "");
2330    
2331          // Ajout d'une infobulle d'aide lorsque le formulaire est en mode          // Ajout d'une infobulle d'aide lorsque le formulaire est en mode
# Line 1923  class instruction extends instruction_ge Line 2396  class instruction extends instruction_ge
2396           * - avis_decision           * - avis_decision
2397           */           */
2398          // Récupération de tous les paramètres de l'événement sélectionné          // Récupération de tous les paramètres de l'événement sélectionné
2399          $sql = "SELECT * FROM ".DB_PREFIXE."evenement          // TODO : remplacer cette requête par l'instanciation de l'événement
2400          WHERE evenement=".$this->valF['evenement'];          $qres = $this->f->get_all_results_from_db_query(
2401          $res = $this->f->db->query($sql);              sprintf(
2402          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);                  'SELECT
2403          if (database::isError($res)) {                      *
2404              die($res->getMessage());                  FROM
2405          }                      %1$sevenement
2406          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {                  WHERE
2407                        evenement = %2$d',
2408                    DB_PREFIXE,
2409                    intval($this->valF['evenement'])
2410                ),
2411                array(
2412                    "origin" => __METHOD__,
2413                )
2414            );
2415            foreach ($qres['result'] as $row) {
2416              // Récupération de l'identifiant de l'action              // Récupération de l'identifiant de l'action
2417              // si une action est paramétrée dans l'événement              // si une action est paramétrée dans l'événement
2418              $this->valF['action'] = NULL;              $this->valF['action'] = NULL;
# Line 1971  class instruction extends instruction_ge Line 2453  class instruction extends instruction_ge
2453              }              }
2454          }          }
2455          // 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
2456          $sql = "SELECT * FROM ".DB_PREFIXE."dossier          // TODO : remplacer cette requête par l'instanciation de l'objet
2457          WHERE dossier='".$this->valF['dossier']."'";          $qres = $this->f->get_all_results_from_db_query(
2458          $res = $this->f->db->query($sql);              sprintf(
2459          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);                  'SELECT
2460          if (database::isError($res)) {                      *
2461              die($res->getMessage());                  FROM
2462          }                      %1$sdossier
2463          $row=& $res->fetchRow(DB_FETCHMODE_ASSOC);                  WHERE
2464                    dossier = \'%2$s\'',
2465                    DB_PREFIXE,
2466                    $this->f->db->escapeSimple($this->valF['dossier'])
2467                ),
2468                array(
2469                    "origin" => __METHOD__,
2470                )
2471            );
2472            $row = array_shift($qres['result']);
2473          $this->updateArchiveData($row);          $this->updateArchiveData($row);
2474                                    
2475          // Récupération de la duree de validite du dossier d'autorisation          // Récupération de la duree de validite du dossier d'autorisation
2476          $sql = "SELECT duree_validite_parametrage          $qres = $this->f->get_one_result_from_db_query(
2477                  FROM ".DB_PREFIXE."dossier_autorisation_type_detaille              sprintf(
2478                  LEFT JOIN ".DB_PREFIXE."dossier_autorisation                  'SELECT
2479                      ON dossier_autorisation.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille                      duree_validite_parametrage
2480                  LEFT JOIN ".DB_PREFIXE."dossier                  FROM
2481                      ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation                      %1$sdossier_autorisation_type_detaille
2482          WHERE dossier.dossier='".$this->valF['dossier']."'";                      LEFT JOIN %1$sdossier_autorisation
2483          $duree_validite_parametrage = $this->f->db->getOne($sql);                          ON  dossier_autorisation.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
2484          $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);                      LEFT JOIN %1$sdossier
2485          database::isError($duree_validite_parametrage);                          ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation
2486          if ($duree_validite_parametrage != '') {                  WHERE
2487              $this->valF['duree_validite_parametrage']= $duree_validite_parametrage;                      dossier.dossier = \'%2$s\'',
2488                    DB_PREFIXE,
2489                    $this->f->db->escapeSimple($this->valF['dossier'])
2490                ),
2491                array(
2492                    "origin" => __METHOD__,
2493                )
2494            );
2495    
2496            if ($qres['result'] != '') {
2497                $this->valF['duree_validite_parametrage'] = $qres['result'];
2498          }          }
2499    
2500          // Identifiant du type de courrier          // Identifiant du type de courrier
# Line 2003  class instruction extends instruction_ge Line 2504  class instruction extends instruction_ge
2504          $this->valF["code_barres"] = $idTypeCourrier . $idCourrier;          $this->valF["code_barres"] = $idTypeCourrier . $idCourrier;
2505      }      }
2506            
2507      // Test si une restriction est valide      /**
2508      // return boolean       * Test si une restriction est valide.
2509         *
2510         * @return boolean
2511         */
2512      function restrictionIsValid($restriction){      function restrictionIsValid($restriction){
2513          if($this->restriction_valid != null) {          if($this->restriction_valid != null) {
2514              return $this->restriction_valid;              return $this->restriction_valid;
# Line 2186  class instruction extends instruction_ge Line 2690  class instruction extends instruction_ge
2690          if(empty($evenement) || !is_numeric($evenement)) {          if(empty($evenement) || !is_numeric($evenement)) {
2691              return "";              return "";
2692          }          }
2693          $sql = "SELECT retour  
2694              FROM ".DB_PREFIXE."evenement          $evenement = $this->f->get_inst__om_dbform(array(
2695              WHERE evenement = ".$evenement;              "obj" => "evenement",
2696          $retour = $this->f->db->getOne($sql);              "idx" => $evenement,
2697          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);          ));
2698          if (database::isError($retour)) {          
2699              die($retour->getMessage());          return $evenement->getVal('retour') == 't';
         }  
         if ($retour == 't') {  
             return true;  
         } else {  
             return false;  
         }  
2700      }      }
2701    
2702      /**      /**
# Line 2213  class instruction extends instruction_ge Line 2711  class instruction extends instruction_ge
2711              return "";              return "";
2712          }          }
2713          //Récupère la restriction          //Récupère la restriction
2714          $sql= "SELECT          $evenement = $this->f->get_inst__om_dbform(array(
2715                    restriction              "obj" => "evenement",
2716                FROM              "idx" => $evenement,
2717                    ".DB_PREFIXE."evenement          ));
2718                WHERE          
2719                    evenement =".$evenement;          return $evenement->getVal('restriction');
   
         $restriction = $this->f->db->getOne($sql);  
         $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);  
         if (database::isError($restriction)) {  
             die($restriction->getMessage());  
         }          
         return $restriction;  
2720      }      }
2721    
2722      /**      /**
# Line 2506  class instruction extends instruction_ge Line 2997  class instruction extends instruction_ge
2997       * @return string L'identifiant des données techniques liées du dossier       * @return string L'identifiant des données techniques liées du dossier
2998       */       */
2999      function getDonneesTechniques() {      function getDonneesTechniques() {
3000        
3001            $qres = $this->f->get_one_result_from_db_query(
3002                sprintf(
3003                    'SELECT
3004                        donnees_techniques
3005                    FROM
3006                        %1$sdonnees_techniques
3007                    WHERE
3008                        dossier_instruction = \'%2$s\'',
3009                    DB_PREFIXE,
3010                    $this->f->db->escapeSimple($this->valF["dossier"])
3011                ),
3012                array(
3013                    "origin" => __METHOD__,
3014                )
3015            );
3016                    
3017          $donnees_techniques = '';          return $qres['result'];
   
         $sql = "SELECT donnees_techniques  
             FROM ".DB_PREFIXE."donnees_techniques  
             WHERE dossier_instruction ='".$this->valF["dossier"]."'";  
         $donnees_techniques = $this->f->db->getOne($sql);  
         $this->f->addToLog("getStatut() : db->getOne(\"".$sql."\")", VERBOSE_MODE);  
         if ( database::isError($donnees_techniques)){  
             die();  
         }  
   
         return $donnees_techniques;  
3018      }      }
3019    
3020      /**      /**
# Line 2557  class instruction extends instruction_ge Line 3053  class instruction extends instruction_ge
3053          $valF_dt = array();          $valF_dt = array();
3054          //          //
3055          // Récupération des paramètres de l'action          // Récupération des paramètres de l'action
3056          $sql = "SELECT * FROM ".DB_PREFIXE."action          // TODO : remplacer cette requête par l'instanciation de l'action
3057          WHERE action='".$this->valF['action']."'";          $qres = $this->f->get_all_results_from_db_query(
3058          $res = $this->f->db->query($sql);              sprintf(
3059          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);                  'SELECT
3060          if (database::isError($res)) {                      *
3061              die($res->getMessage());                  FROM
3062          }                      %1$saction
3063          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {                  WHERE
3064                        action = \'%2$s\'',
3065                    DB_PREFIXE,
3066                    $this->f->db->escapeSimple($this->valF['action'])
3067                ),
3068                array(
3069                    "origin" => __METHOD__
3070                )
3071            );
3072            foreach ($qres['result'] as $row) {
3073    
3074              // pour chacune des regles, on applique la regle              // pour chacune des regles, on applique la regle
3075              if ($row['regle_delai'] != '') {              if ($row['regle_delai'] != '') {
# Line 2706  class instruction extends instruction_ge Line 3211  class instruction extends instruction_ge
3211              $dt_id = $this->getDonneesTechniques();              $dt_id = $this->getDonneesTechniques();
3212              // On met à jour le dossier              // On met à jour le dossier
3213              $cle = " donnees_techniques='".$dt_id."'";              $cle = " donnees_techniques='".$dt_id."'";
3214              $res1 = $this->f->db->autoExecute(DB_PREFIXE.'donnees_techniques', $valF_dt, DB_AUTOQUERY_UPDATE, $cle);              $res1 = $this->f->db->autoexecute(DB_PREFIXE.'donnees_techniques', $valF_dt, DB_AUTOQUERY_UPDATE, $cle);
3215              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE."donnees_techniques\", ".print_r($valF_dt, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);              $this->addToLog(
3216              if (database::isError($res1)) {                  __METHOD__."(): db->autoexecute(\"".DB_PREFIXE."donnees_techniques\", ".print_r($valF_dt, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");",
3217                  die($res->getMessage());                  VERBOSE_MODE
3218              }              );
3219                $this->f->isDatabaseError($res1);
3220              // Affichage d'informations à l'utilisateur              // Affichage d'informations à l'utilisateur
3221              $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')."]");
3222          }          }
# Line 2935  class instruction extends instruction_ge Line 3441  class instruction extends instruction_ge
3441          if ($inst_evenement->getVal('notification') === 'notification_automatique' &&          if ($inst_evenement->getVal('notification') === 'notification_automatique' &&
3442              ($inst_evenement->getVal('lettretype') === null ||              ($inst_evenement->getVal('lettretype') === null ||
3443              $inst_evenement->getVal('lettretype') === '')) {              $inst_evenement->getVal('lettretype') === '')) {
3444                // Message à afficher dans les logs pour indiquer quelle notification a échouée
3445                $msgLog = sprintf(
3446                    '%s %s : %d',
3447                    __('Erreur lors de la notification automatique du(des) pétitionnaire(s).'),
3448                    __('Instruction notifiée'),
3449                    $id
3450                );
3451    
3452              // Récupération de la liste des demandeurs à notifier et de la catégorie              // Récupération de la liste des demandeurs à notifier et de la catégorie
3453              $categorie = $this->f->get_param_option_notification($collectivite_di);              $categorie = $this->f->get_param_option_notification($collectivite_di);
3454              $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;              $isPortal = $categorie === PORTAL;
3455              $demandeursANotifie = $this->get_demandeurs_notifiable(              $demandeursANotifie = $this->get_demandeurs_notifiable(
3456                  $this->valF['dossier'],                  $this->valF['dossier'],
3457                  $isPortal                  $isPortal
3458              );              );
3459    
3460              // Création d'une notification et d'une tâche pour chaque demandeur à notifier              // Création d'une notification et d'une tâche pour chaque demandeur à notifier
3461                $demandeurPrincipalNotifie = false;
3462              foreach ($demandeursANotifie as $demandeur) {              foreach ($demandeursANotifie as $demandeur) {
3463                    // Identifie si le demandeur principal a été notifié ou pas
3464                    // et récupère ses informations
3465                    if ($demandeur['petitionnaire_principal'] == 't') {
3466                        $demandeurPrincipalNotifie = true;
3467                        // Si le demandeur principal est notifiable mais qu'il y a des erreurs dans
3468                        // son paramétrage, on effectue pas le traitement et on passe à l'itération
3469                        // suivante. On le considère également comme non notifié pour gérer l'envoie
3470                        // des messages d'erreurs
3471                        // Si la demande a été déposée via le portail alors le paramétrage n'a pas
3472                        // d'impact sur la notification
3473                        $erreursParam = $this->get_info_notification_fail($val['dossier']);
3474                        if (! $this->dossier_depose_sur_portail($val['dossier']) && $erreursParam != array()) {
3475                            $demandeurPrincipalNotifie = false;
3476                            continue;
3477                        }
3478                    }
3479                  // Ajout de la notif et récupération de son id                  // Ajout de la notif et récupération de son id
3480                  $idNotif = $this->ajouter_notification(                  $idNotif = $this->ajouter_notification(
3481                      $this->valF[$this->clePrimaire],                      $this->valF[$this->clePrimaire],
3482                      $this->f->get_connected_user_login_name(),                      $this->f->get_connected_user_login_name(),
3483                      $demandeur,                      $demandeur,
3484                      $collectivite_di,                      $collectivite_di,
3485                        array(),
3486                      true                      true
3487                  );                  );
3488                  if ($idNotif === false) {                  if ($idNotif === false) {
3489                        $this->addToLog(
3490                            sprintf('%s() : %s', __METHOD__, $msgLog),
3491                            DEBUG_MODE
3492                        );
3493                      return false;                      return false;
3494                  }                  }
3495                  // Création de la tache en lui donnant l'id de la notification                  // Création de la tache en lui donnant l'id de la notification
# Line 2963  class instruction extends instruction_ge Line 3499  class instruction extends instruction_ge
3499                      $categorie                      $categorie
3500                  );                  );
3501                  if ($notification_by_task === false) {                  if ($notification_by_task === false) {
3502                        $this->addToLog(
3503                            sprintf('%s() : %s', __METHOD__, $msgLog),
3504                            DEBUG_MODE
3505                        );
3506                      $this->addToMessage(                      $this->addToMessage(
3507                          __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")                          __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
3508                      );                      );
3509                      return false;                      return false;
3510                  }                  }
3511              }              }
3512                // Pour la notification par mail ou la notification via portal si le dossier a
3513                // été déposés via portal, si le demandeur principal n'est pas notifiable,
3514                // on créé une nouvelle notification en erreur avec en commentaire la raison pour
3515                // laquelle le demandeur principal n'a pas pu être notifié
3516                $depotPortal = $this->dossier_depose_sur_portail();
3517                if (! $demandeurPrincipalNotifie && ($isPortal === false || $depotPortal === true)) {
3518                    // Précision dans les logs que le pétitionnaire principal n'est pas notifiable.
3519                    // ' ' permet de mettre un espace entre les 2 msg de log.
3520                    $msgLog .= sprintf(' %s', __('Le pétitionnaire principale n\'est pas notifiable.'));
3521                    // Analyse pour savoir pourquoi le demandeur principal n'est pas notifiable
3522                    $erreursParam = $this->get_info_notification_fail($val['dossier']);
3523                    $demandeurPrincipal = $this->get_info_petitionnaire_principal_dossier($val['dossier']);
3524                    // Ajout de la notif et récupération de son id
3525                    $idNotif = $this->ajouter_notification(
3526                        $this->valF[$this->clePrimaire],
3527                        $this->f->get_connected_user_login_name(),
3528                        $demandeurPrincipal,
3529                        $collectivite_di,
3530                        array(),
3531                        true,
3532                        'Echec',
3533                        implode(' ', $erreursParam)
3534                    );
3535                    if ($idNotif === false) {
3536                        $this->addToLog(
3537                            sprintf('%s() : %s', __METHOD__, $msgLog),
3538                            DEBUG_MODE
3539                        );
3540                        $this->addToMessage(
3541                            __('Erreur : la création de la notification a échouée.').
3542                            __("Veuillez contacter votre administrateur.")
3543                        );
3544                        return false;
3545                    }
3546                    // Prépare un message d'alerte à destination de l'instructeur pour l'informer
3547                    // de l'échec de la notification
3548                    $dossier_message = $this->get_inst_dossier_message(0);
3549                    $dossier_message_val = array(
3550                        'dossier' => $val['dossier'],
3551                        'type' => _('erreur expedition'),
3552                        'emetteur' => $this->f->get_connected_user_login_name().' (automatique)',
3553                        'login' => $_SESSION['login'],
3554                        'date_emission' => date('Y-m-d H:i:s'),
3555                        'contenu' => _('Échec lors de la notification de l\'instruction ').
3556                            $inst_evenement->getVal('libelle').
3557                            '.<br>'.
3558                            implode("\n", $erreursParam).
3559                            '<br>'.
3560                            _('Veuillez corriger ces informations avant de renvoyer la notification.')
3561                    );
3562                    $add = $dossier_message->add_notification_message($dossier_message_val, true);
3563                    // Si une erreur se produit pendant l'ajout
3564                    if ($add !== true) {
3565                        $this->addToLog(__METHOD__."(): Le message d'alerte concernant l'echec de l'envoi de la notification n'a pas pu être envoyé.", DEBUG_MODE);
3566                        return false;
3567                    }
3568                }
3569              $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.")));              $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.")));
3570          }          }
3571    
3572            // Notification automatique en cas de dépôt de dossier dématérialisé
3573            // Vérifie si l'option de notification est active et si il s'agit bien d'une
3574            // instruction de récépissé
3575            if (
3576                $this->f->is_option_notification_depot_demat_enabled($collectivite_di)
3577                && $this->is_instruction_recepisse()
3578            ) {
3579                // Message à afficher dans les logs pour indiquer quelle notification a échouée
3580                $msgLog = sprintf(
3581                    __('Erreur lors de la notification de dépôt du dossier dématérialisé : %s.'),
3582                    $val['dossier']
3583                );
3584                // Récupère l'instance de la demande
3585                $demande = $inst_di->get_inst_demande();
3586                // Vérifie que le dossier a été déposé via platau ou portal
3587                if (
3588                    ($demande->getVal('source_depot') == PLATAU ||
3589                    $demande->getVal('source_depot') == PORTAL)
3590                ) {
3591                    // Récupère la liste des mails fournis en paramètre. Si aucun adresse n'a été récupéré
3592                    // l'envoi de la notification n'est pas effectué et un message d'erreur est affiché.
3593                    $listeEmails = $this->f->get_param_courriel_de_notification_commune($collectivite_di);
3594                    if (empty($listeEmails)) {
3595                        $this->addToLog(
3596                            sprintf(
3597                                '%s(): %s %s',
3598                                __METHOD__,
3599                                $msgLog,
3600                                __('Aucun courriel paramétré.')
3601                            ),
3602                            DEBUG_MODE
3603                        );
3604                    } else {
3605                        foreach ($listeEmails as $email) {
3606                            // Ajout de la notif et récupération de son id
3607                            $destinataire = array(
3608                                'destinataire' => $email,
3609                                'courriel' => $email
3610                            );
3611                            $idNotif = $this->ajouter_notification(
3612                                $this->valF[$this->clePrimaire],
3613                                $this->f->get_connected_user_login_name(),
3614                                $destinataire,
3615                                $collectivite_di,
3616                                array(),
3617                                true
3618                            );
3619                            if ($idNotif === false) {
3620                                $this->addToLog(
3621                                    sprintf('%s(): %s', __METHOD__, $msgLog),
3622                                    DEBUG_MODE
3623                                );
3624                                return false;
3625                            }
3626                            // Création de la tache en lui donnant l'id de la notification
3627                            $notification_by_task = $this->notification_by_task(
3628                                $idNotif,
3629                                $this->valF['dossier'],
3630                                'mail',
3631                                'notification_depot_demat'
3632                            );
3633                            if ($notification_by_task === false) {
3634                                $this->addToMessage(
3635                                    __("Erreur lors de la génération de la notification de dépot de dossier par voie dématérialisée.")
3636                                );
3637                                $this->addToLog(
3638                                    sprintf('%s(): %s', __METHOD__, $msgLog),
3639                                    DEBUG_MODE
3640                                );
3641                                return false;
3642                            }
3643                        }
3644                    }
3645                }
3646            }
3647    
3648          /**          /**
3649           * Mise à jour de la date de dernière modification du dossier           * Mise à jour de la date de dernière modification du dossier
3650           */           */
# Line 2995  class instruction extends instruction_ge Line 3668  class instruction extends instruction_ge
3668          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));
3669      }      }
3670    
3671        /**
3672         * Cette méthode vérifie si toutes les conditions de l'envoi de la notification
3673         * sont remplies.
3674         * Les conditions vérifiées sont les suivantes :
3675         *  - L'option de notification *option_notification* doit être définie
3676         *  - Le petitionnaire principal doit accepter les notifications
3677         *  - Le pétitionnaire principal doit avoir une adresse mail renseignée
3678         *  - Le pétitionnaire principal doit avoir une adresse mail correcte
3679         * Pour chaque vérification effectué un message d'erreur est ajouté si la
3680         * condition n'est pas remplie.
3681         * Renvoie le message d'erreur en sortie.
3682         *
3683         * @param string identifiant du dossier sur lequel les notifications ont échouée
3684         * @return string
3685         */
3686        protected function get_info_notification_fail($dossier = null) {
3687            // Utilise l'identifiant du dossier passé en paramètre et si aucun dossier n'a été récupéré
3688            // utilise celui associé à l'instruction
3689            if ($dossier == null) {
3690                $dossier = $this->getVal('dossier');
3691            }
3692            // Tableau contenant la liste des messages d'erreur
3693            $errorMessage = array();
3694            // Récupère l'option de notification
3695            $collectivite_di = $this->get_dossier_instruction_om_collectivite($dossier);
3696            $option_notification = $this->f->get_param_option_notification($collectivite_di);
3697            if ($option_notification !== PORTAL && $option_notification !== 'mail') {
3698                $errorMessage[] = __("L'option de notification option_notification doit obligatoirement être définie.");
3699            }
3700            // Récupère les informations du demandeurs principal
3701            $infoPetitionnaire = $this->get_info_petitionnaire_principal_dossier($dossier);
3702            // Vérifie si le pétitionnaire principal à bien la case "accepte les notification" cochée
3703            if (isset($infoPetitionnaire['notification']) && $infoPetitionnaire['notification'] != 't') {
3704                $errorMessage[] = __('Le pétitionnaire principal n\'accepte pas les notifications.');
3705            }
3706            // Vérifie si l'adresse mail du pétitionnaire principale est renseignée
3707            if (isset($infoPetitionnaire['courriel']) && ! empty($infoPetitionnaire['courriel'])) {
3708                // Vérifie si le format de l'adresse mail est pas correct et, si ce n'est pas le cas, informe l'utilisateur
3709                // qu'il doit le corriger avant de pouvoir ajouter l'nstruction
3710                if (! $this->f->checkValidEmailAddress($infoPetitionnaire['courriel'])) {
3711                    $errorMessage[] = __('Le courriel du pétitionnaire principal n\'est pas correct : ').
3712                        $infoPetitionnaire['courriel'].
3713                        '.';
3714                }
3715            } else {
3716                // Si le courriel du pétitionnaire principal
3717                $errorMessage[] = __('Le courriel du pétitionnaire principal n\'est pas renseigné.');
3718            }
3719    
3720            return $errorMessage;
3721        }
3722    
3723        /**
3724         * Méthode servant à vérifier si un dossier a été déposé sur
3725         * le portail citoyen ou pas.
3726         * La verification se fait via une requête sql dans laquelle
3727         * on va chercher un dossier ayant pour id l'identifiant de
3728         * dossier associé à l'instruction et pour lequel la demande
3729         * associée la plus ancienne est une demande de création de
3730         * dossier via portail
3731         *
3732         * @param string identifiant du dossier. Si non renseigné c'est le dossier
3733         * associé à l'instruction qui est utilisé
3734         * @return boolean|void true : dossier déposé via portail, false : dossier
3735         * non déposé via portail et null : erreur de base de données.
3736         */
3737        protected function dossier_depose_sur_portail($dossier = null) {
3738            if (empty($dossier)) {
3739                $dossier = $this->getVal('dossier');
3740            }
3741            $qres = $this->f->get_one_result_from_db_query(
3742                sprintf(
3743                    'SELECT
3744                        dossier
3745                    FROM
3746                        %1$sdossier
3747                        -- Récuperation de la première demande associée au dossier
3748                        LEFT JOIN (
3749                            SELECT
3750                                demande,
3751                                dossier_instruction,
3752                                source_depot
3753                            FROM
3754                                %1$sdemande
3755                            WHERE
3756                               dossier_instruction = \'%2$s\'
3757                            ORDER BY
3758                               demande ASC
3759                            LIMIT 1
3760                        ) AS demande
3761                            ON dossier.dossier = demande.dossier_instruction
3762                    WHERE
3763                        dossier.dossier = \'%2$s\'
3764                        AND demande.source_depot = \'portal\'',
3765                    DB_PREFIXE,
3766                    $this->f->db->escapeSimple($dossier)
3767                ),
3768                array(
3769                    "origin" => __METHOD__,
3770                    "force_return" => true,
3771                )
3772            );
3773            if ($qres["code"] !== "OK") {
3774                $this->addToMessage(__('Erreur : La vérification du mode de dépôt du dossier à échoué'));
3775                return;
3776            }
3777            // Si on a un résultat c'est que le dossier a été déposé via le portail
3778            return ! empty($qres["result"]);
3779        }
3780    
3781        public function is_service_notifiable() {
3782            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
3783    
3784            // Si l'instruction a une édition non finalisé quel que soit
3785            // le type de notification, il n'est pas notifiable
3786            if ($this->has_an_edition() === true) {
3787                if ($this->is_unfinalizable_without_bypass() === false) {
3788                    return false;
3789                }
3790            }
3791            // Vérifie si la notification des tiers est active pour l'évènement
3792            return $this->get_boolean_from_pgsql_value($evenement->getVal('notification_service'));
3793        }
3794    
3795        public function is_tiers_notifiable() {
3796            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
3797    
3798            // Si l'instruction a une édition non finalisé quel que soit
3799            // le type de notification, il n'est pas notifiable
3800            if ($this->has_an_edition() === true) {
3801                if ($this->is_unfinalizable_without_bypass() === false) {
3802                    return false;
3803                }
3804            }
3805            // Vérifie si la notification des tiers est active pour l'évènement
3806            return ! empty($evenement->getVal('notification_tiers'));
3807        }
3808    
3809        /**
3810         * Méthode permettant de savoir si une instruction peut
3811         * être notifiée manuellement selon les différents types
3812         * de notification.
3813         *
3814         * Si l'instruction a une édition non finalisée alors elle n'est pas
3815         * manuellement notifiable.
3816         * Si l'instruction est associé à un événement de notification pour
3817         * lequel un retour signature est recquis, elle n'est notifiable que
3818         * si la date de retour de signature est remplie.
3819         * Par défaut si le type de notification n'est pas connu alors l'instruction
3820         * n'est pas notifiable.
3821         * Pour tous les autres cas l'instruction est manuellement notifiable.
3822         *
3823         * @return boolean true : notifiable | false : non notifiable
3824         */
3825      public function is_notifiable_by_task_manual() {      public function is_notifiable_by_task_manual() {
3826          $ev = $this->get_inst_evenement($this->getVal('evenement'));          $ev = $this->get_inst_evenement($this->getVal('evenement'));
3827    
# Line 3007  class instruction extends instruction_ge Line 3834  class instruction extends instruction_ge
3834          }          }
3835    
3836          // Gestion des différents cas selon la valeur du champs notification          // Gestion des différents cas selon la valeur du champs notification
3837          switch ($ev->getVal('notification')) {          if ($ev->getVal('notification') == 'notification_manuelle' ||
3838              case 'notification_manuelle':              $ev->getVal('notification') == 'notification_manuelle_annexe' ||
3839                  return true;              $ev->getVal('notification') == 'notification_automatique'
3840              case 'notification_manuelle_annexe':          ) {
3841                  return true;              return true;
3842              case 'notification_automatique':          } elseif (($ev->getVal('notification') == 'notification_auto_signature_requise' ||
3843                  return false;              $ev->getVal('notification') == 'notification_manuelle_signature_requise' ||
3844              case 'notification_auto_signature_requise':              $ev->getVal('notification') == 'notification_manuelle_annexe_signature_requise') &&
3845                  return false;              $this->getVal('date_retour_signature') != null &&
3846              case 'notification_manuelle_signature_requise':              $this->getVal('date_retour_signature') != ''
3847                  // Si il y a une date de retour de signature la notification est possible          ) {
3848                  if ($this->getVal('date_retour_signature') === null              return true ;
                     || $this->getVal('date_retour_signature') === '') {  
                     return false;  
                 }  
                 return true;  
             case 'notification_manuelle_annexe_signature_requise':  
                 // Si il y a une date de retour de signature la notification est possible  
                 if ($this->getVal('date_retour_signature') === null  
                     || $this->getVal('date_retour_signature') === '') {  
                     return false;  
                 }  
                 return true;  
             default:  
                 return false;  
3849          }          }
3850            return false;
3851      }      }
3852    
3853      /**      /**
3854       * Crée une instance et une tache de notification pour le demandeur       * Crée une instance de notification et une tache notification_instruction de catégorie portal
3855       * principal.       * pour le demandeur principal.
3856       *       *
3857       * @return boolean true si le traitement à réussi       * @return boolean true si le traitement à réussi
3858       */       */
3859      protected function notifier_demandeur_principal() {      protected function notifier_demandeur_principal_via_portal() {
3860          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
3861          $message = '';          $message = '';
3862          // Récupération des informations concernant le demandeur          // Récupération des informations concernant le demandeur
# Line 3059  class instruction extends instruction_ge Line 3874  class instruction extends instruction_ge
3874                  $this->f->get_connected_user_login_name(),                  $this->f->get_connected_user_login_name(),
3875                  $destinataire[0],                  $destinataire[0],
3876                  $collectivite_di,                  $collectivite_di,
3877                    array(),
3878                  true                  true
3879              );              );
3880              if ($idNotification === false) {              if ($idNotification === false) {
3881                  return $this->end_treatment(__METHOD__, false);                  return $this->end_treatment(__METHOD__, false);
3882              }              }
3883              // Création de la tâche en lui donnant l'id de la notification              // Création de la tâche en lui donnant l'id de la notification
3884              $notification_by_task = $this->notification_by_task($idNotification, $dossier);              $notification_by_task = $this->notification_by_task($idNotification, $dossier, PORTAL);
3885              if ($notification_by_task === false) {              if ($notification_by_task === false) {
3886                  $this->addToMessage(                  $this->addToMessage(
3887                      __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")                      __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
# Line 3076  class instruction extends instruction_ge Line 3892  class instruction extends instruction_ge
3892              return $this->end_treatment(__METHOD__, true);              return $this->end_treatment(__METHOD__, true);
3893          }          }
3894          $this->addToMessage( __("Le demandeur principal n'est pas notifiable."));          $this->addToMessage( __("Le demandeur principal n'est pas notifiable."));
3895          return $this->end_treatment(__METHOD__, true);          return $this->end_treatment(__METHOD__, false);
3896      }      }
3897    
3898      public function notification_by_task($object_id, $dossier, $category = null, $type = null) {      public function notification_by_task($object_id, $dossier, $category = null, $type = null) {
         // Par défaut le type est portal  
         if ($category === null) {  
             $category = 'portal';  
         }  
3899          // Si le type n'est pas correctement spécifié, alors il est calculé          // Si le type n'est pas correctement spécifié, alors il est calculé
3900          if ($type === null          if ($type !== 'notification_recepisse'
3901              || $type !== 'notification_recepisse'              && $type !== 'notification_instruction'
3902              || $type !== 'notification_instruction'              && $type !== 'notification_decision'
3903              || $type !== 'notification_decision') {              && $type !== 'notification_service_consulte'
3904                && $type !== 'notification_tiers_consulte'
3905                && $type !== 'notification_depot_demat'
3906                && $type !== 'notification_commune'
3907                && $type !== 'notification_signataire') {
3908              //              //
3909              $type = 'notification_instruction';              $type = 'notification_instruction';
3910              // Vérifie si l'instruction est un récépissé              // Vérifie si l'instruction est un récépissé
3911              $trace = debug_backtrace();              if ($this->is_instruction_recepisse()) {
3912              foreach ($trace as $key => $value) {                  $type = 'notification_recepisse';
3913                  if (isset($trace[$key]['class']) === true  
                     && empty($trace[$key]['class']) === false) {  
                     //  
                     if (strtolower($trace[$key]['class']) === 'demande') {  
                         $type = 'notification_recepisse';  
                     }  
                 }  
3914              }              }
3915              // Vérifie si l'instruction est une décision              // Vérifie si l'instruction est une décision
3916              if ($type !== 'notification_recepisse') {              if ($type !== 'notification_recepisse') {
# Line 3110  class instruction extends instruction_ge Line 3920  class instruction extends instruction_ge
3920                  }                  }
3921              }              }
3922          }          }
3923          // Préparation de la tache de notification          // Préparation des valeurs de la tâche
         $inst_task = $this->f->get_inst__om_dbform(array(  
             "obj" => "task",  
             "idx" => 0,  
         ));  
3924          $task_val = array(          $task_val = array(
3925              'type' => $type,              'type' => $type,
3926              'object_id' => $object_id,              'object_id' => $object_id,
3927              'dossier' => $dossier,              'dossier' => $dossier,
3928              'category' => $category,              'category' => $category,
3929          );          );
3930            // Préparation de la tache de notification
3931            $inst_task = $this->f->get_inst__om_dbform(array(
3932                "obj" => "task",
3933                "idx" => 0,
3934            ));
3935    
3936          $add_task = $inst_task->add_task(array('val' => $task_val));          $add_task = $inst_task->add_task(array('val' => $task_val));
3937          if ($add_task === false) {          if ($add_task === false) {
3938                $this->addToLog(
3939                    sprintf(
3940                        '%s(): %s %s : %s',
3941                        __METHOD__,
3942                        __('Echec de l\'ajout de la tâche de notification.'),
3943                        __('Paramétrage de la tâche'),
3944                        var_export($task_val, true)
3945                    ),
3946                    DEBUG_MODE
3947                );
3948              return false;              return false;
3949          }          }
3950    
# Line 3131  class instruction extends instruction_ge Line 3952  class instruction extends instruction_ge
3952      }      }
3953    
3954      /**      /**
3955         * Cette méthode permet de savoir si l'instruction est une instruction
3956         * de recepisse (instruction lié à l'ajout du dossier).
3957         *
3958         * Pour cela, on récupère la liste des actions qui ont menées à la création
3959         * de l'instruction. Si une de ces actions est lié à un objet "demande" on
3960         * en deduis que c'est l'ajout d'une demande qui a déclenché la création de
3961         * l'instruction et donc qu'il s'agit d'un recepisse.
3962         *
3963         * @return boolean
3964         */
3965        protected function is_instruction_recepisse() {
3966            // Récupère la liste des actions qui ont mené à la création de
3967            // l'instruction
3968            $trace = debug_backtrace();
3969            // Parcours la liste des actions et si une de ces actions est lié
3970            // à la classe demande on cosidère que l'instruction est un recepisse
3971            foreach ($trace as $key => $value) {
3972                if (isset($trace[$key]['class']) === true
3973                    && empty($trace[$key]['class']) === false) {
3974                    if (strtolower($trace[$key]['class']) === 'demande') {
3975                        return true;
3976                    }
3977                }
3978            }
3979            return false;
3980        }
3981    
3982        /**
3983       * A partir des informations passée en argument ajoute un nouvel élément       * A partir des informations passée en argument ajoute un nouvel élément
3984       * dans la table instruction_notification.       * dans la table instruction_notification.
3985       * Avant l'ajout vérifie en utilisant l'id de la collectivité passée en       * Avant l'ajout vérifie en utilisant l'id de la collectivité passée en
# Line 3160  class instruction extends instruction_ge Line 4009  class instruction extends instruction_ge
4009          $emetteur,          $emetteur,
4010          $destinataire,          $destinataire,
4011          $collectiviteId,          $collectiviteId,
4012            $annexes = array(),
4013          $demandeAuto = false,          $demandeAuto = false,
4014          $idInstrDocAnnexe = null          $statut = 'en cours d\'envoi',
4015            $commentaire = 'Notification en cours de traitement'
4016      ) {      ) {
4017          // Vérification que les paramètres nécessaires à l'envoi de la notification existe avant          // Vérification que les paramètres nécessaires à l'envoi de la notification existe avant
4018          // de créer la notification          // de créer la notification
4019          if (! $this->is_parametrage_notification_correct($collectiviteId)) {          if (! $this->is_parametrage_notification_correct($collectiviteId)) {
4020              $this->addToMessage(__("Erreur de paramétrage. L'url d'accès au(x) document(s) notifié(s) n'est pas paramétrée."));              $msgErreur = __("Erreur de paramétrage. L'url d'accès au(x) document(s) notifié(s) n'est pas paramétrée.");
4021                $this->addToMessage($msgErreur);
4022                $this->addToLog(
4023                    sprintf('%s() : %s', __METHOD__, $msgErreur),
4024                    DEBUG_MODE
4025                );
4026              return false;              return false;
4027          }          }
4028          // Préparation de la notification          // Préparation de la notification
# Line 3183  class instruction extends instruction_ge Line 4039  class instruction extends instruction_ge
4039              'destinataire' => $destinataire['destinataire'],              'destinataire' => $destinataire['destinataire'],
4040              'courriel' => $destinataire['courriel'],              'courriel' => $destinataire['courriel'],
4041              'date_premier_acces' => null,              'date_premier_acces' => null,
4042              'statut' => 'en cours d\'envoi',              'statut' => $statut,
4043              'commentaire' => 'Notification en cours de traitement'              'commentaire' => $commentaire
4044          );          );
4045    
4046          // Création de la notification          // Création de la notification
4047          $add_notif = $inst_notif->ajouter($notif_val);          $add_notif = $inst_notif->ajouter($notif_val);
4048          if ($add_notif === false) {          if ($add_notif === false) {
4049              $this->addToMessage(__("Erreur lors de la génération de la notification au(x) pétitionnaire(s)."));              $this->addToMessage(__("Erreur lors de la génération de la notification au(x) pétitionnaire(s)."));
4050                $this->addToLog(
4051                    sprintf(
4052                        '%s() : %s %s : %s',
4053                        __METHOD__,
4054                        __("Echec de l'ajout de la notification en base de données."),
4055                        __('Paramétrage de la notification'),
4056                        var_export($notif_val, true)
4057                    ),
4058                    DEBUG_MODE
4059                );
4060              return false;              return false;
4061          }          }
4062    
4063          // Si il y a une lettretype finalisé stockage de la clé d'accès au documents          // Si il y a une lettretype finalisé stockage de la clé d'accès au documents
4064          if ($this->evenement_has_an_edition($this->getVal('evenement')) === true) {          if ($this->evenement_has_an_edition($this->getVal('evenement')) === true) {
4065              $add_notif_doc = $this->ajouter_notification_document(              $add_notif_doc = $this->ajouter_notification_document(
4066                    $inst_notif->getVal($inst_notif->clePrimaire),
4067                  $this->getVal($this->clePrimaire),                  $this->getVal($this->clePrimaire),
4068                  $inst_notif->getVal($inst_notif->clePrimaire)                  'instruction'
4069              );              );
4070              if ($add_notif_doc === false) {              if ($add_notif_doc === false) {
4071                  $this->addToMessage(__("Erreur lors de la génération de la notification du document."));                  $this->addToMessage(__("Erreur lors de la génération de la notification du document."));
# Line 3206  class instruction extends instruction_ge Line 4073  class instruction extends instruction_ge
4073              }              }
4074          }          }
4075          // Si une annexe a été choisie stockage de la clé d'accès à l'annexe          // Si une annexe a été choisie stockage de la clé d'accès à l'annexe
4076          if ($idInstrDocAnnexe != null || $idInstrDocAnnexe != '') {          if (! empty($annexes) && is_array($annexes)) {
4077              $add_notif_annexe = $this->ajouter_notification_document(              $add_notif_annexe = $this->ajouter_notification_document_multiple(
                 $idInstrDocAnnexe,  
4078                  $inst_notif->getVal($inst_notif->clePrimaire),                  $inst_notif->getVal($inst_notif->clePrimaire),
4079                  true                  $annexes
4080              );              );
4081              if ($add_notif_annexe === false) {              if ($add_notif_annexe === false) {
4082                  $this->addToMessage(__("Erreur lors de la génération de la notification de l'annexe."));                  $this->addToMessage(__("Erreur lors de la génération de la notification de l'annexe."));
# Line 3223  class instruction extends instruction_ge Line 4089  class instruction extends instruction_ge
4089      }      }
4090    
4091      /**      /**
4092       * Vérifie si le paramétrage de la notification des demandeurs est correct.       * Pour chaque élément du tableau passé en paramètre ajoute une nouvelle
4093         * instance dans la table instruction_notification_document lié a la
4094         * notification dont l'id est passé en paramètre.
4095       *       *
4096       * @param integer identifiant de la collectivité       * @param array tableau contenant les informations nécessaires pour créer les annexes
4097       * @return boolean       *
4098         * @return integer|boolean identifiant de la notification créée si le traitement
4099         * a réussie, false sinon.
4100       */       */
4101      protected function is_parametrage_notification_correct($collectiviteId) {      protected function ajouter_notification_document_multiple($idNotification, $listeDocument) {
4102          $categorie = $this->f->get_param_option_notification($collectiviteId);          foreach ($listeDocument as $paramDoc) {
4103          $urlAccesNotif = $this->f->get_parametre_notification_url_acces($collectiviteId);              if (! $this->ajouter_notification_document($idNotification, $paramDoc['id'], $paramDoc['tableDocument'], $paramDoc['isAnnexe'])) {
4104          if ($categorie == 'mail' && $urlAccesNotif == null) {                  $this->addToMessage(__("Erreur lors de la génération des documents à notifier."));
4105              return false;                  return false;
4106                }
4107          }          }
4108          return true;          return true;
4109      }      }
4110    
4111      /**      /**
4112       * Ajoute un élément dans la table instruction_notification_document.       * Ajoute un élément dans la table instruction_notification_document en utilisant
4113         * les éléments fourni en paramètre
4114       *       *
      * @param integer $idInstruction : id de l'instruction à laquelle est rattaché le document  
4115       * @param integer $idNotification : id de la notification à laquelle on associe le document       * @param integer $idNotification : id de la notification à laquelle on associe le document
4116         * @param integer $idDocument : id de l'objet auquel est rattaché le document
4117         * @param string $tableDocument : nom de la table a laquelle est rattaché le document
4118       * @param boolean $isAnnexe : indique si le document est une annexe ou pas       * @param boolean $isAnnexe : indique si le document est une annexe ou pas
4119       *       *
4120       * @return boolean indique si le traitement a réussi       * @return boolean indique si le traitement a réussi
4121       */       */
4122      protected function ajouter_notification_document($idInstruction, $idNotification, $isAnnexe = false) {      protected function ajouter_notification_document($idNotification, $idDocument, $tableDocument, $isAnnexe = false) {
4123          $inst_notif_doc = $this->f->get_inst__om_dbform(array(          $inst_notif_doc = $this->f->get_inst__om_dbform(array(
4124              "obj" => "instruction_notification_document",              "obj" => "instruction_notification_document",
4125              "idx" => "]",              "idx" => "]",
4126          ));          ));
4127            // l'attribut instruction doit obligatoirement être renseigné
4128            // pour éviter toutes confusion avec d'autres instruction l'id
4129            // 0 est donné au document n'appartenant pas aux instructions
4130          $notif_doc_val = array(          $notif_doc_val = array(
4131              'instruction_notification_document' => null,              'instruction_notification_document' => null,
4132              'instruction_notification' => $idNotification,              'instruction_notification' => $idNotification,
4133              'instruction' => $idInstruction,              'instruction' => $tableDocument == 'instruction' ? $idDocument : 0,
4134                'document_type' => $tableDocument,
4135                'document_id' => $idDocument,
4136              'cle' => $this->getCleAccesDocument(),              'cle' => $this->getCleAccesDocument(),
4137              'annexe' => $isAnnexe              'annexe' => $isAnnexe
4138          );          );
4139    
4140          $add_notif_doc = $inst_notif_doc->ajouter($notif_doc_val);          $add_notif_doc = $inst_notif_doc->ajouter($notif_doc_val);
4141          if ($add_notif_doc === false) {          if ($add_notif_doc === false) {
4142                $this->addToLog(
4143                    sprintf(
4144                        '%s() : %s %s : %s',
4145                        __METHOD__,
4146                        __('Echec de l\'ajout du paramétrage du document notifié en base de données.'),
4147                        __('Paramétrage du document'),
4148                        var_export($notif_doc_val, true)
4149                    ),
4150                    DEBUG_MODE
4151                );
4152              return false;              return false;
4153          }          }
4154          return true;          return true;
4155      }      }
4156            
4157      /**      /**
4158         * Vérifie si le paramétrage de la notification des demandeurs est correct.
4159         *
4160         * @param integer identifiant de la collectivité
4161         * @return boolean
4162         */
4163        protected function is_parametrage_notification_correct($collectiviteId) {
4164            $categorie = $this->f->get_param_option_notification($collectiviteId);
4165            $urlAccesNotif = $this->f->get_parametre_notification_url_acces($collectiviteId);
4166            if ($categorie === 'mail' && $urlAccesNotif === null) {
4167                return false;
4168            }
4169            return true;
4170        }
4171    
4172        /**
4173       * TRIGGER - triggermodifierapres.       * TRIGGER - triggermodifierapres.
4174       *       *
4175       * @return boolean       * @return boolean
# Line 3275  class instruction extends instruction_ge Line 4178  class instruction extends instruction_ge
4178          $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);          $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
4179          $collectivite_di = $this->get_dossier_instruction_om_collectivite($val['dossier']);          $collectivite_di = $this->get_dossier_instruction_om_collectivite($val['dossier']);
4180          $message = '';          $message = '';
         /**  
          * L'objectif ici est d'effectuer les recalculs de date dans le dossier  
          * si la date de l'evenement est modifiee  
          */  
         // Initialisation  
         $valF = array();  
         $valF_dt = array();  
         // Initialisation du type d'événement  
         $type_evmt = "";  
         // Récupération de l'action correspondante à l'événement  
         $sql = "SELECT action  
         FROM ".DB_PREFIXE."evenement  
         WHERE evenement=".$this->valF['evenement'];  
         $action = $this->f->db->getOne($sql);  
         $this->addToLog(__METHOD__."(): db->getone(\"".$sql."\");", VERBOSE_MODE);  
         if (database::isError($action)) {  
             die($action->getMessage());  
         }  
4181    
4182          // Récupération des paramètres de l'action          // Définit si le dossier d'instruction doit être mis à jour
4183          $sql = "SELECT * FROM ".DB_PREFIXE."action          $update_dossier = true;
4184          WHERE action='".$action."'";          // Les actions de mise à jour des dates ne doivent pas appliquer
4185          $res = $this->f->db->query($sql);          // l'action de l'événement et donc ne pas mettre à jour le dossier
4186          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);          if ($this->getParameter("maj") == 125
4187          if (database::isError($res)) {              || $this->getParameter("maj") == 170
4188              die($res->getMessage());              || $this->getParameter("maj") == 175) {
4189                $update_dossier = false;
4190          }          }
4191          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){  
4192              // application des regles sur le courrier + delai          // Traitement en cas de mise à jour du dossier
4193              if(preg_match("/date_evenement/",$row['regle_date_limite'])){          if ($update_dossier === true) {
4194                  $valF['date_limite']= $this->regle($row['regle_date_limite'], 'regle_date_limite');              /**
4195              }               * L'objectif ici est d'effectuer les recalculs de date dans le dossier
4196              if(preg_match("/date_evenement/",$row['regle_date_complet'])){               * si la date de l'evenement est modifiee
4197                  $valF['date_complet']= $this->regle($row['regle_date_complet'], 'regle_date_complet');               */
4198              }              // Initialisation
4199              if(preg_match("/date_evenement/",$row['regle_date_dernier_depot'])){              $valF = array();
4200                  $valF['date_dernier_depot']= $this->regle($row['regle_date_dernier_depot'], 'regle_date_dernier_depot');              $valF_dt = array();
4201              }              // Initialisation du type d'événement
4202              if(preg_match("/date_evenement/",$row['regle_date_notification_delai'])){              $type_evmt = "";
4203                  $valF['date_notification_delai']= $this->regle($row['regle_date_notification_delai'], 'regle_date_notification_delai');              // Récupération de l'action correspondante à l'événement
4204              }              $evenement = $this->f->get_inst__om_dbform(array(
4205              if(preg_match("/date_evenement/",$row['regle_date_decision'])){                  "obj" => "evenement",
4206                  $valF['date_decision']= $this->regle($row['regle_date_decision'], 'regle_date_decision');                  "idx" => $this->valF['evenement']
4207              }              ));
4208              if(preg_match("/date_evenement/",$row['regle_date_rejet'])){  
4209                  $valF['date_rejet']= $this->regle($row['regle_date_rejet'], 'regle_date_rejet');              // Récupération des paramètres de l'action
4210              }              // TODO : remplacer cette requête par l'instanciation de l'action
4211              if(preg_match("/date_evenement/",$row['regle_date_validite'])){              $qres = $this->f->get_all_results_from_db_query(
4212                  $valF['date_validite']= $this->regle($row['regle_date_validite'], 'regle_date_validite');                  sprintf(
4213              }                      'SELECT
4214              if(preg_match("/date_evenement/",$row['regle_date_chantier'])){                          *
4215                  $valF['date_chantier']= $this->regle($row['regle_date_chantier'], 'regle_date_chantier');                      FROM
4216              }                          %1$saction
4217              if(preg_match("/date_evenement/",$row['regle_date_achevement'])){                      WHERE
4218                  $valF['date_achevement']= $this->regle($row['regle_date_achevement'], 'regle_date_achevement');                          action = \'%2$s\'',
4219              }                      DB_PREFIXE,
4220              if(preg_match("/date_evenement/",$row['regle_date_conformite'])){                      $this->f->db->escapeSimple($evenement->getVal('action'))
4221                  $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');                  ),
4222              }                  array(
4223              if(preg_match("/date_evenement/",$row['regle_date_cloture_instruction'])){                      "origin" => __METHOD__
4224                  $valF['date_cloture_instruction']= $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');                  )
4225              }              );
4226              if(preg_match("/date_evenement/",$row['regle_date_premiere_visite'])){              foreach ($qres['result'] as $row) {
4227                  $valF['date_premiere_visite']= $this->regle($row['regle_date_premiere_visite'], 'regle_date_premiere_visite');                  // application des regles sur le courrier + delai
4228              }                  if(preg_match("/date_evenement/",$row['regle_date_limite'])){
4229              if(preg_match("/date_evenement/",$row['regle_date_derniere_visite'])){                      $valF['date_limite']= $this->regle($row['regle_date_limite'], 'regle_date_limite');
4230                  $valF['date_derniere_visite']= $this->regle($row['regle_date_derniere_visite'], 'regle_date_derniere_visite');                  }
4231              }                  if(preg_match("/date_evenement/",$row['regle_date_complet'])){
4232              if(preg_match("/date_evenement/",$row['regle_date_contradictoire'])){                      $valF['date_complet']= $this->regle($row['regle_date_complet'], 'regle_date_complet');
4233                  $valF['date_contradictoire']= $this->regle($row['regle_date_contradictoire'], 'regle_date_contradictoire');                  }
4234              }                  if(preg_match("/date_evenement/",$row['regle_date_dernier_depot'])){
4235              if(preg_match("/date_evenement/",$row['regle_date_retour_contradictoire'])){                      $valF['date_dernier_depot']= $this->regle($row['regle_date_dernier_depot'], 'regle_date_dernier_depot');
4236                  $valF['date_retour_contradictoire']= $this->regle($row['regle_date_retour_contradictoire'], 'regle_date_retour_contradictoire');                  }
4237              }                  if(preg_match("/date_evenement/",$row['regle_date_notification_delai'])){
4238              if(preg_match("/date_evenement/",$row['regle_date_ait'])){                      $valF['date_notification_delai']= $this->regle($row['regle_date_notification_delai'], 'regle_date_notification_delai');
4239                  $valF['date_ait']= $this->regle($row['regle_date_ait'], 'regle_date_ait');                  }
4240              }                  if(preg_match("/date_evenement/",$row['regle_date_decision'])){
4241              if(preg_match("/date_evenement/",$row['regle_date_transmission_parquet'])){                      $valF['date_decision']= $this->regle($row['regle_date_decision'], 'regle_date_decision');
4242                  $valF['date_transmission_parquet']= $this->regle($row['regle_date_transmission_parquet'], 'regle_date_transmission_parquet');                  }
4243              }                  if(preg_match("/date_evenement/",$row['regle_date_rejet'])){
4244              if ($row['regle_donnees_techniques1'] !== '') {                      $valF['date_rejet']= $this->regle($row['regle_date_rejet'], 'regle_date_rejet');
4245                  $valF_dt[$row['cible_regle_donnees_techniques1']] = $this->regle($row['regle_donnees_techniques1'], 'regle_donnees_techniques1');                  }
4246              }                  if(preg_match("/date_evenement/",$row['regle_date_validite'])){
4247              if ($row['regle_donnees_techniques2'] !== '') {                      $valF['date_validite']= $this->regle($row['regle_date_validite'], 'regle_date_validite');
4248                  $valF_dt[$row['cible_regle_donnees_techniques2']] = $this->regle($row['regle_donnees_techniques2'], 'regle_donnees_techniques2');                  }
4249              }                  if(preg_match("/date_evenement/",$row['regle_date_chantier'])){
4250              if ($row['regle_donnees_techniques3'] !== '') {                      $valF['date_chantier']= $this->regle($row['regle_date_chantier'], 'regle_date_chantier');
4251                  $valF_dt[$row['cible_regle_donnees_techniques3']] = $this->regle($row['regle_donnees_techniques3'], 'regle_donnees_techniques3');                  }
4252              }                  if(preg_match("/date_evenement/",$row['regle_date_achevement'])){
4253              if ($row['regle_donnees_techniques4'] !== '') {                      $valF['date_achevement']= $this->regle($row['regle_date_achevement'], 'regle_date_achevement');
4254                  $valF_dt[$row['cible_regle_donnees_techniques4']] = $this->regle($row['regle_donnees_techniques4'], 'regle_donnees_techniques4');                  }
4255              }                  if(preg_match("/date_evenement/",$row['regle_date_conformite'])){
4256              if ($row['regle_donnees_techniques5'] !== '') {                      $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');
4257                  $valF_dt[$row['cible_regle_donnees_techniques5']] = $this->regle($row['regle_donnees_techniques5'], 'regle_donnees_techniques5');                  }
4258              }                  if(preg_match("/date_evenement/",$row['regle_date_cloture_instruction'])){
4259              if ($row['regle_dossier_instruction_type'] !== '') {                      $valF['date_cloture_instruction']= $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');
4260                  $valF['dossier_instruction_type'] = $this->regle($row['regle_dossier_instruction_type'], 'regle_dossier_instruction_type');                  }
4261                    if(preg_match("/date_evenement/",$row['regle_date_premiere_visite'])){
4262                        $valF['date_premiere_visite']= $this->regle($row['regle_date_premiere_visite'], 'regle_date_premiere_visite');
4263                    }
4264                    if(preg_match("/date_evenement/",$row['regle_date_derniere_visite'])){
4265                        $valF['date_derniere_visite']= $this->regle($row['regle_date_derniere_visite'], 'regle_date_derniere_visite');
4266                    }
4267                    if(preg_match("/date_evenement/",$row['regle_date_contradictoire'])){
4268                        $valF['date_contradictoire']= $this->regle($row['regle_date_contradictoire'], 'regle_date_contradictoire');
4269                    }
4270                    if(preg_match("/date_evenement/",$row['regle_date_retour_contradictoire'])){
4271                        $valF['date_retour_contradictoire']= $this->regle($row['regle_date_retour_contradictoire'], 'regle_date_retour_contradictoire');
4272                    }
4273                    if(preg_match("/date_evenement/",$row['regle_date_ait'])){
4274                        $valF['date_ait']= $this->regle($row['regle_date_ait'], 'regle_date_ait');
4275                    }
4276                    if(preg_match("/date_evenement/",$row['regle_date_transmission_parquet'])){
4277                        $valF['date_transmission_parquet']= $this->regle($row['regle_date_transmission_parquet'], 'regle_date_transmission_parquet');
4278                    }
4279                    if ($row['regle_donnees_techniques1'] !== '') {
4280                        $valF_dt[$row['cible_regle_donnees_techniques1']] = $this->regle($row['regle_donnees_techniques1'], 'regle_donnees_techniques1');
4281                    }
4282                    if ($row['regle_donnees_techniques2'] !== '') {
4283                        $valF_dt[$row['cible_regle_donnees_techniques2']] = $this->regle($row['regle_donnees_techniques2'], 'regle_donnees_techniques2');
4284                    }
4285                    if ($row['regle_donnees_techniques3'] !== '') {
4286                        $valF_dt[$row['cible_regle_donnees_techniques3']] = $this->regle($row['regle_donnees_techniques3'], 'regle_donnees_techniques3');
4287                    }
4288                    if ($row['regle_donnees_techniques4'] !== '') {
4289                        $valF_dt[$row['cible_regle_donnees_techniques4']] = $this->regle($row['regle_donnees_techniques4'], 'regle_donnees_techniques4');
4290                    }
4291                    if ($row['regle_donnees_techniques5'] !== '') {
4292                        $valF_dt[$row['cible_regle_donnees_techniques5']] = $this->regle($row['regle_donnees_techniques5'], 'regle_donnees_techniques5');
4293                    }
4294                    if ($row['regle_dossier_instruction_type'] !== '') {
4295                        $valF['dossier_instruction_type'] = $this->regle($row['regle_dossier_instruction_type'], 'regle_dossier_instruction_type');
4296                    }
4297              }              }
4298          }              // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement
4299          // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement              if (count($valF_dt) > 0) {
4300          if (count($valF_dt) > 0) {                  $dt_id = $this->getDonneesTechniques();
4301              $dt_id = $this->getDonneesTechniques();                  // On met à jour le dossier
4302              // On met à jour le dossier                  $cle = " donnees_techniques='".$dt_id."'";
4303              $cle = " donnees_techniques='".$dt_id."'";                  $res1 = $this->f->db->autoExecute(DB_PREFIXE.'donnees_techniques', $valF_dt, DB_AUTOQUERY_UPDATE, $cle);
4304              $res1 = $this->f->db->autoExecute(DB_PREFIXE.'donnees_techniques', $valF_dt, DB_AUTOQUERY_UPDATE, $cle);                  $this->addToLog(
4305              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE."donnees_techniques\", ".print_r($valF_dt, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);                      __METHOD__."(): db->autoexecute(\"".DB_PREFIXE."donnees_techniques\", ".print_r($valF_dt, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");",
4306              if (database::isError($res1)) {                      VERBOSE_MODE
4307                  die($res->getMessage());                  );
4308                    $this->f->isDatabaseError($res1);
4309                    // Affichage d'informations à l'utilisateur
4310                    $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
4311              }              }
4312              // Affichage d'informations à l'utilisateur              // Si des valeurs ont été calculées alors on met à jour l'enregistrement
4313              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");              if (count($valF) > 0) {
4314          }                  $inst_dossier = $this->f->get_inst__om_dbform(array(
4315          // Si des valeurs ont été calculées alors on met à jour l'enregistrement                      "obj" => "dossier",
4316          if (count($valF) > 0) {                      "idx" => $this->valF['dossier'],
4317              //                  ));
4318              $inst_dossier = $this->f->get_inst__om_dbform(array(                  $valF['instruction'] = $id;
4319                  "obj" => "dossier",                  $valF['crud'] = 'update';
4320                  "idx" => $this->valF['dossier'],                  $update_by_instruction = $inst_dossier->update_by_instruction($valF);
4321              ));                  if ($update_by_instruction === false) {
4322              $valF['instruction'] = $id;                      $this->cleanMessage();
4323              $valF['crud'] = 'update';                      $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
4324              $update_by_instruction = $inst_dossier->update_by_instruction($valF);                      return false;
4325              if ($update_by_instruction === false) {                  }
4326                  $this->cleanMessage();                  // Affichage d'informations à l'utilisateur
4327                  $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));                  $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
                 return false;  
4328              }              }
             // Affichage d'informations à l'utilisateur  
             $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");  
4329          }          }
4330    
4331            // Par défaut les instructions à ajouter suite à la saisie d'une date
4332            // de retour signature ou de notification, utilisent l'action 0
4333            // Si la création d'événement d'instruction suivant est déclenchée par
4334            // une notification suite au traitement d'une tâche (démat') alors l'ajout
4335            // de la nouvelle instruction se fait avec l'action 176
4336            // Cela permet de ne pas contrôler la restriction lors de l'ajout de la
4337            // nouvelle instruction, depuis la méthode verifier()
4338            $code_action_add = 0;
4339            if ($this->getParameter("maj") == 175) {
4340                $code_action_add = 176;
4341            }
4342          $restriction = $this->get_restriction($val['evenement']);          $restriction = $this->get_restriction($val['evenement']);
4343          $this->restriction_valid = $this->restrictionIsValid($restriction);          $this->restriction_valid = $this->restrictionIsValid($restriction);
4344    
4345          if($restriction == "" || $this->restriction_valid ){          if($restriction == "" || $this->restriction_valid ){
4346              // Récupération de tous les paramètres de l'événement sélectionné              // Récupération de tous les paramètres de l'événement sélectionné
4347              $sql = "SELECT * FROM ".DB_PREFIXE."evenement              // TODO : remplacer cette requête par l'instanciation de l'evenement
4348              WHERE evenement=".$this->valF['evenement'];              $qres = $this->f->get_all_results_from_db_query(
4349              $res = $this->f->db->query($sql);                  sprintf(
4350              $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);                      'SELECT
4351              if (database::isError($res)) {                          *
4352                  die($res->getMessage());                      FROM
4353              }                          %1$sevenement
4354                        WHERE
4355                            evenement = %2$d',
4356                        DB_PREFIXE,
4357                        intval($this->valF['evenement'])
4358                    ),
4359                    array(
4360                        "origin" => __METHOD__
4361                    )
4362                );
4363              $current_id = $this->getVal($this->clePrimaire);              $current_id = $this->getVal($this->clePrimaire);
4364              while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {              foreach ($qres['result'] as $row) {
4365                  // Si la date de retour signature est éditée on vérifie si il existe un événement automatique                  // Si la date de retour signature est éditée on vérifie si il existe un événement automatique
4366                  if ($this->getVal('date_retour_signature') == "" AND                  if ($this->getVal('date_retour_signature') == "" AND
4367                      $this->valF['date_retour_signature'] != "" AND                      $this->valF['date_retour_signature'] != "" AND
# Line 3443  class instruction extends instruction_ge Line 4385  class instruction extends instruction_ge
4385                      $valNewInstr["date_retour_rar"] = $this->f->formatDate($this->valF['date_retour_rar']);                      $valNewInstr["date_retour_rar"] = $this->f->formatDate($this->valF['date_retour_rar']);
4386                      $valNewInstr["date_envoi_controle_legalite"] = $this->f->formatDate($this->valF['date_envoi_controle_legalite']);                      $valNewInstr["date_envoi_controle_legalite"] = $this->f->formatDate($this->valF['date_envoi_controle_legalite']);
4387                      $valNewInstr["date_retour_controle_legalite"] = $this->f->formatDate($this->valF['date_retour_controle_legalite']);                      $valNewInstr["date_retour_controle_legalite"] = $this->f->formatDate($this->valF['date_retour_controle_legalite']);
4388                      $new_instruction->setParameter("maj", 0);                      $new_instruction->setParameter("maj", $code_action_add);
4389                      $new_instruction->class_actions[0]["identifier"] =                      $new_instruction->class_actions[$code_action_add]["identifier"] =
4390                          "retour signature de l'instruction $current_id";                          sprintf(
4391                                __("Ajout suite au retour signature de l'instruction %s"),
4392                                $current_id
4393                            );
4394                      $retour = $new_instruction->ajouter($valNewInstr);                      $retour = $new_instruction->ajouter($valNewInstr);
4395                                            
4396                      //Si une erreur s'est produite et qu'il s'agit d'un problème                      //Si une erreur s'est produite et qu'il s'agit d'un problème
# Line 3488  class instruction extends instruction_ge Line 4433  class instruction extends instruction_ge
4433                          $valNewInstr["date_retour_rar"] = $this->f->formatDate($this->valF['date_retour_rar']);                          $valNewInstr["date_retour_rar"] = $this->f->formatDate($this->valF['date_retour_rar']);
4434                          $valNewInstr["date_envoi_controle_legalite"] = $this->f->formatDate($this->valF['date_envoi_controle_legalite']);                          $valNewInstr["date_envoi_controle_legalite"] = $this->f->formatDate($this->valF['date_envoi_controle_legalite']);
4435                          $valNewInstr["date_retour_controle_legalite"] = $this->f->formatDate($this->valF['date_retour_controle_legalite']);                          $valNewInstr["date_retour_controle_legalite"] = $this->f->formatDate($this->valF['date_retour_controle_legalite']);
4436                          $new_instruction->setParameter("maj", 0);                          $new_instruction->setParameter("maj", $code_action_add);
4437                          $new_instruction->class_actions[0]["identifier"] =                          $new_instruction->class_actions[$code_action_add]["identifier"] =
4438                              "notification de l'instruction $current_id";                              sprintf(__("Ajout suite à la notification de l'instruction %s"), $current_id);
4439                          $retour = $new_instruction->ajouter($valNewInstr);                          $retour = $new_instruction->ajouter($valNewInstr);
4440    
4441                          //Si une erreur s'est produite et qu'il s'agit d'un problème                          //Si une erreur s'est produite et qu'il s'agit d'un problème
# Line 3515  class instruction extends instruction_ge Line 4460  class instruction extends instruction_ge
4460              }              }
4461          }          }
4462    
4463          /**          // Traitement en cas de mise à jour du dossier
4464           * Mise à jour de la date de dernière modification du dossier          if ($update_dossier === true) {
4465           * d'instruction              /**
4466           */               * Mise à jour de la date de dernière modification du dossier
4467          $inst_di = $this->get_inst_dossier($this->getVal('dossier'));               * d'instruction
4468          $inst_di->update_last_modification_date();               */
4469                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
4470                $inst_di->update_last_modification_date();
4471    
4472          // Mise à jour des données du dossier d'autorisation              // Mise à jour des données du dossier d'autorisation
4473          $da = $this->f->get_inst__om_dbform(array(              $da = $this->f->get_inst__om_dbform(array(
4474              "obj" => "dossier_autorisation",                  "obj" => "dossier_autorisation",
4475              "idx" => $this->getNumDemandeAutorFromDossier($this->valF['dossier']),                  "idx" => $this->getNumDemandeAutorFromDossier($this->valF['dossier']),
4476          ));              ));
4477          $params = array(              $params = array(
4478              'di_id' => $this->getVal('dossier'),                  'di_id' => $this->getVal('dossier'),
4479          );              );
4480          if($da->majDossierAutorisation($params) === false) {              if($da->majDossierAutorisation($params) === false) {
4481              $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."));
4482              $this->correct = false;                  $this->correct = false;
4483              return false;                  return false;
4484                }
4485          }          }
4486    
4487          // mise à jour des métadonnées issues des dates de suivi          // mise à jour des métadonnées issues des dates de suivi
# Line 3545  class instruction extends instruction_ge Line 4493  class instruction extends instruction_ge
4493              $metadata = $this->getMetadata("om_fichier_instruction");              $metadata = $this->getMetadata("om_fichier_instruction");
4494    
4495              // On vérifie si l'instruction à finaliser a un événement de type arrete              // On vérifie si l'instruction à finaliser a un événement de type arrete
4496              $sql = "SELECT type FROM ".DB_PREFIXE."evenement WHERE evenement = ".$this->getVal("evenement");              // TODO : A voir pour remplacer par une instanciation de l'événement.
4497              $typeEvenement = $this->f->db->getOne($sql);              //        Voir également si l'événement ne dois pas être instancié en début de
4498              $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);              //        méthode pour pouvoir être réutilisé.
4499              if ($this->f->isDatabaseError($typeEvenement, true) === true) {              $qres = $this->f->get_one_result_from_db_query(
4500                    sprintf(
4501                        'SELECT
4502                            type
4503                        FROM
4504                            %1$sevenement
4505                        WHERE
4506                            evenement = \'%2$d\'',
4507                        DB_PREFIXE,
4508                        intval($this->getVal("evenement"))
4509                    ),
4510                    array(
4511                        "origin" => __METHOD__,
4512                        "force_return" => true,
4513                    )
4514                );
4515    
4516                if ($qres["code"] !== "OK") {
4517                  $this->correct = false;                  $this->correct = false;
4518                  $this->addToMessage(__("Erreur de traitement de fichier."));                  $this->addToMessage(__("Erreur de traitement de fichier."));
4519                  $this->addToLog(__METHOD__."() erreur BDD: ".var_export($typeEvenement->getMessage(), true), DEBUG_MODE);                  $this->addToLog(__METHOD__."() erreur BDD: ".var_export($qres['message'], true), DEBUG_MODE);
4520                  return false;                  return false;
4521              }              }
4522    
4523              // Si l'événement est de type arrete, on ajoute les métadonnées spécifiques              // Si l'événement est de type arrete, on ajoute les métadonnées spécifiques
4524              if ($typeEvenement == 'arrete'){              if ($qres['result'] == 'arrete'){
4525                  $metadata = array_merge($metadata, $this->getMetadata("arrete"));                  $metadata = array_merge($metadata, $this->getMetadata("arrete"));
4526              }              }
4527    
# Line 3604  class instruction extends instruction_ge Line 4569  class instruction extends instruction_ge
4569              }              }
4570          }          }
4571    
4572          // Notification auto des demandeurs          // Déclenchement des notifications automatique après finalisation et
4573            // retour de signature
4574          if ($dateRetourSignatureModified === true          if ($dateRetourSignatureModified === true
4575              && $this->valF['date_retour_signature'] !== ''              && $this->valF['date_retour_signature'] !== ''
4576              && $this->valF['date_retour_signature'] !== null) {              && $this->valF['date_retour_signature'] !== null) {
4577              //  
4578                // Message à afficher dans les logs pour indiquer quelle notification a échouée
4579                $msgLog = sprintf(
4580                    '%s %s : %d',
4581                    __('Erreur lors de la notification automatique du(des) pétitionnaire(s) après retour signature.'),
4582                    __('Instruction notifiée'),
4583                    $id
4584                );
4585    
4586                // Récupération de l'instance de l'événement pour accéder au paramètrage
4587                // des notifications
4588              $ev = $this->get_inst_evenement($this->valF['evenement']);              $ev = $this->get_inst_evenement($this->valF['evenement']);
4589                // Si la notification automatique des tiers consulté est active
4590                // déclenche le traitement de notification.
4591                // Ce traitement va envoyer des courriels de notification à tous les tiers concernés
4592                $typeNotifTiers = $ev->getVal('notification_tiers');
4593                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
4594                if ($typeNotifTiers === 'notification_automatique') {
4595                    if ($this->traitement_notification_automatique_tiers_consulte($ev, $inst_di) === false) {
4596                        $this->addToMessage(__('Le traitement de la notification automatique de tiers à échoué.'));
4597                        $this->correct = false;
4598                    }
4599                }
4600    
4601              if ($ev->getVal('notification') === 'notification_auto_signature_requise') {              if ($ev->getVal('notification') === 'notification_auto_signature_requise') {
4602                  // Récupération de la liste des demandeurs à notifier et de la catégorie                  // Récupération de la liste des demandeurs à notifier et de la catégorie
4603                  $categorie = $this->f->get_param_option_notification($collectivite_di);                  $categorie = $this->f->get_param_option_notification($collectivite_di);
4604                  $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;                  $isPortal = $categorie === PORTAL;
4605                  $demandeursANotifie = $this->get_demandeurs_notifiable(                  $demandeursANotifie = $this->get_demandeurs_notifiable(
4606                      $this->valF['dossier'],                      $this->valF['dossier'],
4607                      $isPortal                      $isPortal
4608                  );                  );
4609    
4610                  // Création d'une notification et d'une tâche pour chaque demandeur à notifier                  // Création d'une notification et d'une tâche pour chaque demandeur à notifier
4611                    $demandeurPrincipalNotifie = false;
4612                  foreach ($demandeursANotifie as $demandeur) {                  foreach ($demandeursANotifie as $demandeur) {
4613                        // Identifie si le demandeur principal a été notifié ou pas
4614                        // et récupère ses informations
4615                        if ($demandeur['petitionnaire_principal'] == 't') {
4616                            $demandeurPrincipalNotifie = true;
4617                            // Si le demandeur principal est notifiable mais qu'il y a des erreurs dans
4618                            // son paramétrage, on effectue pas le traitement et on passe à l'itération
4619                            // suivante. On le considère également comme non notifié pour gérer l'envoie
4620                            // des messages d'erreurs
4621                            // Si la demande a été déposée via le portail alors le paramétrage n'a pas
4622                            // d'impact sur la notification
4623                            $erreursParam = $this->get_info_notification_fail();
4624                            if (! $this->dossier_depose_sur_portail() && $erreursParam != array()) {
4625                                $demandeurPrincipalNotifie = false;
4626                                continue;
4627                            }
4628                        }
4629                      // Ajout de la notif et récupération de son id                      // Ajout de la notif et récupération de son id
4630                      $idNotif = $this->ajouter_notification(                      $idNotif = $this->ajouter_notification(
4631                          $this->valF[$this->clePrimaire],                          $this->valF[$this->clePrimaire],
4632                          $this->f->get_connected_user_login_name(),                          $this->f->get_connected_user_login_name(),
4633                          $demandeur,                          $demandeur,
4634                          $collectivite_di,                          $collectivite_di,
4635                            array(),
4636                          true                          true
4637                      );                      );
4638                      if ($idNotif === false) {                      if ($idNotif === false) {
4639                            $this->addToLog(
4640                                sprintf('%s() : %s',__METHOD__, $msgLog),
4641                                DEBUG_MODE
4642                            );
4643                          return false;                          return false;
4644                      }                      }
4645                      // Création de la tache en lui donnant l'id de la notification                      // Création de la tache en lui donnant l'id de la notification
# Line 3639  class instruction extends instruction_ge Line 4649  class instruction extends instruction_ge
4649                          $categorie                          $categorie
4650                      );                      );
4651                      if ($notification_by_task === false) {                      if ($notification_by_task === false) {
4652                            $this->addToLog(
4653                                sprintf('%s() : %s',__METHOD__, $msgLog),
4654                                DEBUG_MODE
4655                            );
4656                          $this->addToMessage(                          $this->addToMessage(
4657                              __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")                              __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
4658                          );                          );
4659                          return false;                          return false;
4660                      }                      }
4661                  }                  }
4662                    // Pour la notification par mail ou la notification via portal si le dossier a
4663                    // été déposés via portal, si le demandeur principal n'est pas notifiable,
4664                    // on créé une nouvelle notification en erreur avec en commentaire la raison pour
4665                    // laquelle le demandeur principal n'a pas pu être notifié
4666                    $depotPortal = $this->dossier_depose_sur_portail();
4667                    if (! $demandeurPrincipalNotifie && ($isPortal === false || $depotPortal === true)) {
4668                        // Précise dans les logs que le pétitionnaire principal n'a pas été notifié
4669                        $msgLog .= sprintf(' %s', __('Le pétitionnaire principale n\'est pas notifiable.'));
4670                        // Analyse pour savoir pourquoi le demandeur principal n'est pas notifiable
4671                        $erreursParam = $this->get_info_notification_fail();
4672                        $demandeurPrincipal = $this->get_info_petitionnaire_principal_dossier($this->getVal('dossier'));
4673                        // Ajout de la notif et récupération de son id
4674                        $idNotif = $this->ajouter_notification(
4675                            $this->valF[$this->clePrimaire],
4676                            $this->f->get_connected_user_login_name(),
4677                            $demandeurPrincipal,
4678                            $collectivite_di,
4679                            array(),
4680                            true,
4681                            'Echec',
4682                            implode(' ', $erreursParam)
4683                        );
4684                        if ($idNotif === false) {
4685                            $this->addToLog(
4686                                sprintf('%s() : %s', __METHOD__, $msgLog),
4687                                DEBUG_MODE
4688                            );
4689                            $this->addToMessage(
4690                                __('Erreur : la création de la notification a échouée.').
4691                                __("Veuillez contacter votre administrateur.")
4692                            );
4693                            return false;
4694                        }
4695                        // Prépare un message d'alerte à destination de l'instructeur pour l'informer
4696                        // de l'échec de la notification
4697                        $dossier_message = $this->get_inst_dossier_message(0);
4698                        $dossier_message_val = array(
4699                            'dossier' => $this->getVal('dossier'),
4700                            'type' => _('erreur expedition'),
4701                            'emetteur' => $this->f->get_connected_user_login_name(),
4702                            'login' => $_SESSION['login'],
4703                            'date_emission' => date('Y-m-d H:i:s'),
4704                            'contenu' => _('Échec lors de la notification de l\'instruction ').
4705                                $ev->getVal('libelle').
4706                                '.<br>'.
4707                                implode("\n", $erreursParam).
4708                                '<br>'.
4709                                _('Veuillez corriger ces informations avant de renvoyer la notification.')
4710                        );
4711                        $add = $dossier_message->add_notification_message($dossier_message_val, true);
4712                        // Si une erreur se produit pendant l'ajout
4713                        if ($add !== true) {
4714                            $this->addToLog(
4715                                sprintf(
4716                                    '%s() : %s',
4717                                    __METHOD__,
4718                                    __("Le message d'alerte concernant l'echec de l'envoi de la notification n'a pas pu être envoyé.")
4719                                ),
4720                                DEBUG_MODE
4721                            );
4722                            return false;
4723                        }
4724                    }
4725                  $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.")));                  $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.")));
4726              }              }
4727          }          }
# Line 3673  class instruction extends instruction_ge Line 4750  class instruction extends instruction_ge
4750                  // est différente                  // est différente
4751                  if ($inst_di->getVal($champ) !== $val[sprintf('archive_%s', $champ)]) {                  if ($inst_di->getVal($champ) !== $val[sprintf('archive_%s', $champ)]) {
4752                      $val[sprintf('archive_%s', $champ)] === '' ? $valF[$champ] = null : $valF[$champ] = $val[sprintf('archive_%s', $champ)];                      $val[sprintf('archive_%s', $champ)] === '' ? $valF[$champ] = null : $valF[$champ] = $val[sprintf('archive_%s', $champ)];
4753                        // Gestion du cas particulier 'accord_tacite' pour renvoyer la valeur '   ' (3 espaces vides) au lieu de null
4754                        // Car les valeurs possibles du champ accord_tacite sont : 'Oui', 'Non' ou '   '
4755                        if ($champ === "accord_tacite" && $valF[$champ] === null) {
4756                            $valF[$champ] = '   ';
4757                        }
4758                  }                  }
4759              }              }
4760          }          }
# Line 3739  class instruction extends instruction_ge Line 4821  class instruction extends instruction_ge
4821              }              }
4822          }          }
4823          // On supprime toutes les notications liées à l'instruction          // On supprime toutes les notications liées à l'instruction
4824          $notifASupprimer = $this->get_instruction_notification($this->getVal($this->clePrimaire));          $notifASupprimer = $this->get_instruction_notification(
4825                $this->getVal($this->clePrimaire),
4826                array(
4827                    'notification_recepisse',
4828                    'notification_instruction',
4829                    'notification_decision',
4830                    'notification_service_consulte',
4831                    'notification_tiers_consulte',
4832                    'notification_depot_demat',
4833                    'notification_commune',
4834                    'notification_signataire'
4835                ),
4836                true
4837            );
4838                
4839          foreach ($notifASupprimer as $idNotif) {          foreach ($notifASupprimer as $idNotif) {
4840              $inst_notif = $this->f->get_inst__om_dbform(array(              $inst_notif = $this->f->get_inst__om_dbform(array(
4841                  "obj" => "instruction_notification",                  "obj" => "instruction_notification",
# Line 3903  class instruction extends instruction_ge Line 4999  class instruction extends instruction_ge
4999      }      }
5000    
5001      /**      /**
5002         * Surcharge de la méthode verifier() de la classe om_dbform pour y ajouter
5003         * les vérifications suivantes :
5004         *   - Si l'instruction à un événement associé et que cet événement à des restrictions :
5005         *       1. vérifie si la restriction est valide, si ce n'est pas le cas récupère et affiche
5006         *          le message d'erreur associé à la restriction
5007         *       2. vérifie si les restrictions sont respectées. Si ce n'est pas le cas bloque l'ajout
5008         *          et / ou la modification et affiche un message d'erreur
5009         *   -
5010         *   -
5011         *   -
5012         *   -
5013         *   -
5014         *   -
5015         *
5016         * @param array val : tableau contenant les valeurs issues du formulaire.
5017         * @param - dnu1 : Paramètre déprécié et non utilisé.
5018         * @param - dnu2 : Paramètre déprécié et non utilisé.
5019         *
5020       * @return void       * @return void
5021       */       */
5022      function verifier($val = array(), &$dnu1 = null, $dnu2 = null) {      function verifier($val = array(), &$dnu1 = null, $dnu2 = null) {
# Line 3914  class instruction extends instruction_ge Line 5028  class instruction extends instruction_ge
5028              //Test qu'une restriction est présente              //Test qu'une restriction est présente
5029              if ($restriction != "" ){              if ($restriction != "" ){
5030                                    
5031                  //Test si la restriction est valide                  // Vérifie le contexte de la modification et test si la restriction est valide.
5032                    // Si l'instruction est modifiée par une tache le dossier n'est pas impacté.
5033                    // Il n'est donc pas nécessaire de vérifier les restrictions.
5034                  $this->restriction_valid = $this->restrictionIsValid($restriction);                  $this->restriction_valid = $this->restrictionIsValid($restriction);
5035                  if ( !$this->restriction_valid ){                  if ($this->getParameter("maj") != 176
5036                        && !$this->restriction_valid) {
5037    
5038                      // Affichage du message si la restriction s'applique                      // Affichage du message si la restriction s'applique
5039                      $this->addToMessage(                      $this->addToMessage(
# Line 3984  class instruction extends instruction_ge Line 5101  class instruction extends instruction_ge
5101          }          }
5102    
5103      }      }
5104    
5105        /**
5106         * Récupère et stocket dans un tableau toutes les infos du pétitionnaire
5107         * principal du dossier auquel appartiens l'instruction.
5108         * Renvoie un tableau contenant les informations du pétitionnaire principal.
5109         *
5110         * Si l'identifiant de l'instruction n'a pas pu etre récupéré renvoie false
5111         * et affiche un message dans les logs.
5112         * En cas d'erreur de base de donnée renvoie false et affiche un message d'erreur.
5113         *
5114         * @param string identifiant du dossier
5115         * @return array|boolean
5116         */
5117        protected function get_info_petitionnaire_principal_dossier($dossier = null) {
5118            // Si l'identifiant de l'instruction n'a pas été fournit on récupère celui de
5119            // l'objet courant
5120            if (empty($dossier)) {
5121                $dossier = $this->getVal('dossier');
5122                // Si la récupération de l'identifiant de l'instruction a échoué la méthode renvoie
5123                // false et on affiche un message d'erreur dans les logs
5124                if (empty($dossier)) {
5125                    $this->addToLog(__METHOD__.' : L\'identifiant du dossier n\'a pas pu être récupéré');
5126                    return false;
5127                }
5128            }
5129    
5130            // Requête sql servant à récupérer toutes les informations relatives au demandeurs
5131            // principal
5132            $qres = $this->f->get_all_results_from_db_query(
5133                sprintf(
5134                    'SELECT
5135                        -- Récupère toutes les informations du demandeur principal
5136                        demandeur.*,
5137                        CASE
5138                            WHEN demandeur.qualite=\'particulier\'
5139                            THEN TRIM(CONCAT(demandeur.particulier_nom, \' \', demandeur.particulier_prenom, \' \', demandeur.courriel))
5140                        ELSE
5141                            TRIM(CONCAT(demandeur.personne_morale_raison_sociale, \' \', demandeur.personne_morale_denomination, \' \', demandeur.courriel))
5142                        END AS destinataire
5143                    FROM
5144                        %1$sdossier
5145                        LEFT JOIN %1$slien_dossier_demandeur
5146                            ON lien_dossier_demandeur.dossier = dossier.dossier
5147                        LEFT JOIN %1$sdemandeur
5148                            ON demandeur.demandeur = lien_dossier_demandeur.demandeur
5149                    WHERE
5150                        dossier.dossier = \'%2$s\'
5151                        AND lien_dossier_demandeur.petitionnaire_principal IS TRUE',
5152                    DB_PREFIXE,
5153                    $this->f->db->escapeSimple($dossier)
5154                ),
5155                array(
5156                    "origin" => __METHOD__,
5157                )
5158            );
5159            if (is_array($qres["result"]) === true
5160                && array_key_exists(0, $qres["result"]) === true) {
5161                //
5162                return $qres["result"][0];
5163            }
5164            return null;
5165        }
5166    
5167    
5168            
5169      /**      /**
5170       * Finalisation des documents.       * Finalisation des documents.
# Line 4047  class instruction extends instruction_ge Line 5228  class instruction extends instruction_ge
5228              $spe_metadata = $this->getMetadata("om_fichier_instruction");              $spe_metadata = $this->getMetadata("om_fichier_instruction");
5229    
5230              //On vérifie si l'instruction à finaliser a un événement de type arrete              //On vérifie si l'instruction à finaliser a un événement de type arrete
5231              $sql = "SELECT type              // TODO : A voir pour remplacer par une instanciation de l'événement.
5232                  FROM ".DB_PREFIXE."evenement              //        Voir également si l'événement ne dois pas être instancié en début de
5233                  WHERE evenement = ".$this->getVal("evenement");              //        méthode pour pouvoir être réutilisé.
5234              $typeEvenement = $this->f->db->getOne($sql);              $qres = $this->f->get_one_result_from_db_query(
5235              $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);                  sprintf(
5236              if ($this->f->isDatabaseError($typeEvenement, true) === true) {                      'SELECT
5237                            type
5238                        FROM
5239                            %1$sevenement
5240                        WHERE
5241                            evenement = \'%2$d\'',
5242                        DB_PREFIXE,
5243                        intval($this->getVal("evenement"))
5244                    ),
5245                    array(
5246                        "origin" => __METHOD__,
5247                        "force_return" => true,
5248                    )
5249                );
5250    
5251                if ($qres["code"] !== "OK") {
5252                  $this->correct = false;                  $this->correct = false;
5253                  $this->addToMessage($bdd_msg_error);                  $this->addToMessage($bdd_msg_error);
5254                  return $this->end_treatment(__METHOD__, false);                  return $this->end_treatment(__METHOD__, false);
# Line 4061  class instruction extends instruction_ge Line 5257  class instruction extends instruction_ge
5257              //Initialisation de la variable              //Initialisation de la variable
5258              $arrete_metadata = array();              $arrete_metadata = array();
5259              // Si l'événement est de type arrete, on ajoute les métadonnées spécifiques              // Si l'événement est de type arrete, on ajoute les métadonnées spécifiques
5260              if ( $typeEvenement === 'arrete' ){              if ($qres['result'] === 'arrete'){
5261                  $arrete_metadata = $this->getMetadata("arrete");                  $arrete_metadata = $this->getMetadata("arrete");
5262              }              }
5263    
# Line 4299  class instruction extends instruction_ge Line 5495  class instruction extends instruction_ge
5495          }          }
5496    
5497          // Requête sql          // Requête sql
5498          $sql = "SELECT libelle FROM ".DB_PREFIXE."evenement          $evenement = $this->f->get_inst__om_dbform(array(
5499                  WHERE evenement=".$evenement;              "obj" => "evenement",
5500          $evenement_libelle = $this->f->db->getOne($sql);              "idx" => $evenement
5501          $this->addToLog("getTitle(): db->getOne(\"".$sql."\");", VERBOSE_MODE);          ));
         if (database::isError($evenement_libelle)) {  
             die();  
         }  
5502    
5503          // Retourne le libelle de l'événement          // Retourne le libelle de l'événement
5504          return $evenement_libelle;          return $evenement->getVal('libelle');
5505      }      }
5506    
5507    
# Line 4338  class instruction extends instruction_ge Line 5531  class instruction extends instruction_ge
5531              $dossier = $this->getVal("dossier");              $dossier = $this->getVal("dossier");
5532          }          }
5533          //Requête pour récupérer les informations essentiels sur le dossier d'instruction          //Requête pour récupérer les informations essentiels sur le dossier d'instruction
5534          $sql = "SELECT dossier.dossier as dossier,          $qres = $this->f->get_all_results_from_db_query(
5535                          dossier_autorisation.dossier_autorisation as dossier_autorisation,              sprintf(
5536                          to_char(dossier.date_demande, 'YYYY/MM') as date_demande_initiale,                  'SELECT
5537                          dossier_instruction_type.code as dossier_instruction_type,                      dossier.dossier AS dossier,
5538                          etat_dossier_autorisation.libelle as statut,                      dossier_autorisation.dossier_autorisation AS dossier_autorisation,
5539                          dossier_autorisation_type.code as dossier_autorisation_type,                      to_char(dossier.date_demande, \'YYYY/MM\') AS date_demande_initiale,
5540                          groupe.code as groupe_instruction,                      dossier_instruction_type.code AS dossier_instruction_type,
5541                          CASE WHEN dossier.erp IS TRUE                      etat_dossier_autorisation.libelle AS statut,
5542                              THEN 'true'                      dossier_autorisation_type.code AS dossier_autorisation_type,
5543                              ELSE 'false'                      groupe.code AS groupe_instruction,
5544                          END as erp                      CASE WHEN dossier.erp IS TRUE
5545                  FROM ".DB_PREFIXE."dossier                          THEN \'true\'
5546                      LEFT JOIN ".DB_PREFIXE."dossier_instruction_type                            ELSE \'false\'
5547                        END AS erp
5548                    FROM
5549                        %1$sdossier
5550                        LEFT JOIN %1$sdossier_instruction_type  
5551                          ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type                          ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
5552                      LEFT JOIN ".DB_PREFIXE."dossier_autorisation                      LEFT JOIN %1$sdossier_autorisation
5553                          ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation                          ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation
5554                      LEFT JOIN ".DB_PREFIXE."etat_dossier_autorisation                      LEFT JOIN %1$setat_dossier_autorisation
5555                          ON  dossier_autorisation.etat_dossier_autorisation = etat_dossier_autorisation.etat_dossier_autorisation                          ON  dossier_autorisation.etat_dossier_autorisation = etat_dossier_autorisation.etat_dossier_autorisation
5556                      LEFT JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille                      LEFT JOIN %1$sdossier_autorisation_type_detaille
5557                          ON dossier_autorisation.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille                          ON dossier_autorisation.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
5558                      LEFT JOIN ".DB_PREFIXE."dossier_autorisation_type                      LEFT JOIN %1$sdossier_autorisation_type
5559                          ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type                          ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
5560                      LEFT JOIN ".DB_PREFIXE."groupe                      LEFT JOIN %1$sgroupe
5561                          ON dossier_autorisation_type.groupe = groupe.groupe                          ON dossier_autorisation_type.groupe = groupe.groupe
5562                  WHERE dossier.dossier = '".$dossier."'";                  WHERE
5563          $res = $this->f->db->query($sql);                      dossier.dossier = \'%2$s\'',
5564          $this->f->addToLog("getSpecificMetadata() : db->query(".$sql.")", VERBOSE_MODE);                  DB_PREFIXE,
5565          if ( database::isError($res)){                  $this->f->db->escapeSimple($dossier)
5566              die();              ),
5567          }              array(
5568                            "origin" => __METHOD__,
5569          //Le résultat est récupéré dans un objet              )
5570          $row =& $res->fetchRow(DB_FETCHMODE_OBJECT);          );
5571            $row = array_shift($qres['result']);
5572    
5573          //Si il y a un résultat          //Si il y a un résultat
5574          if ($row !== null) {          if (! empty($row)) {
5575    
5576              // Instrance de la classe dossier              // Instrance de la classe dossier
5577              $inst_dossier = $this->get_inst_dossier($dossier);              $inst_dossier = $this->get_inst_dossier($dossier);
5578                // TODO : améliorer ce code
5579                //
5580                // Avant l e résultat été récupéré dans un objet à partir de la requête mais en modifiant pour
5581                // utiliser la méthode get_all_results_from_db_query() c'est maintenant un tableau
5582                // qu'on obtiens. Pour garder le même fonctionnement on transforme le tableau des
5583                // valeurs issues de la requête en objet.
5584                $metadata = (object)$row;
5585              // Insère l'attribut version à l'objet              // Insère l'attribut version à l'objet
5586              $row->version = $inst_dossier->get_dossier_instruction_version();              $metadata->version = $inst_dossier->get_di_numero_suffixe();
5587    
5588              //Alors on créé l'objet dossier_instruction              //Alors on créé l'objet dossier_instruction
5589              $this->specificMetadata = $row;              $this->specificMetadata = $metadata;
5590    
5591          }          }
5592      }      }
# Line 4401  class instruction extends instruction_ge Line 5605  class instruction extends instruction_ge
5605                            
5606              //On récupère le statut de l'état du dossier à partir de l'identifiant du              //On récupère le statut de l'état du dossier à partir de l'identifiant du
5607              //dossier              //dossier
5608              $sql = "SELECT etat.statut              $qres = $this->f->get_one_result_from_db_query(
5609                  FROM ".DB_PREFIXE."dossier                  sprintf(
5610                  LEFT JOIN                      'SELECT
5611                      ".DB_PREFIXE."etat                          etat.statut
5612                      ON                      FROM
5613                          dossier.etat = etat.etat                          %1$sdossier
5614                  WHERE dossier ='".$idx."'";                          LEFT JOIN
5615              $statut = $this->f->db->getOne($sql);                              %1$setat
5616              $this->f->addToLog("getStatutAutorisationDossier() : db->getOne(\"".$sql."\")", VERBOSE_MODE);                              ON
5617              if ( database::isError($statut)){                                  dossier.etat = etat.etat
5618                  die();                      WHERE
5619              }                          dossier = \'%2$s\'',
5620                        DB_PREFIXE,
5621                        $this->f->db->escapeSimple($idx)
5622                    ),
5623                    array(
5624                        "origin" => __METHOD__,
5625                    )
5626                );
5627          }          }
5628          return $statut;  
5629            return $qres['result'];
5630      }      }
5631    
5632      /**      /**
# Line 4427  class instruction extends instruction_ge Line 5639  class instruction extends instruction_ge
5639          $return = array();          $return = array();
5640    
5641          // 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
5642          $sql = "SELECT * FROM ".DB_PREFIXE."dossier          // TODO : remplacer cette requête par une instanciation de l'objet
5643          WHERE dossier='".$this->valF['dossier']."'";          $qres = $this->f->get_all_results_from_db_query(
5644          $res = $this->f->db->query($sql);              sprintf(
5645          $this->addToLog("get_dossier_actual(): db->query(\"".$sql."\");", VERBOSE_MODE);                  'SELECT
5646          $this->f->isDatabaseError($res);                      *
5647                    FROM
5648                        %1$sdossier
5649                    WHERE
5650                        dossier = \'%2$s\'',
5651                    DB_PREFIXE,
5652                    $this->f->db->escapeSimple($this->valF['dossier'])
5653                ),
5654                array(
5655                    'origin' => __METHOD__
5656                )
5657            );
5658    
5659          //          foreach ($qres['result'] as $row) {
         while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {  
5660    
5661              // Récupération de la valeur actuelle du délai, de l'accord tacite,              // Récupération de la valeur actuelle du délai, de l'accord tacite,
5662              // de l'état et de l'avis du dossier d'instruction              // de l'état et de l'avis du dossier d'instruction
# Line 4489  class instruction extends instruction_ge Line 5711  class instruction extends instruction_ge
5711       * @return boolean                 * @return boolean          
5712       */       */
5713      function checkEvenementNonVerrouillable($idx) {      function checkEvenementNonVerrouillable($idx) {
   
         // Initialisation du résultat  
         $non_verrouillable = false;  
   
5714          // Si la condition n'est pas vide          // Si la condition n'est pas vide
5715          if ($idx != "") {          if ($idx != "") {
5716    
5717              // Requête SQL              // Requête SQL
5718              $sql = "SELECT evenement.non_verrouillable              $qres = $this->f->get_one_result_from_db_query(
5719                      FROM ".DB_PREFIXE."evenement                  sprintf(
5720                      LEFT JOIN ".DB_PREFIXE."instruction                      'SELECT
5721                          ON instruction.evenement = evenement.evenement                          evenement.non_verrouillable
5722                      WHERE instruction.instruction = $idx";                      FROM
5723              $this->f->addToLog("checkEvenementNonVerrouillable() : db->getOne(\"".$sql."\")", VERBOSE_MODE);                          %1$sevenement
5724              $res = $this->f->db->getOne($sql);                          LEFT JOIN %1$sinstruction
5725              $this->f->isDatabaseError($res);                              ON instruction.evenement = evenement.evenement
5726                        WHERE
5727              // Si le retour de la requête est true                          instruction.instruction = \'%2$s\'',
5728              if ($res == 't') {                      DB_PREFIXE,
5729                  //                      intval($idx)
5730                  $non_verrouillable = true;                  ),
5731              }                  array(
5732                        "origin" => __METHOD__,
5733                    )
5734                );
5735          }          }
5736    
5737          // Retourne résultat          // Si on a un résultat et que ce résultat indique que l'événement n'est
5738          return $non_verrouillable;          // pas vérrouillable renvoie true, sinon renvoie false
5739            return isset($qres) && isset($qres['result']) && $qres['result'] == 't';
5740      }      }
5741            
5742      /**      /**
# Line 4754  class instruction extends instruction_ge Line 5976  class instruction extends instruction_ge
5976       */       */
5977      function getArreteMetadata() {      function getArreteMetadata() {
5978    
5979      //Récupération de la dernière instruction dont l'événement est de type 'arrete'          //Récupération de la dernière instruction dont l'événement est de type 'arrete'
5980      $this->metadonneesArrete = array("nomsignataire"=>"", "qualitesignataire"=>"",          $this->metadonneesArrete = array("nomsignataire"=>"", "qualitesignataire"=>"",
5981          "decisionarrete"=>"", "datenotification"=>"", "datesignaturearrete"=>"",              "decisionarrete"=>"", "datenotification"=>"", "datesignaturearrete"=>"",
5982          "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",              "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",
5983          "ap_codepostal"=>"", "ap_ville"=>"");              "ap_codepostal"=>"", "ap_ville"=>"");
5984    
5985          $sqlArrete = "SELECT          $qres = $this->f->get_all_results_from_db_query(
5986                  signataire_arrete.prenom || ' ' ||signataire_arrete.nom as \"nomsignataire\",              sprintf(
5987                  signataire_arrete.qualite as \"qualitesignataire\",                  'SELECT
5988                  instruction.etat as \"decisionarrete\",                      signataire_arrete.prenom || \' \' ||signataire_arrete.nom as nomsignataire,
5989                  instruction.date_retour_rar as \"datenotification\",                      signataire_arrete.qualite as qualitesignataire,
5990                  instruction.date_retour_signature as \"datesignaturearrete\",                      instruction.etat as decisionarrete,
5991                  instruction.date_retour_controle_legalite as \"datecontrolelegalite\",                      instruction.date_retour_rar as datenotification,
5992                  dossier.terrain_adresse_voie_numero as \"ap_numrue\",                      instruction.date_retour_signature as datesignaturearrete,
5993                  dossier.terrain_adresse_voie as \"ap_nomdelavoie\",                      instruction.date_retour_controle_legalite as datecontrolelegalite,
5994                  dossier.terrain_adresse_code_postal as \"ap_codepostal\",                      dossier.terrain_adresse_voie_numero as ap_numrue,
5995                  dossier.terrain_adresse_localite as \"ap_ville\"                      dossier.terrain_adresse_voie as ap_nomdelavoie,
5996              FROM ".DB_PREFIXE."instruction                      dossier.terrain_adresse_code_postal as ap_codepostal,
5997              LEFT JOIN ".DB_PREFIXE."signataire_arrete ON                      dossier.terrain_adresse_localite as ap_ville
5998                  instruction.signataire_arrete = signataire_arrete.signataire_arrete                  FROM
5999              LEFT JOIN ".DB_PREFIXE."dossier ON                      %1$sinstruction
6000                  instruction.dossier = dossier.dossier                      LEFT JOIN %1$ssignataire_arrete
6001              LEFT JOIN ".DB_PREFIXE."donnees_techniques ON                          ON instruction.signataire_arrete = signataire_arrete.signataire_arrete
6002                      donnees_techniques.dossier_instruction = dossier.dossier                      LEFT JOIN %1$sdossier
6003              WHERE instruction.instruction = ".$this->getVal("instruction");                          ON instruction.dossier = dossier.dossier
6004          $resArrete = $this->f->db->query($sqlArrete);                      LEFT JOIN %1$sdonnees_techniques
6005          $this->f->addToLog("getArreteMetadata(): db->query(\"".$sqlArrete."\");", VERBOSE_MODE);                          ON donnees_techniques.dossier_instruction = dossier.dossier
6006          if ( database::isError($resArrete)){                  WHERE
6007              die();                      instruction.instruction = %2$d',
6008          }                  DB_PREFIXE,
6009                    intval($this->getVal('instruction'))
6010          $this->metadonneesArrete = $resArrete->fetchRow(DB_FETCHMODE_ASSOC);              ),
6011                array(
6012                    'origin' => __METHOD__
6013                )
6014            );
6015            $this->metadonneesArrete = array_shift($qres['result']);
6016      }      }
6017    
6018      /**      /**
# Line 5132  class instruction extends instruction_ge Line 6359  class instruction extends instruction_ge
6359                    
6360    
6361          // Sinon on vérifie l'éligibilité du dossier au changement de décision          // Sinon on vérifie l'éligibilité du dossier au changement de décision
6362          $sql =          // /!\ Requête lié à celles du widget indiquant les dossiers éligible au changement
6363              "SELECT          // de décision :
6364            //   * dossier_instruction.class.php : view_widget_dossiers_evenement_retour_finalise()
6365            //   * dossier_instruction.inc.php : si le paramètre filtre_decision = true
6366            $sql = sprintf(
6367                'SELECT
6368                  dossier.dossier                  dossier.dossier
6369              FROM              FROM
6370                  ".DB_PREFIXE."dossier                  %1$sdossier
6371              JOIN ".DB_PREFIXE."instruction ON instruction.instruction = (                  JOIN %1$setat
6372                  SELECT instruction                      ON dossier.etat = etat.etat AND etat.statut = \'encours\'
6373                  FROM ".DB_PREFIXE."instruction                  JOIN %1$slien_dossier_demandeur
6374                  JOIN ".DB_PREFIXE."evenement on instruction.evenement=evenement.evenement                      ON dossier.dossier = lien_dossier_demandeur.dossier AND lien_dossier_demandeur.petitionnaire_principal IS TRUE
6375                  WHERE instruction.dossier = dossier.dossier                  JOIN %1$sdossier_instruction_type
6376                  AND evenement.retour IS FALSE                      ON dossier.dossier_instruction_type=dossier_instruction_type.dossier_instruction_type
6377                  ORDER BY date_evenement DESC, instruction DESC                  JOIN %1$sinstruction
6378                  LIMIT 1                      -- Recherche de la dernière instruction qui ne soit pas liée à un événement retour
6379              )                      ON instruction.instruction = (
6380              JOIN ".DB_PREFIXE."evenement ON instruction.evenement=evenement.evenement                              SELECT instruction
6381              JOIN ".DB_PREFIXE."instructeur ON dossier.instructeur=instructeur.instructeur                              FROM %1$sinstruction
6382              JOIN ".DB_PREFIXE."om_utilisateur ON instructeur.om_utilisateur=om_utilisateur.om_utilisateur                              JOIN %1$sevenement ON instruction.evenement=evenement.evenement
6383              JOIN ".DB_PREFIXE."om_collectivite ON om_collectivite.om_collectivite=om_utilisateur.om_collectivite                              AND evenement.retour IS FALSE
6384              JOIN ".DB_PREFIXE."etat ON dossier.etat = etat.etat                              WHERE instruction.dossier = dossier.dossier
6385                                ORDER BY date_evenement DESC, instruction DESC
6386                                LIMIT 1
6387                            )
6388                            -- On ne garde que les dossiers pour lesquels la dernière instruction est finalisée
6389                            -- ou alors pour laquelle l instruction a été ajouté par la commune et est
6390                            -- non signée, non notifié, etc.
6391                            AND (instruction.om_final_instruction IS TRUE
6392                                OR instruction.created_by_commune IS TRUE)
6393                            AND instruction.date_retour_signature IS NULL
6394                            AND instruction.date_envoi_rar IS NULL
6395                            AND instruction.date_retour_rar IS NULL
6396                            AND instruction.date_envoi_controle_legalite IS NULL
6397                            AND instruction.date_retour_controle_legalite IS NULL
6398                    -- On vérifie que l instruction soit un arrêté ou un changement de décision
6399                    JOIN %1$sevenement
6400                        ON instruction.evenement=evenement.evenement
6401                            AND (evenement.type = \'arrete\'
6402                                OR evenement.type = \'changement_decision\')
6403                    -- Recherche les informations du pétitionnaire principal pour l affichage
6404                    JOIN %1$sdemandeur
6405                        ON lien_dossier_demandeur.demandeur = demandeur.demandeur
6406                    -- Recherche la collectivité rattachée à l instructeur
6407                    JOIN %1$sinstructeur
6408                        ON dossier.instructeur=instructeur.instructeur
6409                    JOIN %1$sdivision
6410                        ON instructeur.division=division.division
6411                    JOIN %1$sdirection
6412                        ON division.direction=direction.direction
6413                    JOIN %1$som_collectivite
6414                        ON direction.om_collectivite=om_collectivite.om_collectivite
6415              WHERE              WHERE
6416                                    -- Vérification que la décision a été prise par l agglo
6417                      (                  om_collectivite.niveau = \'2\'
6418                          evenement.type = 'arrete' AND                  AND dossier.dossier = \'%2$s\'
6419                          (              ',
6420                              instruction.om_final_instruction IS TRUE              DB_PREFIXE,
6421                              OR instruction.created_by_commune IS TRUE              $this->f->db->escapeSimple($idx)
6422                          ) OR          );
                         evenement.type = 'changement_decision'  
                     )  
                 AND evenement.retour IS FALSE  
                 AND instruction.date_retour_signature IS NULL  
                 AND instruction.date_envoi_rar IS NULL  
                 AND instruction.date_retour_rar IS NULL  
                 AND instruction.date_envoi_controle_legalite IS NULL  
                 AND instruction.date_retour_controle_legalite IS NULL  
                 AND etat.statut = 'encours'  
                 AND dossier.dossier = '".$idx."'  
                 AND om_collectivite.niveau = '2'  
             ";  
6423    
6424    
6425          // Si collectivité de l'utilisateur niveau mono alors filtre sur celle-ci          // Si collectivité de l'utilisateur niveau mono alors filtre sur celle-ci
6426          if ($this->f->isCollectiviteMono($_SESSION['collectivite']) === true) {          if ($this->f->isCollectiviteMono($_SESSION['collectivite']) === true) {
6427              $sql .= " AND dossier.om_collectivite=".$_SESSION['collectivite'];              $sql .= sprintf(
6428          }                  ' AND dossier.om_collectivite = %1$d',
6429          $res = $this->f->db->getone($sql);                  intval($_SESSION['collectivite'])
6430          if (database::isError($res)) {              );
             die();  
         }  
         // Si le dossier n'est pas sujet au changement de decision  
         if($res == null) {  
             return false;  
6431          }          }
6432          return true;          $qres = $this->f->get_one_result_from_db_query(
6433                $sql,
6434                array(
6435                    "origin" => __METHOD__,
6436                )
6437            );
6438    
6439            return $qres['result'] !== null;
6440      }      }
6441    
6442    
# Line 5270  class instruction extends instruction_ge Line 6521  class instruction extends instruction_ge
6521    
6522    
6523      /**      /**
6524         * CONDITION - is_finalized.
6525         *
6526         * Condition pour vérifier si une instruction est finalisée.
6527         *
6528         * @return boolean
6529         */
6530        public function is_finalized() {
6531    
6532            return $this->getVal('om_final_instruction') === "t";
6533        }
6534    
6535        /**
6536         * CONDITION - is_not_date_retour_signature_set.
6537         *
6538         * Condition pour vérifier si une date de retour signature n'est pas définie.
6539         *
6540         * @return boolean
6541         */
6542        public function is_not_date_retour_signature_set() {
6543    
6544            return $this->getVal('date_retour_signature') == null;
6545    
6546        }
6547    
6548    
6549        /**
6550       * TREATMENT - finalize.       * TREATMENT - finalize.
6551       *       *
6552       * Permet de finaliser un enregistrement.       * Permet de finaliser un enregistrement.
# Line 5284  class instruction extends instruction_ge Line 6561  class instruction extends instruction_ge
6561          // dites de TREATMENT.          // dites de TREATMENT.
6562          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
6563          $message = '';          $message = '';
6564            $ev = $this->get_inst_evenement($this->getVal('evenement'));
6565    
6566            // Controle du signataire
6567            if (! $this->controle_signataire($ev)) {
6568                $this->addToMessage(__("Le document ne peut pas être finalisé car aucun signataire n'a été sélectionné."));
6569                // Termine le traitement
6570                return $this->end_treatment(__METHOD__, false);
6571            }
6572    
6573          // Traitement de la finalisation          // Traitement de la finalisation
6574          $ret = $this->manage_finalizing("finalize", $val);          $ret = $this->manage_finalizing("finalize", $val);
# Line 5297  class instruction extends instruction_ge Line 6582  class instruction extends instruction_ge
6582    
6583          // Envoi des notifications aux demandeurs si la notification est automatique          // Envoi des notifications aux demandeurs si la notification est automatique
6584          // et que la signature n'est pas requise          // et que la signature n'est pas requise
         $ev = $this->get_inst_evenement($this->getVal('evenement'));  
6585          if ($ev->getVal('notification') === 'notification_automatique') {          if ($ev->getVal('notification') === 'notification_automatique') {
6586                // Préparation du message de log en cas d'erreur de notification
6587                $msgLog = sprintf(
6588                    '%s %s : %d',
6589                    __('Erreur lors de la notification automatique du(des) pétitionnaire(s) suite à la finalisation de l\'instruction.'),
6590                    __('Instruction notifiée'),
6591                    $this->getVal($this->clePrimaire)
6592                );
6593              // Récupération de la catégorie et envoie des notifications au(x) demandeur(s)              // Récupération de la catégorie et envoie des notifications au(x) demandeur(s)
6594              $collectivite_di = $this->get_dossier_instruction_om_collectivite($this->getVal('dossier'));              $collectivite_di = $this->get_dossier_instruction_om_collectivite($this->getVal('dossier'));
6595              // Récupération de la liste des demandeurs à notifier et de la catégorie              // Récupération de la liste des demandeurs à notifier et de la catégorie
6596              $categorie = $this->f->get_param_option_notification($collectivite_di);              $categorie = $this->f->get_param_option_notification($collectivite_di);
6597              $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;              $isPortal = $categorie === PORTAL;
6598              $demandeursANotifie = $this->get_demandeurs_notifiable(              $demandeursANotifie = $this->get_demandeurs_notifiable(
6599                  $this->getVal('dossier'),                  $this->getVal('dossier'),
6600                  $isPortal                  $isPortal
6601              );              );
6602    
6603              // Création d'une notification et d'une tâche pour chaque demandeur à notifier              // Création d'une notification et d'une tâche pour chaque demandeur à notifier
6604                $demandeurPrincipalNotifie = false;
6605              if (count($demandeursANotifie) > 0) {              if (count($demandeursANotifie) > 0) {
6606                  foreach ($demandeursANotifie as $demandeur) {                  foreach ($demandeursANotifie as $demandeur) {
6607                        // Identifie si le demandeur principal a été notifié ou pas
6608                        // et récupère ses informations
6609                        if ($demandeur['petitionnaire_principal'] == 't') {
6610                            $demandeurPrincipalNotifie = true;
6611                            // Si le demandeur principal est notifiable mais qu'il y a des erreurs dans
6612                            // son paramétrage, on effectue pas le traitement et on passe à l'itération
6613                            // suivante. On le considère également comme non notifié pour gérer l'envoie
6614                            // des messages d'erreurs
6615                            // Si la demande a été déposée via le portail alors le paramétrage n'a pas
6616                            // d'impact sur la notification
6617                            $erreursParam = $this->get_info_notification_fail();
6618                            if (! $this->dossier_depose_sur_portail() && $erreursParam != array()) {
6619                                $demandeurPrincipalNotifie = false;
6620                                continue;
6621                            }
6622                        }
6623                      // Ajout de la notif et récupération de son id                      // Ajout de la notif et récupération de son id
6624                      $idNotif = $this->ajouter_notification(                      $idNotif = $this->ajouter_notification(
6625                          $this->getVal($this->clePrimaire),                          $this->getVal($this->clePrimaire),
6626                          $this->f->get_connected_user_login_name(),                          $this->f->get_connected_user_login_name(),
6627                          $demandeur,                          $demandeur,
6628                          $collectivite_di,                          $collectivite_di,
6629                            array(),
6630                          true                          true
6631                      );                      );
6632                      if ($idNotif === false) {                      if ($idNotif === false) {
6633                          // Termine le traitement                          // Termine le traitement
6634                            $this->addToLog(
6635                                sprintf('%s() : %s', __METHOD__, $msgLog),
6636                                DEBUG_MODE
6637                            );
6638                          return $this->end_treatment(__METHOD__, false);                          return $this->end_treatment(__METHOD__, false);
6639                      }                      }
6640                      $notification_by_task = $this->notification_by_task(                      $notification_by_task = $this->notification_by_task(
# Line 5330  class instruction extends instruction_ge Line 6643  class instruction extends instruction_ge
6643                          $categorie                          $categorie
6644                      );                      );
6645                      if ($notification_by_task === false) {                      if ($notification_by_task === false) {
6646                            $this->addToLog(
6647                                sprintf('%s() : %s', __METHOD__, $msgLog),
6648                                DEBUG_MODE
6649                            );
6650                          $this->addToMessage(                          $this->addToMessage(
6651                              __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")                              __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
6652                          );                          );
6653                          // Termine le traitement                          // Termine le traitement
6654                          return $this->end_treatment(__METHOD__, false);                          return $this->end_treatment(__METHOD__, false);
6655                      }                      }
6656                        $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.")));
6657                    }
6658                }
6659                // Pour la notification par mail ou la notification via portal si le dossier a
6660                // été déposés via portal, si le demandeur principal n'est pas notifiable,
6661                // on créé une nouvelle notification en erreur avec en commentaire la raison pour
6662                // laquelle le demandeur principal n'a pas pu être notifié
6663                $depotPortal = $this->dossier_depose_sur_portail();
6664                if (! $demandeurPrincipalNotifie && ($isPortal === false || $depotPortal === true)) {
6665                    // Préparation des logs pour indiquer que le pétitionnaire principale n'est pas notifiable
6666                    $msgLog .= sprintf(' %s', __('Le pétitionnaire principale n\'est pas notifiable.'));
6667                    // Analyse pour savoir pourquoi le demandeur principal n'est pas notifiable
6668                    $erreursParam = $this->get_info_notification_fail();
6669                    $demandeurPrincipal = $this->get_info_petitionnaire_principal_dossier($this->getVal('dossier'));
6670                    // Ajout de la notif et récupération de son id
6671                    $idNotif = $this->ajouter_notification(
6672                        $this->valF[$this->clePrimaire],
6673                        $this->f->get_connected_user_login_name(),
6674                        $demandeurPrincipal,
6675                        $collectivite_di,
6676                        array(),
6677                        true,
6678                        'Echec',
6679                        implode(' ', $erreursParam)
6680                    );
6681                    if ($idNotif === false) {
6682                        $this->addToMessage(
6683                            __('Erreur : la création de la notification a échouée.').
6684                            __("Veuillez contacter votre administrateur.")
6685                        );
6686                        $this->addToLog(
6687                            sprintf('%s() : %s', __METHOD__, $msgLog),
6688                            DEBUG_MODE
6689                        );
6690                        return false;
6691                    }
6692                    // Prépare un message d'alerte à destination de l'instructeur pour l'informer
6693                    // de l'échec de la notification
6694                    $dossier_message = $this->get_inst_dossier_message(0);
6695                    $dossier_message_val = array(
6696                        'dossier' => $this->getVal('dossier'),
6697                        'type' => _('erreur expedition'),
6698                        'emetteur' => $this->f->get_connected_user_login_name(),
6699                        'login' => $_SESSION['login'],
6700                        'date_emission' => date('Y-m-d H:i:s'),
6701                        'contenu' => _('Échec lors de la notification de l\'instruction ').
6702                            $ev->getVal('libelle').
6703                            '.<br>'.
6704                            implode("\n", $erreursParam).
6705                            '<br>'.
6706                            _('Veuillez corriger ces informations avant de renvoyer la notification.')
6707                    );
6708                    $add = $dossier_message->add_notification_message($dossier_message_val, true);
6709                    // Si une erreur se produit pendant l'ajout
6710                    if ($add !== true) {
6711                        $this->addToLog(__METHOD__."(): Le message d'alerte concernant l'echec de l'envoi de la notification n'a pas pu être envoyé.", DEBUG_MODE);
6712                        return false;
6713                  }                  }
                 $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.")));  
6714              }              }
6715          }          }
6716    
# Line 5346  class instruction extends instruction_ge Line 6719  class instruction extends instruction_ge
6719      }      }
6720    
6721      /**      /**
6722         * Récupère l'instance de dossier message.
6723         *
6724         * @param string $dossier_message Identifiant du message.
6725         *
6726         * @return object
6727         */
6728        private function get_inst_dossier_message($dossier_message = null) {
6729            //
6730            return $this->get_inst_common("dossier_message", $dossier_message);
6731        }
6732    
6733        /**
6734         * Vérifie si le signataire est obligatoire pour finaliser
6735         * le document apartir du paramétrage de l'événement.
6736         * Si c'est le cas, vérifie si il y a bien un signataire
6737         * renseigné.
6738         * Si c'est le cas renvoie true, sinon renvoie false.
6739         *
6740         * @param evenement évenement de l'instruction permettant de
6741         * récupérer le paramétrage
6742         * @return boolean
6743         */
6744        protected function controle_signataire($evenement) {
6745            // Vérifie si le signataire est obligatoire et si c'est le cas
6746            // vérifie si il y a bien un signataire pour le document
6747            if ($evenement->is_signataire_obligatoire() &&
6748                ($this->getVal('signataire_arrete') === null ||
6749                $this->getVal('signataire_arrete') === '')) {
6750                return false;
6751            }
6752            return true;
6753        }
6754    
6755        /**
6756       * TREATMENT - unfinalize.       * TREATMENT - unfinalize.
6757       *       *
6758       * Permet de définaliser un enregistrement.       * Permet de définaliser un enregistrement.
# Line 5515  class instruction extends instruction_ge Line 6922  class instruction extends instruction_ge
6922              "idx" => $idx,              "idx" => $idx,
6923          ));          ));
6924    
6925          /**          $qres = $this->f->get_all_results_from_db_query(
6926           *              sprintf(
6927           */                  'SELECT
6928          //                      *,
6929          $sql = "SELECT *, bible.libelle as bible_lib                      bible.libelle as bible_lib
6930          FROM ".DB_PREFIXE."bible                  FROM
6931          LEFT OUTER JOIN ".DB_PREFIXE."dossier_autorisation_type                      %1$sbible
6932              ON bible.dossier_autorisation_type=dossier_autorisation_type.dossier_autorisation_type                      LEFT OUTER JOIN %1$sdossier_autorisation_type
6933          LEFT JOIN ".DB_PREFIXE."om_collectivite                          ON bible.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
6934              ON bible.om_collectivite = om_collectivite.om_collectivite                      LEFT JOIN %1$som_collectivite
6935          WHERE (evenement=".$evenement." OR evenement IS NULL)                          ON bible.om_collectivite = om_collectivite.om_collectivite
6936              AND (complement=".$complement." OR complement IS NULL)                  WHERE
6937              AND (bible.dossier_autorisation_type IS NULL                      (evenement = %2$d
6938                  OR dossier_autorisation_type.code ='".$code_da_type."')                          OR evenement IS NULL)
6939              AND (om_collectivite.niveau = '2'                      AND (complement = %3$d
6940                  OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")                          OR complement IS NULL)
6941          ORDER BY bible_lib ASC";                      AND (bible.dossier_autorisation_type IS NULL
6942          $res = $this->f->db->query($sql);                          OR dossier_autorisation_type.code = \'%4$s\')
6943          $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\");", VERBOSE_MODE);                      AND (om_collectivite.niveau = \'2\'
6944          $this->f->isDatabaseError($res);                          OR bible.om_collectivite = %5$d)
6945                    ORDER BY
6946                        bible_lib ASC',
6947                    DB_PREFIXE,
6948                    intval($evenement),
6949                    intval($complement),
6950                    $this->f->db->escapeSimple($code_da_type),
6951                    intval($dossier->getVal("om_collectivite"))
6952                ),
6953                array(
6954                    'origin' => __METHOD__
6955                )
6956            );
6957          //          //
6958          echo "<form method=\"post\" name=\"f3\" action=\"#\">\n";          echo "<form method=\"post\" name=\"f3\" action=\"#\">\n";
6959          //          //
6960          if ($res->numrows() > 0) {          if (count($qres['result']) > 0) {
6961              //              //
6962              echo "\t<table id='tab-bible' width='100%'>\n";              echo "\t<table id='tab-bible' width='100%'>\n";
6963              //              //
# Line 5549  class instruction extends instruction_ge Line 6968  class instruction extends instruction_ge
6968              //              //
6969              $i = 0;              $i = 0;
6970              //              //
6971              while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {              foreach ($qres['result'] as $row) {
6972                  //                  //
6973                  echo "\t\t<tr";                  echo "\t\t<tr";
6974                  echo " class=\"".($i % 2 == 0 ? "odd" : "even")."\"";                  echo " class=\"".($i % 2 == 0 ? "odd" : "even")."\"";
# Line 5617  class instruction extends instruction_ge Line 7036  class instruction extends instruction_ge
7036          $retour['complement2_om_html'] = '';          $retour['complement2_om_html'] = '';
7037          $retour['complement3_om_html'] = '';          $retour['complement3_om_html'] = '';
7038          $retour['complement4_om_html'] = '';          $retour['complement4_om_html'] = '';
7039    
7040          // Vérification d'une consultation liée à l'événement          // Vérification d'une consultation liée à l'événement
7041          $consultation = $this->f->db->getOne(          $instEvenement = $this->f->get_inst__om_dbform(array(
7042              "select consultation from ".DB_PREFIXE."evenement where evenement=".$evenement              "obj" => "evenement",
7043          );              "idx" => $evenement,
7044          $this->f->isDatabaseError($consultation);          ));
7045    
7046          // Si consultation liée, récupération du retour d'avis          // Si consultation liée, récupération du retour d'avis
7047          if($consultation=='Oui'){          if($instEvenement->getVal('consultation') == 'Oui'){
7048              $sql="select date_retour,avis_consultation.libelle as avis_consultation,  
7049                    service.libelle as service              $qres = $this->f->get_all_results_from_db_query(
7050                    from ".DB_PREFIXE."consultation inner join ".DB_PREFIXE."service                  sprintf(
7051                    on consultation.service =service.service                      'SELECT
7052                    left join ".DB_PREFIXE."avis_consultation on                          date_retour,
7053                      consultation.avis_consultation = avis_consultation.avis_consultation                          avis_consultation.libelle as avis_consultation,
7054                    where dossier ='".$idx."' and consultation.visible";                          COALESCE(service.libelle, tiers_consulte.libelle) as service
7055              $res = $this->f->db->query($sql);                      FROM
7056              $this->f->isDatabaseError($res);                          %1$sconsultation
7057                            LEFT JOIN %1$stiers_consulte
7058                                ON consultation.tiers_consulte = tiers_consulte.tiers_consulte
7059                            LEFT JOIN %1$sservice
7060                                ON consultation.service = service.service
7061                            LEFT JOIN %1$savis_consultation
7062                                ON consultation.avis_consultation = avis_consultation.avis_consultation
7063                        WHERE
7064                            dossier = \'%2$s\'
7065                            AND consultation.visible',
7066                        DB_PREFIXE,
7067                        $this->f->db->escapeSimple($idx)
7068                    ),
7069                    array(
7070                        'origin' => __METHOD__
7071                    )
7072                );
7073              // Récupération des consultations              // Récupération des consultations
7074              while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){              foreach ($qres['result'] as $row) {
7075                  $correct=false;                  $correct=false;
7076                  // date retour                  // date retour
7077                  if ($row['date_retour']<>""){                  if ($row['date_retour']<>""){
# Line 5687  class instruction extends instruction_ge Line 7124  class instruction extends instruction_ge
7124          $merge_fields = array();          $merge_fields = array();
7125          //          //
7126          if (array_key_exists('c1', $_POST) === true) {          if (array_key_exists('c1', $_POST) === true) {
7127              $merge_fields['[complement_instruction]'] = urldecode($_POST['c1']);              $merge_fields['[complement_instruction]'] = $_POST['c1'];
7128              $merge_fields['[complement1_instruction]'] = urldecode($_POST['c1']);              $merge_fields['[complement1_instruction]'] = $_POST['c1'];
7129          }          }
7130          if (array_key_exists('c2', $_POST) === true) {          if (array_key_exists('c2', $_POST) === true) {
7131              $merge_fields['[complement2_instruction]'] = urldecode($_POST['c2']);              $merge_fields['[complement2_instruction]'] = $_POST['c2'];
7132          }          }
7133          if (array_key_exists('c3', $_POST) === true) {          if (array_key_exists('c3', $_POST) === true) {
7134              $merge_fields['[complement3_instruction]'] = urldecode($_POST['c3']);              $merge_fields['[complement3_instruction]'] = $_POST['c3'];
7135          }          }
7136          if (array_key_exists('c4', $_POST) === true) {          if (array_key_exists('c4', $_POST) === true) {
7137              $merge_fields['[complement4_instruction]'] = urldecode($_POST['c4']);              $merge_fields['[complement4_instruction]'] = $_POST['c4'];
7138          }          }
7139          $params = array(          $params = array(
7140              "watermark" => true,              "watermark" => true,
# Line 5709  class instruction extends instruction_ge Line 7146  class instruction extends instruction_ge
7146          if (array_key_exists('corps', $_POST) === true) {          if (array_key_exists('corps', $_POST) === true) {
7147              $params["specific"]["corps"] = array(              $params["specific"]["corps"] = array(
7148                  "mode" => "set",                  "mode" => "set",
7149                  "value" => urldecode($_POST['corps']),                  "value" => $_POST['corps'],
7150              );              );
7151          }          }
7152          if (array_key_exists('titre', $_POST) === true) {          if (array_key_exists('titre', $_POST) === true) {
7153              $params["specific"]["titre"] = array(              $params["specific"]["titre"] = array(
7154                  "mode" => "set",                  "mode" => "set",
7155                  "value" => urldecode($_POST['titre']),                  "value" => $_POST['titre'],
7156              );              );
7157          }          }
7158          $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();          $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
# Line 5776  class instruction extends instruction_ge Line 7213  class instruction extends instruction_ge
7213          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {
7214              $code_da_type = $matches[0];              $code_da_type = $matches[0];
7215          }          }
         //  
         $sql = "SELECT * FROM ".DB_PREFIXE."bible  
             LEFT OUTER JOIN ".DB_PREFIXE."dossier_autorisation_type  
                 ON bible.dossier_autorisation_type=  
                     dossier_autorisation_type.dossier_autorisation_type  
             LEFT JOIN  
                     ".DB_PREFIXE."om_collectivite  
                     ON bible.om_collectivite = om_collectivite.om_collectivite  
             WHERE (evenement =".$event." or evenement IS NULL) and  
                 (complement=".$compnb." OR complement IS NULL) and  
                 automatique='Oui' and  
                 (dossier_autorisation_type.code ='".$code_da_type."' or  
                     bible.dossier_autorisation_type IS NULL) and  
                 (om_collectivite.niveau = '2' OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")";  
7216    
7217          $res = $this->f->db->query($sql);          $qres = $this->f->get_all_results_from_db_query(
7218          $this->f->isDatabaseError($res);              sprintf(
7219                    'SELECT
7220                        *
7221                    FROM
7222                        %1$sbible
7223                        LEFT OUTER JOIN %1$sdossier_autorisation_type
7224                            ON bible.dossier_autorisation_type =
7225                                dossier_autorisation_type.dossier_autorisation_type
7226                        LEFT JOIN %1$som_collectivite
7227                            ON bible.om_collectivite = om_collectivite.om_collectivite
7228                    WHERE
7229                        (evenement = %2$d
7230                            OR evenement IS NULL)
7231                        AND (complement = %3$d
7232                            OR complement IS NULL)
7233                        AND automatique = \'Oui\'
7234                        AND (dossier_autorisation_type.code = \'%4$s\'
7235                            OR bible.dossier_autorisation_type IS NULL)
7236                        AND (om_collectivite.niveau = \'2\'
7237                            OR bible.om_collectivite = %5$d)',
7238                    DB_PREFIXE,
7239                    intval($event),
7240                    intval($compnb),
7241                    $this->f->db->escapeSimple($code_da_type),
7242                    intval($dossier->getVal("om_collectivite"))
7243                ),
7244                array(
7245                    "origin" => __METHOD__
7246                )
7247            );
7248          $temp = "";          $temp = "";
7249          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){          foreach ($qres['result'] as $row) {
7250              // Remplacement des retours à la ligne par des br              // Remplacement des retours à la ligne par des br
7251              $temp .= preg_replace(              $temp .= preg_replace(
7252                  '#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $row['contenu']                  '#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $row['contenu']
# Line 5848  class instruction extends instruction_ge Line 7300  class instruction extends instruction_ge
7300              // Affiche le message de validation              // Affiche le message de validation
7301              else {              else {
7302                  // On récupère le libellé du bordereau pour l'afficher à l'utilisateur                  // On récupère le libellé du bordereau pour l'afficher à l'utilisateur
7303                  $sql = "SELECT om_etat.libelle                  $etat = $this->f->get_inst__om_dbform(array(
7304                  FROM ".DB_PREFIXE."om_etat                      "obj" => "om_etat",
7305                  WHERE om_etat.id = '".$this->f->get_submitted_post_value("bordereau")."'";                      "idx" => $this->f->get_submitted_post_value("bordereau")
7306                  $res = $this->f->db->getone($sql);                  ));
7307                  $this->f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);                  $qres = $this->f->get_one_result_from_db_query(
7308                  $this->f->isDatabaseError($res);                      sprintf(
7309                            'SELECT
7310                                om_etat.libelle
7311                            FROM
7312                                %som_etat
7313                            WHERE
7314                                om_etat.id = \'%s\'',
7315                            DB_PREFIXE,
7316                            $this->f->db->escapeSimple($this->f->get_submitted_post_value("bordereau"))
7317                        ),
7318                        array(
7319                            "origin" => __METHOD__,
7320                        )
7321                    );
7322    
7323                  //                  //
7324                  $message_class = "valid";                  $message_class = "valid";
7325                  $message = _("Cliquez sur le lien ci-dessous pour telecharger votre bordereau");                  $message = _("Cliquez sur le lien ci-dessous pour telecharger votre bordereau");
# Line 5871  class instruction extends instruction_ge Line 7337  class instruction extends instruction_ge
7337                      $message .= "&collectivite=".$this->f->get_submitted_post_value("om_collectivite");                      $message .= "&collectivite=".$this->f->get_submitted_post_value("om_collectivite");
7338                  }                  }
7339                  $message .= "'"." target='_blank'>";                  $message .= "'"." target='_blank'>";
7340                  $message .= $res." "._("du")." ".$this->f->get_submitted_post_value("date_bordereau_debut")                  $message .= $qres['result']." "._("du")." ".$this->f->get_submitted_post_value("date_bordereau_debut")
7341                      ." "._("au")." ".$this->f->get_submitted_post_value("date_bordereau_fin");                      ." "._("au")." ".$this->f->get_submitted_post_value("date_bordereau_fin");
7342                  $message .= "</a>";                  $message .= "</a>";
7343              }              }
# Line 5933  class instruction extends instruction_ge Line 7399  class instruction extends instruction_ge
7399          // Données du select - On récupère ici la liste de tous les états disponibles          // Données du select - On récupère ici la liste de tous les états disponibles
7400          // dans la table om_etat qui ont un id qui commence par la cahine de caractères          // dans la table om_etat qui ont un id qui commence par la cahine de caractères
7401          // 'bordereau_'          // 'bordereau_'
7402          $sql = "SELECT om_etat.id, om_etat.libelle          $qres = $this->f->get_all_results_from_db_query(
7403                  FROM ".DB_PREFIXE."om_etat              sprintf(
7404                  WHERE om_etat.id LIKE 'bordereau_%'                  'SELECT
7405                  ORDER BY om_etat.id";                      om_etat.id,
7406          $res = $this->f->db->query($sql);                      om_etat.libelle
7407          $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                  FROM
7408          $this->f->isDatabaseError($res);                      %1$som_etat
7409                    WHERE
7410                        om_etat.id LIKE \'bordereau_%%\'
7411                    ORDER BY
7412                        om_etat.id',
7413                    DB_PREFIXE
7414                ),
7415                array(
7416                    "origin" => __METHOD__
7417                )
7418            );
7419          // Données du select          // Données du select
7420          $contenu = array(          $contenu = array(
7421              0 => array("", ),              0 => array("", ),
7422              1 => array(_("choisir bordereau")),              1 => array(_("choisir bordereau")),
7423          );          );
7424          while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {          foreach ($qres['result'] as $row) {
7425              $contenu[0][] = $row['id'];              $contenu[0][] = $row['id'];
7426              $contenu[1][] = $row['libelle'];              $contenu[1][] = $row['libelle'];
7427          }          }
# Line 5957  class instruction extends instruction_ge Line 7433  class instruction extends instruction_ge
7433    
7434              // Données du select - On récupère ici la liste de tous toutes les collectivités              // Données du select - On récupère ici la liste de tous toutes les collectivités
7435              // de niveau 1              // de niveau 1
7436              $sql = "SELECT om_collectivite, libelle              $qres = $this->f->get_all_results_from_db_query(
7437                      FROM ".DB_PREFIXE."om_collectivite                  sprintf(
7438                      WHERE niveau = '1' ORDER BY libelle";                      'SELECT
7439              $res = $this->f->db->query($sql);                          om_collectivite,
7440              $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                          libelle
7441              $this->f->isDatabaseError($res);                      FROM
7442                            %1$som_collectivite
7443                        WHERE
7444                            niveau = \'1\'
7445                        ORDER BY
7446                            libelle',
7447                        DB_PREFIXE
7448                    ),
7449                    array(
7450                        "origin" => __METHOD__
7451                    )
7452                );
7453              // La valeur par défaut du select est Toutes              // La valeur par défaut du select est Toutes
7454              $list_collectivites = array(              $list_collectivites = array(
7455                  0 => array("", ),                  0 => array("", ),
# Line 5972  class instruction extends instruction_ge Line 7459  class instruction extends instruction_ge
7459              $id_colls = "";              $id_colls = "";
7460              // On stocke dans $id_colls l'id de toutes les collectivités de niveau 1 séparées              // On stocke dans $id_colls l'id de toutes les collectivités de niveau 1 séparées
7461              // par des virgules, pour un traitement plus facile dans la requête de sous-état              // par des virgules, pour un traitement plus facile dans la requête de sous-état
7462              while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {              foreach ($qres['result'] as $row) {
7463                  if ($id_colls != "") {                  if ($id_colls != "") {
7464                      $id_colls .= ",";                      $id_colls .= ",";
7465                  }                  }
# Line 6108  class instruction extends instruction_ge Line 7595  class instruction extends instruction_ge
7595                              $conditions = implode(" OR ", $group_clause);                              $conditions = implode(" OR ", $group_clause);
7596                              $sql .= " AND (" . $conditions . ")";                              $sql .= " AND (" . $conditions . ")";
7597    
7598                              $nbInstr = $this->f->db->getone($sql);                              $qres = $this->f->get_one_result_from_db_query(
7599                              $this->f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);                                  $sql,
7600                              $this->f->isDatabaseError($nbInstr);                                  array(
7601                              //                                      "origin" => __METHOD__,
7602                              if ($nbInstr == "1") {                                  )
7603                                );
7604    
7605                                if ($qres['result'] == "1") {
7606                                  // Récupération de la date d'envoi de l'instruction bippé                                  // Récupération de la date d'envoi de l'instruction bippé
7607                                  $sql = "SELECT to_char(date_envoi_rar,'DD/MM/YYYY')  as date_envoi_rar, instruction FROM ".DB_PREFIXE."instruction WHERE code_barres='".$code_barres."'";                                  $qres = $this->f->get_all_results_from_db_query(
7608                                  $res = $this->f->db->query($sql);                                      sprintf(
7609                                  $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                                          'SELECT
7610                                  $this->f->isDatabaseError($res);                                              to_char(date_envoi_rar, \'DD/MM/YYYY\') as date_envoi_rar,
7611                                  $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);                                              instruction
7612                                            FROM
7613                                                %1$sinstruction
7614                                            WHERE
7615                                                code_barres = \'%2$s\'',
7616                                            DB_PREFIXE,
7617                                            $this->f->db->escapeSimple($code_barres)
7618                                        ),
7619                                        array(
7620                                            'origin' => __METHOD__
7621                                        )
7622                                    );
7623                                    $row = array_shift($qres['result']);
7624                                  // Si pas de date ou correspond à la date du formulaire on                                  // Si pas de date ou correspond à la date du formulaire on
7625                                  // effectue le traitement                                  // effectue le traitement
7626                                  if ($row["date_envoi_rar"] == "" || $row["date_envoi_rar"] == $date) {                                  if ($row["date_envoi_rar"] == "" || $row["date_envoi_rar"] == $date) {
# Line 6414  class instruction extends instruction_ge Line 7916  class instruction extends instruction_ge
7916          if ($this->f->get_submitted_post_value('validation') !== null) {          if ($this->f->get_submitted_post_value('validation') !== null) {
7917              if(!empty($type_mise_a_jour) and !empty($date) and !empty($code_barres)) {              if(!empty($type_mise_a_jour) and !empty($date) and !empty($code_barres)) {
7918    
                 // Vérification de l'existence de l'instruction  
                 $sql = "SELECT instruction  
                         FROM ".DB_PREFIXE."instruction  
                             INNER JOIN ".DB_PREFIXE."dossier  
                                 ON dossier.dossier=instruction.dossier  
                             INNER JOIN ".DB_PREFIXE."dossier_instruction_type  
                                 ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type  
                             INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille  
                                 ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille  
                             INNER JOIN ".DB_PREFIXE."dossier_autorisation_type  
                                 ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type  
                             INNER JOIN ".DB_PREFIXE."groupe  
                                 ON dossier_autorisation_type.groupe = groupe.groupe  
                             WHERE code_barres='".$this->f->db->escapesimple($code_barres)."'";  
   
7919                  // Ajout d'un filtre sur les groupes auxquels l'utilisateur a accès                  // Ajout d'un filtre sur les groupes auxquels l'utilisateur a accès
7920                  $group_clause = array();                  $group_clause = array();
7921                  foreach ($_SESSION["groupe"] as $key => $value) {                  foreach ($_SESSION["groupe"] as $key => $value) {
# Line 6439  class instruction extends instruction_ge Line 7926  class instruction extends instruction_ge
7926                      $group_clause[$key] .= ")";                      $group_clause[$key] .= ")";
7927                  }                  }
7928                  $conditions = implode(" OR ", $group_clause);                  $conditions = implode(" OR ", $group_clause);
7929                  $sql .= " AND (" . $conditions . ")";                  $groupFilter = " AND (" . $conditions . ")";
   
   
                 $res = $this->f->db->query($sql);  
                 $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);  
                 $this->f->isDatabaseError($res);  
7930    
7931                  if($res->numrows() == 1) {                  $qres = $this->f->get_all_results_from_db_query(
7932                        sprintf(
7933                            'SELECT
7934                                instruction
7935                            FROM
7936                                %1$sinstruction
7937                                INNER JOIN %1$sdossier
7938                                    ON dossier.dossier = instruction.dossier
7939                                INNER JOIN %1$sdossier_instruction_type
7940                                    ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
7941                                INNER JOIN %1$sdossier_autorisation_type_detaille
7942                                    ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
7943                                INNER JOIN %1$sdossier_autorisation_type
7944                                    ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
7945                                INNER JOIN %1$sgroupe
7946                                    ON dossier_autorisation_type.groupe = groupe.groupe
7947                                WHERE
7948                                    code_barres = \'%2$s\'
7949                                    %3$s',
7950                            DB_PREFIXE,
7951                            $this->f->db->escapeSimple($code_barres),
7952                            $groupFilter
7953                        ),
7954                        array(
7955                            'origin' => __METHOD__
7956                        )
7957                    );
7958                    if(count($qres['result']) === 1) {
7959                      $liste_champs = explode(";", $type_mise_a_jour);                      $liste_champs = explode(";", $type_mise_a_jour);
7960                      $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);                      $row = array_shift($qres['result']);
7961                      $instr = $this->f->get_inst__om_dbform(array(                      $instr = $this->f->get_inst__om_dbform(array(
7962                          "obj" => "instruction",                          "obj" => "instruction",
7963                          "idx" => $row['instruction'],                          "idx" => $row['instruction'],
# Line 6534  class instruction extends instruction_ge Line 8043  class instruction extends instruction_ge
8043                          }                          }
8044                      } else {                      } else {
8045                          // Récupération des infos du dossier                          // Récupération des infos du dossier
8046                          $sqlInfo = "SELECT dossier.dossier_libelle,                          $qres = $this->f->get_all_results_from_db_query(
8047                                              evenement.libelle as evenement,                              sprintf(
8048                                              autorite_competente.code as autorite_competente_code,                                  'SELECT
8049                                              autorite_competente.libelle as autorite_competente,                                      dossier.dossier_libelle,
8050                                              evenement.type as evenement_type,                                      evenement.libelle as evenement,
8051                                              to_char(date_envoi_signature,'DD/MM/YYYY')  as date_envoi_signature,                                      autorite_competente.code as autorite_competente_code,
8052                                              to_char(date_retour_signature,'DD/MM/YYYY')  as date_retour_signature,                                      autorite_competente.libelle as autorite_competente,
8053                                              to_char(date_envoi_controle_legalite,'DD/MM/YYYY')  as date_envoi_controle_legalite,                                      evenement.type as evenement_type,
8054                                              to_char(date_retour_controle_legalite,'DD/MM/YYYY')  as date_retour_controle_legalite,                                      to_char(date_envoi_signature,\'DD/MM/YYYY\') as date_envoi_signature,
8055                                              to_char(date_envoi_rar,'DD/MM/YYYY')  as date_envoi_rar,                                      to_char(date_retour_signature,\'DD/MM/YYYY\') as date_retour_signature,
8056                                              to_char(date_retour_rar,'DD/MM/YYYY')  as date_retour_rar                                      to_char(date_envoi_controle_legalite,\'DD/MM/YYYY\') as date_envoi_controle_legalite,
8057                                      FROM ".DB_PREFIXE."instruction                                      to_char(date_retour_controle_legalite,\'DD/MM/YYYY\') as date_retour_controle_legalite,
8058                                      INNER JOIN ".DB_PREFIXE."dossier ON                                      to_char(date_envoi_rar,\'DD/MM/YYYY\') as date_envoi_rar,
8059                                          dossier.dossier=instruction.dossier                                      to_char(date_retour_rar,\'DD/MM/YYYY\') as date_retour_rar
8060                                      LEFT JOIN ".DB_PREFIXE."autorite_competente ON                                  FROM
8061                                          dossier.autorite_competente=autorite_competente.autorite_competente                                      %1$sinstruction
8062                                      INNER JOIN ".DB_PREFIXE."evenement ON                                      INNER JOIN %1$sdossier
8063                                          instruction.evenement=evenement.evenement                                          ON dossier.dossier=instruction.dossier
8064                                      WHERE code_barres='".$code_barres."'";                                      LEFT JOIN %1$sautorite_competente
8065                          $resInfo = $this->f->db->query($sqlInfo);                                          ON dossier.autorite_competente=autorite_competente.autorite_competente
8066                          $this->f->isDatabaseError($resInfo);                                      INNER JOIN %1$sevenement
8067                          $infos = $resInfo->fetchRow(DB_FETCHMODE_ASSOC);                                          ON instruction.evenement=evenement.evenement
8068                                    WHERE
8069                                        code_barres = \'%2$s\'',
8070                                    DB_PREFIXE,
8071                                    $this->f->db->escapeSimple($code_barres)
8072                                ),
8073                                array(
8074                                    "origin" => __METHOD__
8075                                )
8076                            );
8077                            $infos = array_shift($qres['result']);
8078    
8079                          // Vérification de la non modification des dates de suivi                          // Vérification de la non modification des dates de suivi
8080                          foreach(explode(";", $type_mise_a_jour) as $champ) {                          foreach(explode(";", $type_mise_a_jour) as $champ) {
# Line 6781  class instruction extends instruction_ge Line 8300  class instruction extends instruction_ge
8300              foreach ($listeCodeBarres as $code_barres) {              foreach ($listeCodeBarres as $code_barres) {
8301    
8302                  // On récupère le dossier                  // On récupère le dossier
8303                  $sql = "SELECT dossier                  $qres = $this->f->get_one_result_from_db_query(
8304                          FROM " . DB_PREFIXE . "instruction                      sprintf(
8305                          WHERE code_barres = '" . $code_barres . "'";                          'SELECT
8306                  $dossier = $this->f->db->getOne($sql);                              dossier
8307                  $this->f->addToLog(__METHOD__."(): db->getOne(\"".$sql."\")", VERBOSE_MODE);                          FROM
8308                  $this->f->isDatabaseError($dossier);                              %1$sinstruction
8309                            WHERE
8310                                code_barres = \'%2$s\'',
8311                            DB_PREFIXE,
8312                            $this->f->db->escapeSimple($code_barres)
8313                        ),
8314                        array(
8315                            "origin" => __METHOD__,
8316                        )
8317                    );
8318                    
8319                  $inst_dossier = $this->f->get_inst__om_dbform(array(                  $inst_dossier = $this->f->get_inst__om_dbform(array(
8320                      "obj" => "dossier",                      "obj" => "dossier",
8321                      "idx" => $dossier,                      "idx" => $qres['result'],
8322                  ));                  ));
8323    
8324                  // En fonction du type de dossier, on récupère un demandeur différent dans les requêtes                  // En fonction du type de dossier, on récupère un demandeur différent dans les requêtes
# Line 6810  class instruction extends instruction_ge Line 8339  class instruction extends instruction_ge
8339                  }                  }
8340    
8341                  // Test si l'evenement est de type arrete et si un délégataire a été nommé                  // Test si l'evenement est de type arrete et si un délégataire a été nommé
8342                  $sql = "SELECT                  $qres = $this->f->get_all_results_from_db_query(
8343                        sprintf(
8344                            'SELECT
8345                              dossier.dossier_libelle,                              dossier.dossier_libelle,
8346                              evenement.type,                              evenement.type,
8347                              count(lien_dossier_demandeur) as nbdemandeur,                              count(lien_dossier_demandeur) as nbdemandeur,
8348                              CASE                              CASE
8349                                  WHEN division.libelle IS NOT NULL AND phase.code IS NOT NULL                                  WHEN division.libelle IS NOT NULL AND phase.code IS NOT NULL
8350                                      THEN CONCAT(phase.code, ' - ', division.libelle)                                      THEN CONCAT(phase.code, \' - \', division.libelle)
8351                                  ELSE                                  ELSE
8352                                      phase.code                                      phase.code
8353                              END AS code_phase                              END AS code_phase
8354                          FROM ".DB_PREFIXE."instruction                          FROM
8355                          LEFT JOIN ".DB_PREFIXE."dossier                              %1$sinstruction
8356                              ON instruction.dossier = dossier.dossier                              LEFT JOIN %1$sdossier
8357                          LEFT JOIN ".DB_PREFIXE."division                                  ON instruction.dossier = dossier.dossier
8358                              ON dossier.division = division.division                              LEFT JOIN %1$sdivision
8359                          INNER JOIN ".DB_PREFIXE."evenement ON                                  ON dossier.division = division.division
8360                              instruction.evenement=evenement.evenement                              INNER JOIN %1$sevenement
8361                          LEFT JOIN ".DB_PREFIXE."phase                                  ON instruction.evenement=evenement.evenement
8362                              ON evenement.phase = phase.phase                              LEFT JOIN %1$sphase
8363                          inner JOIN ".DB_PREFIXE."lien_dossier_demandeur ON                                  ON evenement.phase = phase.phase
8364                              instruction.dossier=lien_dossier_demandeur.dossier                              inner JOIN %1$slien_dossier_demandeur
8365                          inner join ".DB_PREFIXE."demandeur on                                  ON instruction.dossier=lien_dossier_demandeur.dossier
8366                              demandeur.demandeur=lien_dossier_demandeur.demandeur                              inner join %1$sdemandeur
8367                          WHERE code_barres='".$code_barres."'                                  ON demandeur.demandeur=lien_dossier_demandeur.demandeur
8368                              AND " . $sql_demandeur . "                          WHERE
8369                          GROUP BY dossier.dossier_libelle, evenement.type, phase.code, division.libelle";                              code_barres = \'%2$s\'
8370                                AND %3$s
8371                  $res = $this->f->db->query($sql);                          GROUP BY
8372                  $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                              dossier.dossier_libelle,
8373                  $this->f->isDatabaseError($res);                              evenement.type,
8374                  $testDemandeur = $res->fetchrow(DB_FETCHMODE_ASSOC);                              phase.code,
8375                                division.libelle',
8376                            DB_PREFIXE,
8377                            $this->f->db->escapeSimple($code_barres),
8378                            $sql_demandeur
8379                        ),
8380                        array(
8381                            "origin" => __METHOD__
8382                        )
8383                    );
8384                    $testDemandeur = array_shift($qres['result']);
8385                                    
8386    
8387                  // Recuperation de l'adresse de destination                  // Recuperation de l'adresse de destination
                 $sqlAdresse = "SELECT  
                     CASE WHEN demandeur.qualite='particulier'  
                         THEN TRIM(CONCAT_WS(' ', pc.libelle, demandeur.particulier_nom, demandeur.particulier_prenom))  
                         ELSE TRIM(demandeur.personne_morale_denomination)  
                     END  as ligne1,  
                     CASE WHEN demandeur.qualite='personne_morale'  
                         THEN TRIM(demandeur.personne_morale_raison_sociale)  
                         ELSE ''  
                     END as ligne1_1,  
                     CASE WHEN demandeur.qualite='personne_morale' AND (demandeur.personne_morale_nom IS NOT NULL OR demandeur.personne_morale_prenom IS NOT NULL)  
                         THEN TRIM(CONCAT_WS(' ', 'rep. par', demandeur.personne_morale_nom, demandeur.personne_morale_prenom))  
                         ELSE ''  
                     END as ligne1_2,  
                     trim(concat(demandeur.numero,' ',demandeur.voie)) as ligne2,  
                     CASE demandeur.complement  
                     WHEN null THEN ''  
                     ELSE trim(demandeur.complement)  
                     END as ligne3,  
                     CASE demandeur.lieu_dit  
                     WHEN null THEN ''  
                     ELSE trim(demandeur.lieu_dit)  
                     END as ligne4,  
                     CONCAT_WS(' ', demandeur.code_postal, demandeur.localite,  
                         (CASE WHEN demandeur.bp IS NOT NULL  
                             THEN CONCAT_WS(' ', 'BP', demandeur.bp)  
                             ELSE ''  
                         END),  
                         (CASE WHEN demandeur.cedex IS NOT NULL  
                             THEN CONCAT_WS(' ', 'CEDEX', demandeur.cedex)  
                             ELSE ''  
                         END))  
                     as ligne5,  
                     code_barres as code_barres  
                 FROM ".DB_PREFIXE."instruction  
                 INNER JOIN ".DB_PREFIXE."dossier ON dossier.dossier = instruction.dossier  
                 INNER JOIN ".DB_PREFIXE."lien_dossier_demandeur ON dossier.dossier = lien_dossier_demandeur.dossier  
                 INNER JOIN ".DB_PREFIXE."demandeur ON lien_dossier_demandeur.demandeur = demandeur.demandeur  
                 LEFT OUTER JOIN ".DB_PREFIXE."civilite as pc ON demandeur.particulier_civilite = pc.civilite OR demandeur.personne_morale_civilite = pc.civilite  
                 WHERE instruction.code_barres ='".$code_barres."'";  
   
8388                  // Envoi pour delegataire ou petitionnaire principal selon le type d'evenement                  // Envoi pour delegataire ou petitionnaire principal selon le type d'evenement
8389                    $sqlAdresse = " AND demandeur.type_demandeur='petitionnaire' AND lien_dossier_demandeur.petitionnaire_principal IS TRUE";
8390                  if($testDemandeur['type'] != 'arrete' AND $testDemandeur['nbdemandeur'] > 1) {                  if($testDemandeur['type'] != 'arrete' AND $testDemandeur['nbdemandeur'] > 1) {
8391                      $sqlAdresse .= " AND demandeur.type_demandeur='delegataire'";                      $sqlAdresse = " AND demandeur.type_demandeur='delegataire'";
                 } else {  
                     $sqlAdresse .= " AND demandeur.type_demandeur='petitionnaire' AND lien_dossier_demandeur.petitionnaire_principal IS TRUE";  
8392                  }                  }
8393    
8394                  $resAdresse = $this->f->db->query($sqlAdresse);                  $qres = $this->f->get_all_results_from_db_query(
8395                  $adresse_dest = $resAdresse->fetchrow(DB_FETCHMODE_ASSOC);                      sprintf(
8396                  $this->f->addToLog(__METHOD__.": db->query(\"".$sqlAdresse."\")", VERBOSE_MODE);                          'SELECT
8397                  $this->f->isDatabaseError($resAdresse);                              CASE WHEN demandeur.qualite = \'particulier\'
8398                                    THEN TRIM(CONCAT_WS(\' \', pc.libelle, demandeur.particulier_nom, demandeur.particulier_prenom))
8399                                    ELSE TRIM(demandeur.personne_morale_denomination)
8400                                END  as ligne1,
8401                                CASE WHEN demandeur.qualite = \'personne_morale\'
8402                                    THEN TRIM(demandeur.personne_morale_raison_sociale)
8403                                    ELSE \'\'
8404                                END as ligne1_1,
8405                                CASE WHEN demandeur.qualite = \'personne_morale\' AND (demandeur.personne_morale_nom IS NOT NULL OR demandeur.personne_morale_prenom IS NOT NULL)
8406                                    THEN TRIM(CONCAT_WS(\' \', \'rep. par\', demandeur.personne_morale_nom, demandeur.personne_morale_prenom))
8407                                    ELSE \'\'
8408                                END as ligne1_2,
8409                                trim(concat(demandeur.numero,\' \',demandeur.voie)) as ligne2,
8410                                CASE demandeur.complement
8411                                WHEN null THEN \'\'
8412                                ELSE trim(demandeur.complement)
8413                                END as ligne3,
8414                                CASE demandeur.lieu_dit
8415                                WHEN null THEN \'\'
8416                                ELSE trim(demandeur.lieu_dit)
8417                                END as ligne4,
8418                                CONCAT_WS(\' \', demandeur.code_postal, demandeur.localite,
8419                                    (CASE WHEN demandeur.bp IS NOT NULL
8420                                        THEN CONCAT_WS(\' \', \'BP\', demandeur.bp)
8421                                        ELSE \'\'
8422                                    END),
8423                                    (CASE WHEN demandeur.cedex IS NOT NULL
8424                                        THEN CONCAT_WS(\' \', \'CEDEX\', demandeur.cedex)
8425                                        ELSE \'\'
8426                                    END))
8427                                as ligne5,
8428                                code_barres as code_barres
8429                            FROM
8430                                %1$sinstruction
8431                                INNER JOIN %1$sdossier
8432                                    ON dossier.dossier = instruction.dossier
8433                                INNER JOIN %1$slien_dossier_demandeur
8434                                    ON dossier.dossier = lien_dossier_demandeur.dossier
8435                                INNER JOIN %1$sdemandeur
8436                                    ON lien_dossier_demandeur.demandeur = demandeur.demandeur
8437                                LEFT OUTER JOIN %1$scivilite AS pc
8438                                    ON demandeur.particulier_civilite = pc.civilite
8439                                        OR demandeur.personne_morale_civilite = pc.civilite
8440                            WHERE
8441                                instruction.code_barres = \'%2$s\'
8442                                %3$s',
8443                            DB_PREFIXE,
8444                            $this->f->db->escapeSimple($code_barres),
8445                            $sqlAdresse
8446                        ),
8447                        array(
8448                            "origin" => __METHOD__
8449                        )
8450                    );
8451                    $adresse_dest = array_shift($qres['result']);
8452    
8453                  // Création adresse destinataire sans ligne vide                  // Création adresse destinataire sans ligne vide
8454                  $adresse_destinataire = array();                  $adresse_destinataire = array();
# Line 7136  class instruction extends instruction_ge Line 8690  class instruction extends instruction_ge
8690      }      }
8691    
8692      /**      /**
8693         * VIEW - view_overlay_notification_service_consulte.
8694         *
8695         * Ouvre le sous-formulaire de notification des services consulte
8696         * en ajaxIt dans un overlay.
8697         * Cette action est bindée pour utiliser la fonction popUpIt.
8698         *
8699         * @return void
8700         */
8701        function view_overlay_notification_service_consulte() {
8702    
8703            // Vérification de l'accessibilité sur l'élément
8704            $this->checkAccessibility();
8705    
8706            printf(
8707                '<script type="text/javascript" >
8708                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=420&idx=%3$s\', 1);
8709                </script>',
8710                'instruction_notification_manuelle',
8711                OM_ROUTE_SOUSFORM,
8712                $this->getVal($this->clePrimaire),
8713                $this->getVal('dossier')
8714            );
8715        }
8716        
8717        /**
8718         * VIEW - overlay_notification_tiers_consulte.
8719         *
8720         * Ouvre le sous-formulaire de notification des tiers consulte
8721         * en ajaxIt dans un overlay.
8722         * Cette action est bindée pour utiliser la fonction popUpIt.
8723         *
8724         * @return void
8725         */
8726        function view_overlay_notification_tiers_consulte() {
8727    
8728            // Vérification de l'accessibilité sur l'élément
8729            $this->checkAccessibility();
8730    
8731            printf(
8732                '<script type="text/javascript" >
8733                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=430&idx=%3$s\', 1);
8734                </script>',
8735                'instruction_notification_manuelle',
8736                OM_ROUTE_SOUSFORM,
8737                $this->getVal($this->clePrimaire),
8738                $this->getVal('dossier')
8739            );
8740        }
8741    
8742        /**
8743         * VIEW - view_modale_selection_document_signe
8744         *
8745         * Ouvre le sous-formulaire de notification des services consulte
8746         * en ajaxIt dans un overlay.
8747         * Cette action est bindée pour utiliser la fonction popUpIt.
8748         *
8749         * @return void
8750         */
8751        function view_modale_selection_document_signe() {
8752    
8753            // Vérification de l'accessibilité sur l'élément
8754            $this->checkAccessibility();
8755    
8756            printf(
8757                '<script type="text/javascript" >
8758                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=115&idx=%3$s\', 1);
8759                </script>',
8760                'instruction_modale',
8761                OM_ROUTE_SOUSFORM,
8762                $this->getVal($this->clePrimaire),
8763                $this->getVal('dossier')
8764            );
8765        }
8766        
8767        /**
8768       * 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
8769       * pour exclure les dossiers du groupe contentieux.       * pour exclure les dossiers du groupe contentieux.
8770       *       *
# Line 7145  class instruction extends instruction_ge Line 8774  class instruction extends instruction_ge
8774      function get_instruction_by_barcode($barcode) {      function get_instruction_by_barcode($barcode) {
8775          // Begin          // Begin
8776          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
8777    
8778          // Vérification de l'existence de l'événement d'instruction          // Vérification de l'existence de l'événement d'instruction
8779          // pour le code-barres donné, en excluant les dossiers liés au groupe CTX          // pour le code-barres donné, en excluant les dossiers liés au groupe CTX
8780          $sql = "SELECT instruction          $qres = $this->f->get_one_result_from_db_query(
8781                  FROM ".DB_PREFIXE."instruction              sprintf(
8782                      INNER JOIN ".DB_PREFIXE."dossier                  'SELECT
8783                        instruction
8784                    FROM
8785                        %1$sinstruction
8786                        INNER JOIN %1$sdossier
8787                          ON dossier.dossier=instruction.dossier                          ON dossier.dossier=instruction.dossier
8788                      INNER JOIN ".DB_PREFIXE."dossier_instruction_type                      INNER JOIN %1$sdossier_instruction_type
8789                          ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type                          ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
8790                      INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille                      INNER JOIN %1$sdossier_autorisation_type_detaille
8791                          ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille                          ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
8792                      INNER JOIN ".DB_PREFIXE."dossier_autorisation_type                      INNER JOIN %1$sdossier_autorisation_type
8793                          ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type                          ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
8794                      INNER JOIN ".DB_PREFIXE."groupe                      INNER JOIN %1$sgroupe
8795                          ON dossier_autorisation_type.groupe = groupe.groupe                          ON dossier_autorisation_type.groupe = groupe.groupe
8796                              AND groupe.code != 'CTX'                              AND groupe.code != \'CTX\'
8797                  WHERE code_barres = '".$this->f->db->escapesimple($barcode)."'";                  WHERE
8798          $res = $this->f->db->getOne($sql);                      code_barres = \'%2$s\'',
8799          $this->f->addToLog(__METHOD__." : db->getOne(\"".$sql."\")", VERBOSE_MODE);                  DB_PREFIXE,
8800          $this->f->isDatabaseError($res);                  $this->f->db->escapeSimple($barcode)
8801                ),
8802                array(
8803                    "origin" => __METHOD__,
8804                )
8805            );
8806            
8807          // Retourne résultat          // Retourne résultat
8808          return $this->end_treatment(__METHOD__, $res);          return $this->end_treatment(__METHOD__, $qres['result']);
8809      }      }
8810    
8811      /**      /**
# Line 7183  class instruction extends instruction_ge Line 8823  class instruction extends instruction_ge
8823          // Begin          // Begin
8824          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
8825          // Requête          // Requête
8826          $res = $this->f->db->autoExecute(          $res = $this->f->db->autoexecute(
8827              DB_PREFIXE.$this->table,              DB_PREFIXE.$this->table,
8828              $valF,              $valF,
8829              DB_AUTOQUERY_UPDATE,              DB_AUTOQUERY_UPDATE,
8830              $this->getCle($id)              $this->getCle($id)
8831          );          );
8832          // S'il y a eu une erreur          $this->addToLog(
8833          if (database::isError($res, true)) {              __METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($id)."\");",
8834                VERBOSE_MODE
8835            );
8836            if ($this->f->isDatabaseError($res, true) !== false) {
8837              $this->end_treatment(__METHOD__, false);              $this->end_treatment(__METHOD__, false);
8838          }          }
8839          //          //
# Line 7363  class instruction extends instruction_ge Line 9006  class instruction extends instruction_ge
9006          // 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
9007          // dites de TREATMENT.          // dites de TREATMENT.
9008          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
9009          // Définition des paramètres          $message = __('Erreur de paramétrage :');
9010          $p_objet = 'param_courriel_de_notification_commune_objet_depuis_instruction';          $erreurParametrage = false;
9011          $p_modele = 'param_courriel_de_notification_commune_modele_depuis_instruction';          // Récupération du paramétrage de la collectivité du dossier
         $p_courriel = 'param_courriel_de_notification_commune';  
         // Définition des variables de substitution  
9012          $id_di = $this->getVal('dossier');          $id_di = $this->getVal('dossier');
         $id_inst = $this->getVal($this->clePrimaire);  
         // Instanciation du DI  
9013          $di = $this->get_inst_dossier($id_di);          $di = $this->get_inst_dossier($id_di);
         // Récupération du paramétrage de la collectivité du dossier  
9014          $collectivite_di = $di->getVal('om_collectivite');          $collectivite_di = $di->getVal('om_collectivite');
9015          $params_mono = $this->f->getCollectivite($collectivite_di);          // Récupération de l'url permettant d'accèder à l'instruction et au dossier
9016          // Récupération du paramétrage de la collectivité multi          $urlAcces = $this->f->get_parametre_notification_url_acces($collectivite_di);
9017          $collectivite_multi = $this->f->get_idx_collectivite_multi();          if (empty($urlAcces) && empty(PATH_BASE_URL)) {
9018          $params_multi = $this->f->getCollectivite($collectivite_multi);              $erreurParametrage = true;
9019          // Vérification de l'objet (obligatoirement multi)              $message .= '<br>'.__("* l'url de notification n'est pas correctement paramétré");
9020          $objet = null;          }
9021          if (isset($params_multi[$p_objet]) === true  
9022              && $params_multi[$p_objet] !== '') {          // Récupération de la liste des mails
9023              $objet = $params_multi[$p_objet];          $adresses = $this->f->get_param_courriel_de_notification_commune($collectivite_di);
9024          }          if (empty($adresses)) {
9025          // Vérification du modèle mono en priorité              $erreurParametrage = true;
9026          $modele = null;              $message .= '<br>'.__("* aucun courriel valide de destinataire de la commune");
9027          if (isset($params_mono[$p_modele]) === true          }
9028              && $params_mono[$p_modele] !== '') {  
9029              $modele = $params_mono[$p_modele];          // Vérification du paramétrage des mails
9030                        $paramMail = $this->f->get_notification_commune_parametre_courriel_type($collectivite_di);
9031          }          if (empty($paramMail) || empty($paramMail['parametre_courriel_type_message'])) {
9032          // Sinon vérification du modèle multi              $erreurParametrage = true;
9033          if ($modele === null              $message .= '<br>'.__("* le modèle du courriel envoyé aux communes est vide");
9034              && isset($params_multi[$p_modele]) === true          }
9035              && $params_multi[$p_modele] !== '') {          if (empty($paramMail) || empty($paramMail['parametre_courriel_type_titre'])) {
9036              $modele = $params_multi[$p_modele];              $erreurParametrage = true;
9037          }              $message .= '<br>'.__("* l'objet du courriel envoyé aux communes est vide");
9038          // Vérification des adresses de courriel mono          }
9039          $courriels_valides = array();  
9040          $courriels_invalides = array();          // Si il y a des erreurs de paramétrage on ne déclenche pas la notification et
9041          if (isset($params_mono[$p_courriel]) === true          // un message a destination de l'utilisateur est affiché
9042              && $params_mono[$p_courriel] !== '') {          if ($erreurParametrage) {
9043              // Un mail par ligne              $message .= '<br>'.__("Veuillez contacter votre administrateur.");
9044              $adresses = explode("\n", $params_mono[$p_courriel]);              $this->addToMessage($message);
9045              // Vérification de la validité de chaque mail avec preg_match              return $this->end_treatment(__METHOD__, false);
             foreach ($adresses as $adresse) {  
                 $adresse = trim($adresse);  
                 if ($this->f->checkValidEmailAddress($adresse) === 1) {  
                     $courriels_valides[] = $adresse;  
                 } else {  
                     $courriels_invalides[] = $adresse;  
                 }  
             }  
9046          }          }
9047          // Vérification du paramétrage global :  
9048          // on stoppe le traitement si au moins un paramètre est incorrect          // Création d'un notification et de sa tâche associé pour chaque mail
9049          if ($objet === null          foreach ($adresses as $adresse) {
9050              || $modele === null              // Ajout de la notif et récupération de son id
9051              || count($courriels_valides) === 0              $destinataire = array(
9052              || count($courriels_invalides) > 0) {                  'destinataire' => $adresse,
9053              // On construit le message d'erreur adéquat                  'courriel' => $adresse
9054              $this->addToMessage(_('Erreur de paramétrage :'));              );
9055              if ($objet === null) {              $idNotif = $this->ajouter_notification(
9056                  $this->addToMessage(_("* l'objet du courriel envoyé aux communes est vide"));                  $this->getVal($this->clePrimaire),
9057              }                  $this->f->get_connected_user_login_name(),
9058              if ($modele === null) {                  $destinataire,
9059                  $this->addToMessage(_("* le modèle du courriel envoyé aux communes est vide"));                  $collectivite_di
9060              }              );
9061              if (count($courriels_valides) === 0) {              if ($idNotif === false) {
9062                  $this->addToMessage(_("* aucun courriel valide de destinataire de la commune"));                  $this->addToMessage(__("Veuillez contacter votre administrateur."));
9063                    return $this->end_treatment(__METHOD__, false);
9064              }              }
9065              if (count($courriels_invalides) > 0) {              // Création de la tache en lui donnant l'id de la notification
9066                  $courriels_invalides = implode(', ', $courriels_invalides);              $notification_by_task = $this->notification_by_task(
9067                  $this->addToMessage(_("* un ou plusieurs courriels des destinataires de la commune sont invalides : ").$courriels_invalides);                  $idNotif,
9068                    $this->getVal('dossier'),
9069                    'mail',
9070                    'notification_commune'
9071                );
9072                if ($notification_by_task === false) {
9073                    $this->addToMessage(__("Erreur lors de la préparation de la notification des communes."));
9074                    $this->addToMessage(__("Veuillez contacter votre administrateur."));
9075                    return $this->end_treatment(__METHOD__, false);
9076              }              }
             $this->addToMessage(_("Veuillez contacter votre administrateur."));  
             return $this->end_treatment(__METHOD__, false);  
         }  
         // Remplacement des variables de substitution  
         $objet = str_replace('<DOSSIER_INSTRUCTION>', $id_di, $objet);  
         $modele = $this->formater_modele($modele, $id_di, $id_inst);  
         // Exécution du traitement d'envoi du/des mail(s)  
         $fails = array();  
         foreach ($courriels_valides as $email) {  
             if ($this->f->sendMail(  
                 iconv("UTF-8", "CP1252", $objet),  
                 iconv("UTF-8", "CP1252", $modele),  
                 iconv("UTF-8", "CP1252", $email)) === false) {  
                 $fails[] = $email;  
             }  
         }  
         // Si échec message d'erreur et arrêt du traitement  
         if (count($fails) > 0) {  
             $fails = implode(', ', $fails);  
             $this->addToMessage(_("Erreur lors de l'envoi du courriel aux destinataires : ").$fails);  
             $this->addToMessage(_("Veuillez contacter votre administrateur."));  
             return $this->end_treatment(__METHOD__, false);  
9077          }          }
9078          // Ajout du log          $this->addToMessage(__('La commune a été notifiée.'));
         $this->setValFFromVal();  
         $val_inst = $this->valF;  
         $val_inst['mails_destinataires'] = implode(', ', $courriels_valides);  
         if ($this->add_log_to_dossier($id_inst, $val_inst) === false) {  
             $this->addToMessage(_("Erreur lors de la notification."));  
             $this->addToMessage(_("Veuillez contacter votre administrateur."));  
             return $this->end_treatment(__METHOD__, false);  
         }  
         // Message de validation  
         $this->addToMessage(_('La commune a été notifiée.'));  
9079          return $this->end_treatment(__METHOD__, true);          return $this->end_treatment(__METHOD__, true);
9080      }      }
9081    
9082      /**      /**
      * Formatte le corps du courriel notifié aux communes  
      *  
      * @param   string  $modele   template du modèle du courriel  
      * @param   string  $id_di    clé primaire du DI  
      * @param   string  $id_inst  clé primaire de l'instruction  
      * @return  string            corps du mail au format HTML  
      */  
     public function formater_modele($modele, $id_di, $id_inst) {  
         // Création du lien d'accès direct à l'instruction  
         $url_inst = PATH_BASE_URL.'app/index.php?module=form&direct_link=true&obj=dossier_instruction&action=3'.  
             '&direct_field=dossier&direct_form=instruction&direct_action=3&direct_idx='.$id_inst;  
         $url_inst = '<a href="'.$url_inst.'">'.$url_inst.'</a>';  
         // Remplacement des champs de fusion  
         $modele = str_replace('<DOSSIER_INSTRUCTION>', $id_di, $modele);  
         $modele = str_replace('<URL_INSTRUCTION>', $url_inst, $modele);  
         $modele = str_replace('<ID_INSTRUCTION>', $id_inst, $modele);  
         // Encodage HTML des sauts de ligne  
         $modele = preg_replace("/\r\n|\r|\n/",'<br/>',$modele);  
         //  
         return $modele;  
     }  
   
   
     /**  
9083       * Récupère l'instance de l'instructeur       * Récupère l'instance de l'instructeur
9084       *       *
9085       * @param integer $instructeur Identifiant de l'instructeur.       * @param integer $instructeur Identifiant de l'instructeur.
# Line 7665  class instruction extends instruction_ge Line 9248  class instruction extends instruction_ge
9248              'idx' => $this->getVal('dossier'),              'idx' => $this->getVal('dossier'),
9249          ));          ));
9250    
9251            //Instanciation de la classe electronicsignature
9252            $inst_es = $this->get_electronicsignature_instance();
9253            if ($inst_es === false) {
9254                $this->correct = false;
9255                return $this->end_treatment(__METHOD__, false);
9256            }
9257    
9258            // Vérifie si la notification se fait via l'application ou via le parapheur
9259            try {
9260                $notification_required = $inst_es->signer_notification_is_delegated();
9261            } catch(electronicsignature_connector_method_not_implemented_exception $_) {
9262                // Si la méthode n'existe pas, on considère que la notification est faite par le parapheur
9263                $notification_required = false;
9264            }
9265    
9266            // Si la notification est faite par l'application vérifie que l'adresse mail du
9267            // signataire est correcte. Si ce n'est pas le cas le document n'est pas envoyé
9268            // au parapheur car il ne sera pas accessible sans le lien transmis dans la
9269            // notification
9270            if ($notification_required === true) {
9271                $signer_mail = $inst_signataire_arrete->getVal('email');
9272                $signer_name = trim($inst_signataire_arrete->getVal('prenom').' '.$inst_signataire_arrete->getVal('nom'));
9273        
9274                $err_msg = __('Le document n\'a pas pu être envoyé en signature car ');
9275    
9276                if (empty($signer_mail)) {
9277                    $this->correct = false;
9278                    $err_detail = sprintf(__("l'email du signataire '%s' est vide."), $signer_name);
9279                    $this->addToMessage($err_msg.$err_detail);
9280                    $this->addToLog(__METHOD__.$err_msg.$err_detail.' Instruction : '.$this->getVal($this->clePrimaire), DEBUG_MODE);
9281                    return $this->end_treatment(__METHOD__, false);
9282                }
9283                if (! $this->f->checkValidEmailAddress($signer_mail)) {
9284                    $this->correct = false;
9285                    $err_detail = sprintf(__("l'email du signataire '%s' est invalide (%s)."), $signer_name, $signer_mail);
9286                    $this->addToMessage($err_msg.$err_detail);
9287                    $this->addToLog(__METHOD__.$err_msg.$err_detail.' Instruction : '.$this->getVal($this->clePrimaire), DEBUG_MODE);
9288                    return $this->end_treatment(__METHOD__, false);
9289                }
9290            }
9291    
9292          // Récupération du document à signer          // Récupération du document à signer
9293          $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));          $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));
9294          if ($file === OP_FAILURE) {          if ($file === OP_FAILURE) {
# Line 7681  class instruction extends instruction_ge Line 9305  class instruction extends instruction_ge
9305              "signataire_arrete_email" => $inst_signataire_arrete->getVal('email'),              "signataire_arrete_email" => $inst_signataire_arrete->getVal('email'),
9306              "signataire_arrete_nom" => $inst_signataire_arrete->getVal('nom'),              "signataire_arrete_nom" => $inst_signataire_arrete->getVal('nom'),
9307              "signataire_arrete_prenom" => $inst_signataire_arrete->getVal('prenom'),              "signataire_arrete_prenom" => $inst_signataire_arrete->getVal('prenom'),
9308              "date_limite_instruction" => $inst_dossier->getVal('incomplet_notifie') === 't' ? $inst_dossier->getVal('date_limite_incompletude') : $inst_dossier->getVal('date_limite'),              // Permet d'envoyer en signature l'instruction le jour de la date limite
9309                "date_limite_instruction" => $this->compute_date_limite(1) != null ? $this->compute_date_limite(1) : null,
9310              "dossier" => $this->getVal('dossier'),              "dossier" => $this->getVal('dossier'),
9311              "is_forced_view_files" => $is_forced_view_files,              "is_forced_view_files" => $is_forced_view_files,
9312              'commentaire_signature' => $is_forced_view_files === true ? __('relecture demandee.') : null              'commentaire_signature' => $is_forced_view_files === true ? __('relecture demandee.') : null
# Line 7697  class instruction extends instruction_ge Line 9322  class instruction extends instruction_ge
9322          $metadonnee_dossier['titre_document'] = $this->getDocumentTitre();          $metadonnee_dossier['titre_document'] = $this->getDocumentTitre();
9323    
9324          $metadonnee_dossier['url_di'] = sprintf(          $metadonnee_dossier['url_di'] = sprintf(
9325              '%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',              '%1$sapp/index.php?module=form&direct_link=true&obj=dossier_instruction&action=3&idx=%2$s&direct_field=dossier&direct_form=document_numerise&direct_action=4&direct_idx=%2$s',
9326              $this->f->get_param_base_path_metadata_url_di() !== null ? $this->f->get_param_base_path_metadata_url_di() : PATH_BASE_URL,              $this->f->get_param_base_path_metadata_url_di() !== null ? $this->f->get_param_base_path_metadata_url_di() : PATH_BASE_URL,
9327              $this->getVal($this->clePrimaire)              $this->getVal('dossier')
9328          );          );
9329    
9330          $optional_data = null;          $optional_data = null;
# Line 7718  class instruction extends instruction_ge Line 9343  class instruction extends instruction_ge
9343              }              }
9344          }          }
9345    
         //Instanciation de la classe electronicsignature  
         $inst_es = $this->get_electronicsignature_instance();  
         if ($inst_es === false) {  
             $this->correct = false;  
             return $this->end_treatment(__METHOD__, false);  
         }  
   
9346          // Appel de la méthode de l'abstracteur send_for_signature()          // Appel de la méthode de l'abstracteur send_for_signature()
9347          // Cette méthode doit retourner un tableau de valeur          // Cette méthode doit retourner un tableau de valeur
9348          try {          try {
# Line 7747  class instruction extends instruction_ge Line 9365  class instruction extends instruction_ge
9365          $valF['commentaire_signature'] = isset($result['commentaire_signature']) == true ? $result['commentaire_signature'] : null;          $valF['commentaire_signature'] = isset($result['commentaire_signature']) == true ? $result['commentaire_signature'] : null;
9366          $valF['date_envoi_signature'] = date("Y-m-d", strtotime($result['date_envoi_signature']));          $valF['date_envoi_signature'] = date("Y-m-d", strtotime($result['date_envoi_signature']));
9367          $valF['historique_signature'] = $this->get_updated_historique_signature($result);          $valF['historique_signature'] = $this->get_updated_historique_signature($result);
9368            $valF['parapheur_lien_page_signature'] = isset($result['signature_page_url']) ? $result['signature_page_url'] : null;
9369          $ret = $this->modifier($valF);          $ret = $this->modifier($valF);
9370    
9371          if ($ret === false) {          if ($ret === false) {
# Line 7757  class instruction extends instruction_ge Line 9375  class instruction extends instruction_ge
9375              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
9376          }          }
9377    
9378            // Notification du signataire
9379            if ($notification_required === true) {
9380                if ($this->notify_signer($signer_name, $signer_mail, $data['om_utilisateur_nom']) === false) {
9381                    $msg = __("Une erreur s'est produite lors de la notification du signataire \"%s (%s)\". Annulation de l'envoi pour signature du document%s.");
9382                    $this->addToMessage(sprintf($msg, $signer_name, $signer_mail, ''));
9383                    $this->addToLog(sprintf($msg, $signer_name, $signer_mail, ' : '.$this->getVal($this->clePrimaire)), DEBUG_MODE);
9384                    // Met à jour les valeurs de l'objet courant pour prendre en compte les modifications faites
9385                    // precedemment
9386                    $this->init_record_data($this->getVal($this->clePrimaire));
9387                    $this->annuler_envoi_en_signature();
9388                    $this->correct = false;
9389                    return $this->end_treatment(__METHOD__, true);
9390                }
9391            }
9392    
9393          // Message          // Message
9394          $this->addToMessage(__("Le document a été envoyé pour signature dans le parapheur."));          $this->addToMessage(__("Le document a été envoyé pour signature dans le parapheur."));
9395          if (array_key_exists('signature_page_url', $result) === true) {          if ($this->f->is_option_enabled('option_afficher_lien_parapheur') === true
9396                && array_key_exists('signature_page_url', $result) === true) {
9397              $this->addToMessage(sprintf(              $this->addToMessage(sprintf(
9398                  '<br> > <a href="%1$s" title="%2$s" target="_blank">%2$s</a>',                  '<br> > <a href="%1$s" title="%2$s" target="_blank">%2$s</a>',
9399                  $result['signature_page_url'],                  $result['signature_page_url'],
9400                  __("Signez directement le document")                  __("Signez directement le document")
9401              ));              ));
9402          }          }
9403            if ($notification_required !== true) {
9404                $this->addToMessage(__("L'envoi de la notification au signataire est effectué par la plateforme."));
9405            }
9406    
9407          // Tout s'est bien passé, on termine le traitement          // Tout s'est bien passé, on termine le traitement
9408          return $this->end_treatment(__METHOD__, true);          return $this->end_treatment(__METHOD__, true);
9409      }      }
9410    
9411      /**      /**
9412         * Notifie le signataire d'un document à signer.
9413         * Gère l'affichage des messages à destination de l'utilisateur selon l'état du traitement.
9414         * En cas d'erreur ajoute une ligne dans les logs de l'application.
9415         *
9416         * @param  string  $signer_name         Nom du signataire
9417         * @param  string  $signer_mail         Mail du signataire
9418         * @param  string  $user_name           Nom de l'utilisateur openADS courant
9419         *
9420         * @return boolean  true si succés, false si erreur
9421         */
9422        protected function notify_signer($signer_name, $signer_mail, $user_name) {
9423            // message d'erreur
9424            $err_msg_log = sprintf(
9425                __("Échec de la notification du signataire \"%s (%s)\" lors de l'envoi au parapaheur du document de l'instruction : %s"),
9426                $signer_name,
9427                $signer_mail,
9428                $this->getVal($this->clePrimaire)
9429            );
9430            $err_msg = sprintf(
9431                '%s %s (%s)"',
9432                __("Échec de la notification du signataire"),
9433                $signer_name,
9434                $signer_mail
9435            );
9436    
9437            // vérification des informations requises
9438            if (empty($signer_name)) {
9439                $err_detail = __("le nom du signataire est vide");
9440                $this->addToLog(__METHOD__.', '.$err_msg_log.', '.$err_detail, DEBUG_MODE);
9441                $this->addToMessage($err_msg.', '.$err_detail);
9442                return false;
9443            }
9444            if (empty($signer_mail)) {
9445                $err_detail = __("le courriel du signataire est vide");
9446                $this->addToLog(__METHOD__.', '.$err_msg_log.', '.$err_detail, DEBUG_MODE);
9447                $this->addToMessage($err_msg.', '.$err_detail);
9448                return false;
9449            }
9450            if (empty($this->getVal('dossier'))) {
9451                $err_detail = __("l'identifiant du dossier est vide");
9452                $this->addToLog(__METHOD__.', '.$err_msg_log.', '.$err_detail, DEBUG_MODE);
9453                $this->addToMessage($err_msg.', '.$err_detail);
9454                return false;
9455            }
9456    
9457            // ajout de la notification à la liste des notifications de l'instruction
9458            $instruction_id = $this->getVal($this->clePrimaire);
9459            $inst_notif = $this->f->get_inst__om_dbform(array(
9460                "obj" => "instruction_notification",
9461                "idx" => "]",
9462            ));
9463            $notif_val = array(
9464                'instruction_notification' => null,
9465                'instruction' => $instruction_id,
9466                'automatique' => true,
9467                'emetteur' => $user_name,
9468                'date_envoi' => null,
9469                'destinataire' => "$signer_name <$signer_mail>",
9470                'courriel' => $signer_mail,
9471                'date_premier_acces' => null,
9472                'statut' => '',
9473                'commentaire' => ''
9474            );
9475            $add_notif = $inst_notif->ajouter($notif_val);
9476            if ($add_notif === false) {
9477                $err_detail = __("Échec de l'ajout de la notification.");
9478                $this->addToLog(__METHOD__.' '.$err_msg_log.'. '.$err_detail.' Notification : '.var_export($notif_val, true), DEBUG_MODE);
9479                $this->addToMessage($err_msg);
9480                return false;
9481            }
9482            $notification_id = $inst_notif->getVal($inst_notif->clePrimaire);
9483    
9484            // ajout d'une tâche de notification (envoi du mail)
9485            $notification_task = $this->notification_by_task(
9486                $notification_id,
9487                $this->getVal('dossier'),
9488                'mail',
9489                'notification_signataire'
9490            );
9491            if ($notification_task === false) {
9492                $err_detail = sprintf(
9493                    __("Échec de l'ajout de la tâche de notification (notification %s)."),
9494                    $notification_id);
9495                $this->addToLog(__METHOD__.' '.$err_msg_log.'. '.$err_detail, DEBUG_MODE);
9496                $this->addToMessage($err_msg);
9497                return false;
9498            }
9499    
9500            // Vérification de la réussite de l'envoi du mail
9501            // Fais une requête pour récupérer la liste des notifications de signataire faites par mail
9502            // et associées à l'instruction en cours. Récupère uniquement la dernière qui doit être celle
9503            // qui viens d'être créée.
9504            // Si la tâche d'envoi du mail est en erreur alors on considère que l'envoi du mail a échoué.
9505            $qres = $this->f->get_one_result_from_db_query(
9506                sprintf(
9507                    'SELECT
9508                        state
9509                    FROM
9510                        %1$stask
9511                    WHERE
9512                        type = \'notification_signataire\'
9513                        AND category = \'mail\'
9514                        AND dossier = \'%2$s\'
9515                    ORDER BY
9516                        task DESC
9517                    LIMIT 1',
9518                    DB_PREFIXE,
9519                    $this->f->db->escapeSimple($this->getVal('dossier'))
9520                ),
9521                array(
9522                    'origin' => __METHOD__
9523                )
9524            );
9525            if ($qres['result'] === 'error') {
9526                $err_detail = sprintf(
9527                    __("Échec de l'envoi du mail de notification (notification %s)."),
9528                    $notification_id);
9529                $this->addToLog(__METHOD__.' '.$err_msg_log.'. '.$err_detail, DEBUG_MODE);
9530                $this->addToMessage($err_msg);
9531                return false;
9532            }
9533    
9534            // succès de la planification de la notification
9535            $this->addToMessage(sprintf(
9536                __('Le signataire "%s (%s)" sera notifié prochainement'),
9537                $signer_name,
9538                $signer_mail));
9539            return true;
9540        }
9541    
9542        /**
9543         * Permet de récupérer la bonne date limite en fonction de si l'instruction
9544         * est en incomplet notifié ou non.
9545         * On peut ajouter des jours à cette date grâce au paramètre "delay".
9546         * Cette fonction est utilisée dans un cas spécifique où on veut envoyer
9547         * l'instruction en signature le jour de la date limite.
9548         *
9549         * @param int $delay Le nombre de jour à ajouter à la date limite.
9550         *
9551         * @return string $date_limite la date limite calculé ou false
9552         */
9553        private function compute_date_limite($delay) {
9554            // Instanciation de l'objet dossier
9555            $inst_dossier = $this->f->get_inst__om_dbform(array(
9556                'obj' => 'dossier',
9557                'idx' => $this->getVal('dossier'),
9558            ));
9559    
9560            $date_to_compute = null;
9561            if ($inst_dossier->getVal('incomplet_notifie') === 't') {
9562              $date_to_compute = $inst_dossier->getVal('date_limite_incompletude');
9563            } else {
9564              $date_to_compute = $inst_dossier->getVal('date_limite');
9565            }
9566            if ($date_to_compute != null) {
9567                return date("Y-m-d", strtotime($date_to_compute."+ $delay days"));
9568            }
9569    
9570            return null;
9571        }
9572    
9573        /**
9574       * Permet de récupérer la traduction de la valeur de statut_signature       * Permet de récupérer la traduction de la valeur de statut_signature
9575       *       *
9576       * @return string la valeur de statut_signature traduite | false       * @return string la valeur de statut_signature traduite | false
# Line 7819  class instruction extends instruction_ge Line 9618  class instruction extends instruction_ge
9618    
9619          $date_to_convert = array(          $date_to_convert = array(
9620              'date_envoi_signature' => $historique_signature_values['date_envoi_signature'],              'date_envoi_signature' => $historique_signature_values['date_envoi_signature'],
9621              'date_limite_instruction' => $historique_signature_values['date_limite_instruction'],              'date_limite_instruction' => $this->compute_date_limite(0),
9622              'date_retour_signature' => $historique_signature_values['date_retour_signature']              'date_retour_signature' => $historique_signature_values['date_retour_signature']
9623          );          );
9624    
# Line 7862  class instruction extends instruction_ge Line 9661  class instruction extends instruction_ge
9661                    
9662          return json_encode($historique_signature_value_tab, JSON_HEX_APOS);          return json_encode($historique_signature_value_tab, JSON_HEX_APOS);
9663      }      }
9664        
9665        /**
9666         * TREATMENT - annuler_envoi_en_signature
9667         *
9668         * Permet d'annuler l'envoi du document de l'instruction au parapheur pour signature
9669         *
9670         * @return boolean true si l'annulation a été effectué avec succès false sinon
9671         */
9672        function annuler_envoi_en_signature() {
9673            $this->begin_treatment(__METHOD__);
9674            $this->correct = true;
9675    
9676            //Instanciation de la classe electronicsignature
9677            $inst_es = $this->get_electronicsignature_instance();
9678            if ($inst_es === false) {
9679                $this->correct = false;
9680                return $this->end_treatment(__METHOD__, false);
9681            }
9682    
9683            $data = array();
9684            if (! empty($this->getVal('id_parapheur_signature'))) {
9685                $data['id_parapheur_signature'] = $this->getVal('id_parapheur_signature');
9686            } else {
9687                $this->correct = false;
9688                $this->addToMessage(__("Il n'y a pas d'identifiant de parapheur."));
9689                return $this->end_treatment(__METHOD__, false);
9690            }
9691    
9692            // Appel de la méthode de l'abstracteur cancel_send_for_signature()
9693            // Cette méthode doit retourner un tableau de valeur
9694            try {
9695                $result = $inst_es->cancel_send_for_signature($data);
9696            }  catch (electronicsignature_exception $e) {
9697                $this->handle_electronicsignature_exception($e);
9698                return $this->end_treatment(__METHOD__, false);
9699            }
9700    
9701            // Après avoir reçu le résultat du parapheur, il faut mettre à jour les champs
9702            $valF = array();
9703    
9704            // Pour appeler la fonction modifier il faut traiter tous les champs de l'objet
9705            foreach($this->champs as $identifiant => $champ) {
9706                $valF[$champ] = $this->val[$identifiant];
9707            }
9708            // On fait ensuite nos modifications spécifiques
9709            $valF['id_parapheur_signature'] = null;
9710            $valF['statut_signature'] = $result['statut'];
9711            $valF['commentaire_signature'] = isset($result['commentaire_signature']) == true ? $result['commentaire_signature'] : null;
9712            $valF['date_envoi_signature'] = null;
9713            $valF['historique_signature'] = $this->get_updated_historique_signature($result);
9714    
9715            $ret = $this->modifier($valF);
9716    
9717            if ($ret === false) {
9718                $this->correct = false;
9719                $this->addToMessage(__("Une erreur est survenue lors de la mise à jour des champs."));
9720                // Termine le traitement
9721                return $this->end_treatment(__METHOD__, false);
9722            }
9723    
9724            // Message
9725            $this->addToMessage(__("L'annulation a été effectuée avec succès."));
9726    
9727            // Tout s'est bien passé, on termine le traitement
9728            return $this->end_treatment(__METHOD__, true);
9729        }
9730    
9731    
9732      /**      /**
# Line 7870  class instruction extends instruction_ge Line 9735  class instruction extends instruction_ge
9735       * @return array sinon false en cas d'erreur       * @return array sinon false en cas d'erreur
9736       */       */
9737      protected function get_historique_signature_decoded() {      protected function get_historique_signature_decoded() {
9738          $val = $this->getVal('historique_signature');          $val = str_replace("'", '"', $this->getVal('historique_signature'));
9739          if ($val === '') {          if ($val === '' || $val == 'false') {
9740              $val = json_encode(array());              $val = json_encode(array());
9741          }          }
9742          if($this->isJson($val) === false) {          if($this->isJson($val) === false) {
# Line 7883  class instruction extends instruction_ge Line 9748  class instruction extends instruction_ge
9748      /**      /**
9749       * Récupère les informations à afficher dans le tableau de suivi à l'aide       * Récupère les informations à afficher dans le tableau de suivi à l'aide
9750       * d'une requête sql. Stocke ces informations dans un tableau.       * d'une requête sql. Stocke ces informations dans un tableau.
9751       * Converti le tableau au format json et renvoi le json obtenu       * Converti le tableau au format json et renvoi le json obtenu.
9752       *       *
9753         * Pour identifier quel suivi est affiché (notification des demandeurs, des services ou
9754         * de tiers) ce sont les tâches liées aux notifications qui sont utilisés.
9755         * La clause where de la requête est construite à partir du tableau contenant les types
9756         * de tâches fourni en paramètre.
9757         * Il est également possible d'afficher les notifications n'étant pas lié à des tâches.
9758         *
9759         * Si le suivi concerne la notification des demandeurs via le portail citoyen,
9760         * la date de premier accès ne sera pas affichée.
9761         *
9762         * @param array liste des tâches permettant d'identifier quelles notification afficher
9763         * @param boolean permet d'afficher les notifications non liées à des tâches
9764       * @return json       * @return json
9765       */       */
9766      protected function get_json_suivi_notification() {      public function get_json_suivi_notification($typeTache, $nonLieTache = false) {
9767          $valSuivi = array();          $whereTypeTache = '';
9768            $sqlTaskNull = 'INNER';
9769    
9770          // Liste des champs à afficher. Permet également la traduction des noms de colonnes.          // Liste des champs à afficher. Permet également la traduction des noms de colonnes.
9771          $listeChampsTrad = array(          $listeChampsTrad = array(
9772              __('emetteur'),              __('emetteur'),
# Line 7896  class instruction extends instruction_ge Line 9774  class instruction extends instruction_ge
9774              __('destinataire'),              __('destinataire'),
9775              __('date_premier_acces'),              __('date_premier_acces'),
9776              __('instruction'),              __('instruction'),
9777                __('annexes'),
9778              __('statut'),              __('statut'),
9779              __('commentaire')              __('commentaire')
9780          );          );
# Line 7905  class instruction extends instruction_ge Line 9784  class instruction extends instruction_ge
9784              'destinataire',              'destinataire',
9785              'date_premier_acces',              'date_premier_acces',
9786              'instruction',              'instruction',
9787                'annexes',
9788              'statut',              'statut',
9789              'commentaire'              'commentaire'
9790          );          );
9791    
9792            // Défini si on veux que la requête récupère également les notifications qui n'ont pas
9793            // de tâches associées. C'est le cas pour les notifications de demandeurs lorsque la
9794            // notification du demandeur principal n'a pas pu être envoyée à cause d'un mauvais
9795            // paramétrage
9796            if(is_bool($nonLieTache) && $nonLieTache === true) {
9797                $sqlTaskNull = 'LEFT';
9798            }
9799            // Prépare la clause where pour ne récupérer que les notifications liées à certain type de tâches
9800            // Permet de différencier les notifications des demandeurs de celle des services et de celles des
9801            // tiers consulté
9802            if (is_array($typeTache) && $typeTache != array()) {
9803                if (is_array($typeTache)) {
9804                    $whereTypeTache = sprintf(
9805                        'AND (task.type IN (%1$s))',
9806                        "'".implode("', '", $typeTache)."'"
9807                    );
9808                }
9809                // La date de premier accès n'a pas besoin d'être renseigné pour
9810                // les notifications des demandeurs via le portail citoyen.
9811                // Les notifications des demandeurs sont liés à 3 types de tâches
9812                // notification_recepisse, notification_instruction, notification_decision
9813                // Si le suivi de la notification concerne un de ces types de tâches on
9814                // considère que c'est une notification de demandeurs.
9815                // Dans ce cas on vérifie si cette notification est paramétrée pour passer
9816                // via le portail. Par défaut si rien n'est paramétré on considère que la
9817                // notification est faite via le portail
9818                if ((in_array('notification_recepisse', $typeTache) ||
9819                in_array('notification_instruction', $typeTache) ||
9820                in_array('notification_decision', $typeTache))) {
9821                    $dossier = $this->getVal('dossier');
9822                    $collectivite_di = $this->get_dossier_instruction_om_collectivite($dossier);
9823                    $modeNotification = $this->f->get_param_option_notification($collectivite_di);
9824                    if ($modeNotification === PORTAL) {
9825                        $listeChamps = array(
9826                            'emetteur',
9827                            'date_envoi',
9828                            'destinataire',
9829                            'instruction',
9830                            'annexes',
9831                            'statut',
9832                            'commentaire'
9833                        );
9834                    }
9835                }
9836                // Il n'y a pas d'annexe pour la notification des communes donc pas besoin
9837                // de les afficher dans le suivi
9838                if (in_array('notification_depot_demat', $typeTache)) {
9839                    $listeChamps = array(
9840                        'emetteur',
9841                        'date_envoi',
9842                        'destinataire',
9843                        'instruction',
9844                        'statut',
9845                        'commentaire'
9846                    );
9847                }
9848            }
9849    
9850            $valSuivi = array();
9851          // Récupération des infos nécessaires à l'affichage du tableau          // Récupération des infos nécessaires à l'affichage du tableau
9852          $sql = sprintf(          $sql = sprintf(
9853              'SELECT              'SELECT DISTINCT
9854                  instruction_notification.instruction_notification,                  instruction_notification.instruction_notification,
9855                    -- Affiche la mention automatique avec le nom de l emetteur si la notification a été envoyé automatiquement
9856                  CASE WHEN instruction_notification.automatique = TRUE                  CASE WHEN instruction_notification.automatique = TRUE
9857                      THEN TRIM(CONCAT(instruction_notification.emetteur, \' \', \'(automatique)\'))                      THEN TRIM(CONCAT(instruction_notification.emetteur, \' \', \'(automatique)\'))
9858                      ELSE instruction_notification.emetteur                      ELSE instruction_notification.emetteur
# Line 7923  class instruction extends instruction_ge Line 9863  class instruction extends instruction_ge
9863                  evenement.libelle as instruction,                  evenement.libelle as instruction,
9864                  instruction_notification.statut,                  instruction_notification.statut,
9865                  instruction_notification.commentaire,                  instruction_notification.commentaire,
9866                  instruction_notification_document.instruction as instruction_annexe                  annexes.instruction_annexe as annexes
9867              FROM              FROM
9868                  %1$sinstruction_notification                  %1$sinstruction_notification
9869                  LEFT JOIN %1$sinstruction                  LEFT JOIN %1$sinstruction
# Line 7933  class instruction extends instruction_ge Line 9873  class instruction extends instruction_ge
9873                  LEFT JOIN %1$sinstruction_notification_document                  LEFT JOIN %1$sinstruction_notification_document
9874                      ON instruction_notification.instruction_notification = instruction_notification_document.instruction_notification                      ON instruction_notification.instruction_notification = instruction_notification_document.instruction_notification
9875                      AND instruction_notification_document.annexe = true                      AND instruction_notification_document.annexe = true
9876                    -- Récupère les tâches liées au notification pour pouvoir par la suite identifier le type de notification
9877                    %4$s JOIN %1$stask
9878                        ON instruction_notification.instruction_notification::CHARACTER VARYING = task.object_id
9879                            %3$s
9880                    -- Récupération de la liste des annexes sous la forme d une liste
9881                    LEFT JOIN (
9882                        SELECT
9883                            instruction_notification,
9884                            -- Récupère la liste des annexes de la notification
9885                            -- sous la forme d un json pour récupérer toutes les informatiosn nécessaire
9886                            -- à l affichage du lien vers les annexes
9887                            CONCAT(
9888                                \'[\',
9889                                STRING_AGG(
9890                                    -- Affiche le nom du fichier selon le type de document/pièce
9891                                    CASE
9892                                        WHEN instruction_notification_document.document_type = \'instruction\'
9893                                            THEN CONCAT(
9894                                                    \'{
9895                                                        "obj" : "instruction",
9896                                                        "champs" : "om_fichier_instruction",
9897                                                        "label" : "\', evenement.libelle, \'",
9898                                                        "id" : "\', instruction.instruction,\'"
9899                                                    }\'
9900                                                )
9901                                        WHEN instruction_notification_document.document_type = \'consultation\'
9902                                            THEN CONCAT(
9903                                                    \'{
9904                                                        "obj" : "consultation",
9905                                                        "champs" : "fichier",
9906                                                        "label" : "\', CONCAT_WS( \' - \', \'Avis\', service.libelle, to_char(consultation.date_retour,\'DD/MM/YYYY\')), \'",
9907                                                        "id" : "\', consultation.consultation, \'"
9908                                                    }\'
9909                                                )
9910                                    ELSE
9911                                        CONCAT(
9912                                            \'{
9913                                                "obj" : "document_numerise",
9914                                                "champs" : "uid",
9915                                                "label" : "\', document_numerise.nom_fichier, \' - \', document_numerise_type.libelle, \'",
9916                                                "id" : "\', document_numerise.document_numerise,\'"
9917                                            }\'
9918                                        )
9919                                    END,
9920                                    \', \'),
9921                                \']\'
9922                            ) AS instruction_annexe
9923                        FROM
9924                            %1$sinstruction_notification_document
9925                            LEFT JOIN %1$sinstruction
9926                                ON instruction_notification_document.instruction = instruction.instruction
9927                            LEFT JOIN %1$sevenement
9928                                ON instruction.evenement = evenement.evenement
9929                            LEFT JOIN %1$sconsultation
9930                                ON instruction_notification_document.document_id = consultation.consultation
9931                            LEFT JOIN %1$sservice
9932                                ON consultation.service = service.service
9933                            LEFT JOIN %1$sdocument_numerise
9934                                ON instruction_notification_document.document_id = document_numerise.document_numerise
9935                            LEFT JOIN %1$sdocument_numerise_type
9936                                ON document_numerise.document_numerise_type = document_numerise_type.document_numerise_type
9937                        WHERE
9938                            instruction_notification_document.annexe = \'t\'
9939                        GROUP BY
9940                            instruction_notification
9941                    ) AS annexes
9942                        ON
9943                            annexes.instruction_notification = instruction_notification.instruction_notification
9944              WHERE              WHERE
9945                  instruction.instruction = %2$s                  instruction.instruction = %2$s
9946              ORDER BY              ORDER BY
9947                  date_envoi ASC, instruction_notification.destinataire ASC',                  date_envoi ASC, instruction_notification.destinataire ASC',
9948              DB_PREFIXE,              DB_PREFIXE,
9949              $this->getVal('instruction')              intval($this->getVal('instruction')),
9950                $whereTypeTache,
9951                $sqlTaskNull
9952            );
9953            $qres = $this->f->get_all_results_from_db_query($sql, array(
9954                    "origin" => __METHOD__
9955                )
9956          );          );
9957          $res = $this->f->db->query($sql);          // Préparation du lien de téléchargement des annexes
9958          $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);          $htmlList =
9959          $this->f->isDatabaseError($res);              '<style>
9960                    #content .gridjs-td a.lien_annexe {
9961                        text-decoration : underline dotted 1px;
9962                    }
9963                    #content a.lien_annexe:hover {
9964                        text-decoration : underline solid 1px;
9965                        color : #46aede;
9966                    }
9967                    ol {padding-left : 10px;}
9968                </style>
9969                <ol>%1$s</ol>';
9970            $lienTelechargement =
9971            '<a class="lien_annexe" href="../app/index.php?module=form&amp;snippet=file&amp;obj=%1$s&amp;champ=%2$s&amp;id=%3$s" target="blank" title="%4$s">
9972                Annexe
9973            </a>';
9974          // Stockage des infos de chaque notification dans un tableau          // Stockage des infos de chaque notification dans un tableau
9975          while( $row =& $res->fetchrow(DB_FETCHMODE_ASSOC) ) {          foreach ($qres['result'] as $row) {
9976              $valNotif = array();              $valNotif = array();
9977              foreach($listeChamps as $champ) {              foreach($listeChamps as $champ) {
9978                  $valNotif[$champ] = $row[$champ];                  $valNotif[$champ] = $row[$champ];
# Line 7954  class instruction extends instruction_ge Line 9982  class instruction extends instruction_ge
9982                      && $row[$champ] !== '') {                      && $row[$champ] !== '') {
9983                      //                      //
9984                      $valNotif[$champ] = date('d/m/Y H:i:s', strtotime($row[$champ]));                      $valNotif[$champ] = date('d/m/Y H:i:s', strtotime($row[$champ]));
9985                    } else if ($champ === 'annexes') {
9986                        $listeAnnexe = '';
9987                        $infoAnnexes = json_decode($row[$champ], true);
9988                        if (! empty($infoAnnexes) && json_last_error() === JSON_ERROR_NONE) {
9989                            // A partir des infos récupérées prépare le code html du lien vers chacune
9990                            // des annexes et ajoute un élément de liste par annexe
9991                            foreach($infoAnnexes as $annexe) {
9992                                $listeAnnexe .= sprintf(
9993                                    '<li>%s</li>',
9994                                    sprintf($lienTelechargement,
9995                                        $annexe['obj'],
9996                                        $annexe['champs'],
9997                                        $annexe['id'],
9998                                        $annexe['label']
9999                                    )
10000                                );
10001                            }
10002                            // Construction de la liste des annexes
10003                            $valNotif[$champ] = sprintf(
10004                                $htmlList,
10005                                $listeAnnexe
10006                            );
10007                        }
10008                  }                  }
10009              }              }
             if ($row['instruction_annexe'] !== null && $row['instruction_annexe'] !== '') {  
                 $inst_instruction = $this->f->get_inst__om_dbform(array(  
                     "obj" => "instruction",  
                     "idx" => $row['instruction_annexe'],  
                 ));  
                 $inst_evenement = $inst_instruction->get_inst_evenement();  
                 $lienAnnexe = ' ('.$inst_evenement->getVal('libelle').')';  
                 $valNotif['instruction'] .= $lienAnnexe;  
             }  
10010              array_push($valSuivi, $valNotif);              array_push($valSuivi, $valNotif);
10011          }          }
10012    
# Line 8060  class instruction extends instruction_ge Line 10102  class instruction extends instruction_ge
10102                  DB_AUTOQUERY_UPDATE,                  DB_AUTOQUERY_UPDATE,
10103                  $this->getCle($this->getVal($this->clePrimaire))                  $this->getCle($this->getVal($this->clePrimaire))
10104              );              );
10105              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($instr_val, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($this->clePrimaire)."\");", DEBUG_MODE);              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($instr_val, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($this->clePrimaire)."\");", VERBOSE_MODE);
10106              if ($this->f->isDatabaseError($res, true) === true) {              if ($this->f->isDatabaseError($res, true) === true) {
10107                  $this->addToMessage(sprintf('%s %s',                  $this->addToMessage(sprintf('%s %s',
10108                      __("Une erreur s'est produite lors de la mise à jour de l'instruction."),                      __("Une erreur s'est produite lors de la mise à jour de l'instruction."),
# Line 8145  class instruction extends instruction_ge Line 10187  class instruction extends instruction_ge
10187          return $val;          return $val;
10188      }      }
10189    
10190        /**
10191         * Permet de récupérer l'identifiant de l'instruction sur le dossier, ayant
10192         * comme événement lié le suivant définit dans l'événement de l'instruction
10193         * instanciée.
10194         *
10195         * @param  string  $next_type   Correspond aux trois déclenchement automatique
10196         *                              de création d'instruction paramétré sur un événement.
10197         * @param  integer $instruction Identifiant de l'instruction à instancier.
10198         * @return mixed                Identifiant de l'instruction recherchée ou false.
10199         */
10200      public function get_related_instructions_next($next_type = 'retour_signature', $instruction = null) {      public function get_related_instructions_next($next_type = 'retour_signature', $instruction = null) {
10201          if (in_array($next_type, array('retour_signature', 'retour_ar', 'suivant_tacite', )) === false) {          if (in_array($next_type, array('retour_signature', 'retour_ar', 'suivant_tacite', )) === false) {
10202              return false;              return false;
# Line 8163  class instruction extends instruction_ge Line 10215  class instruction extends instruction_ge
10215              $evenement = $inst->getVal('evenement');              $evenement = $inst->getVal('evenement');
10216              $dossier = $inst->getVal('dossier');              $dossier = $inst->getVal('dossier');
10217          }          }
10218          //          // Récupération de l'identifiant de l'événement paramétré comme suivant
10219          $query = sprintf('          // sur l'instruction instanciée
10220              SELECT evenement_%3$s          $qres = $this->f->get_one_result_from_db_query(
10221              FROM %1$sevenement              sprintf(
10222              WHERE evenement = %2$s                  'SELECT
10223              ',                      evenement_%3$s
10224              DB_PREFIXE,                  FROM
10225              $evenement,                      %1$sevenement
10226              $next_type                  WHERE
10227                        evenement = %2$s',
10228                    DB_PREFIXE,
10229                    intval($evenement),
10230                    $next_type
10231                ),
10232                array(
10233                    "origin" => __METHOD__,
10234                    "force_return" => true,
10235                )
10236          );          );
10237          $res = $this->f->get_one_result_from_db_query($query, true);          if ($qres["code"] !== "OK") {
         if ($res['code'] === 'KO') {  
10238              return false;              return false;
10239          }          }
10240          $ev_next = $res['result'];          $ev_next = $qres["result"];
10241          //          // Récupération de l'instruction dans le dossier utilisant l'événement
10242          $query = sprintf('          // suivant identifié dans la requête précédente
10243              SELECT MAX(instruction.instruction) as instruction          $qres = $this->f->get_one_result_from_db_query(
10244              FROM %1$sinstruction              sprintf(
10245              WHERE dossier = \'%3$s\'                  'SELECT
10246                  AND evenement = %2$s                      MAX(instruction.instruction) as instruction
10247              ',                  FROM
10248              DB_PREFIXE,                      %1$sinstruction
10249              $ev_next,                  WHERE
10250              $dossier                      dossier = \'%3$s\'
10251                        AND evenement = %2$s',
10252                    DB_PREFIXE,
10253                    intval($ev_next),
10254                    $this->f->db->escapeSimple($dossier)
10255                ),
10256                array(
10257                    "origin" => __METHOD__,
10258                    "force_return" => true,
10259                )
10260          );          );
10261          $res = $this->f->get_one_result_from_db_query($query, true);          if ($qres["code"] !== "OK") {
         if ($res['code'] === 'KO') {  
10262              return false;              return false;
10263          }          }
10264          //          return $qres["result"];
         return $res['result'];  
10265      }      }
10266    
10267      public function get_related_instructions($instruction = null) {      public function get_related_instructions($instruction = null) {
# Line 8213  class instruction extends instruction_ge Line 10280  class instruction extends instruction_ge
10280              $dossier = $inst->getVal('dossier');              $dossier = $inst->getVal('dossier');
10281          }          }
10282          //          //
10283          $query = sprintf('          $qres = $this->f->get_one_result_from_db_query(
10284              SELECT evenement              sprintf(
10285              FROM %1$sevenement                  'SELECT
10286              WHERE evenement_retour_ar = %2$s                      evenement
10287                  OR evenement_retour_signature = %2$s                  FROM
10288              ',                      %1$sevenement
10289              DB_PREFIXE,                  WHERE
10290              $evenement                      evenement_retour_ar = %2$s
10291                        OR evenement_retour_signature = %2$s',
10292                    DB_PREFIXE,
10293                    intval($evenement)
10294                ),
10295                array(
10296                    "origin" => __METHOD__,
10297                    "force_return" => true,
10298                )
10299          );          );
10300          $res = $this->f->get_one_result_from_db_query($query, true);          if ($qres["code"] !== "OK") {
         if ($res['code'] === 'KO') {  
10301              return false;              return false;
10302          }          }
10303          $ev_parent = $res['result'];          $ev_parent = $qres["result"];
10304          //          //
10305          $query = sprintf('          $qres = $this->f->get_one_result_from_db_query(
10306              SELECT MAX(instruction.instruction) as instruction              sprintf(
10307              FROM %1$sinstruction                  'SELECT
10308              WHERE dossier = \'%3$s\'                      MAX(instruction.instruction) as instruction
10309                  AND evenement = %2$s                  FROM
10310              ',                      %1$sinstruction
10311              DB_PREFIXE,                  WHERE
10312              $ev_parent,                      dossier = \'%3$s\'
10313              $dossier                      AND evenement = %2$s',
10314                    DB_PREFIXE,
10315                    intval($ev_parent),
10316                    $this->f->db->escapeSimple($dossier)
10317                ),
10318                array(
10319                    "origin" => __METHOD__,
10320                    "force_return" => true,
10321                )
10322          );          );
10323          $res = $this->f->get_one_result_from_db_query($query, true);          if ($qres["code"] !== "OK") {
         if ($res['code'] === 'KO') {  
10324              return false;              return false;
10325          }          }
10326          $result[] = $res['result'];          $result[] = $qres["result"];
10327          //          //
10328          $query = sprintf('          $qres = $this->f->get_one_result_from_db_query(
10329              SELECT evenement_retour_ar              sprintf(
10330              FROM %1$sevenement                  'SELECT
10331              WHERE evenement = %2$s                      evenement_retour_ar
10332                  AND evenement_retour_ar != %3$s                  FROM
10333              ',                      %1$sevenement
10334              DB_PREFIXE,                  WHERE
10335              $ev_parent,                      evenement = %2$d
10336              $evenement                      AND evenement_retour_ar != %3$d',
10337                    DB_PREFIXE,
10338                    intval($ev_parent),
10339                    intval($evenement)
10340                ),
10341                array(
10342                    "origin" => __METHOD__,
10343                    "force_return" => true,
10344                )
10345          );          );
10346          $res = $this->f->get_one_result_from_db_query($query, true);          if ($qres["code"] !== "OK") {
         if ($res['code'] === 'KO') {  
10347              return false;              return false;
10348          }          }
10349          $evenements[] = $res['result'];          $evenements[] = $qres["result"];
10350          //          //
10351          $query = sprintf('          $qres = $this->f->get_one_result_from_db_query(
10352              SELECT evenement_retour_signature              sprintf(
10353              FROM %1$sevenement                  'SELECT
10354              WHERE evenement = %2$s                      evenement_retour_signature
10355                  AND evenement_retour_signature != %3$s                  FROM
10356              ',                      %1$sevenement
10357              DB_PREFIXE,                  WHERE
10358              $ev_parent,                      evenement = %2$s
10359              $evenement                      AND evenement_retour_signature != %3$s
10360                    ',
10361                    DB_PREFIXE,
10362                    intval($ev_parent),
10363                    intval($evenement)
10364                ),
10365                array(
10366                    "origin" => __METHOD__,
10367                    "force_return" => true,
10368                )
10369          );          );
10370          $res = $this->f->get_one_result_from_db_query($query, true);          if ($qres["code"] !== "OK") {
         if ($res['code'] === 'KO') {  
10371              return false;              return false;
10372          }          }
10373          $evenements[] = $res['result'];          $evenements[] = $qres["result"];
10374          foreach ($evenements as $value) {          foreach ($evenements as $value) {
10375              if ($value !== null) {              if ($value !== null) {
10376                  $query = sprintf('                  $qres = $this->f->get_one_result_from_db_query(
10377                      SELECT MAX(instruction.instruction) as instruction                      sprintf(
10378                      FROM %1$sinstruction                          'SELECT
10379                      WHERE dossier = \'%3$s\'                              MAX(instruction.instruction) as instruction
10380                          AND evenement = %2$s                          FROM
10381                      ',                              %1$sinstruction
10382                      DB_PREFIXE,                          WHERE
10383                      $value,                              dossier = \'%3$s\'
10384                      $dossier                              AND evenement = %2$s',
10385                            DB_PREFIXE,
10386                            intval($value),
10387                            $this->f->db->escapeSimple($dossier)
10388                        ),
10389                        array(
10390                            "origin" => __METHOD__,
10391                            "force_return" => true,
10392                        )
10393                  );                  );
10394                  $res = $this->f->get_one_result_from_db_query($query, true);                  if ($qres["code"] !== "OK") {
                 if ($res['code'] === 'KO') {  
10395                      return false;                      return false;
10396                  }                  }
10397                  $result[] = $res['result'];                  $result[] = $qres["result"];
10398              }              }
10399          }          }
10400          return $result;          return $result;
# Line 8329  class instruction extends instruction_ge Line 10432  class instruction extends instruction_ge
10432          // Ajoute une condition sur le where pour ne récupérer que le pétitionnaire principal          // Ajoute une condition sur le where pour ne récupérer que le pétitionnaire principal
10433          // pour une notification depuis le portail citoyen          // pour une notification depuis le portail citoyen
10434          $sqlPetitionnairePrincipal = '';          $sqlPetitionnairePrincipal = '';
10435            // Gestion des champs nécessaires pour la notification d'un demandeur
10436            $condition_demandeur = "AND demandeur.notification = 't'
10437                AND demandeur.courriel IS NOT NULL";
10438          if ($portail === true) {          if ($portail === true) {
10439              $sqlPetitionnairePrincipal = 'AND lien_dossier_demandeur.petitionnaire_principal = true';              $sqlPetitionnairePrincipal = 'AND lien_dossier_demandeur.petitionnaire_principal = true';
10440                $condition_demandeur = "AND (
10441                        (notification = 't' AND courriel IS NOT NULL)
10442                        OR demande.source_depot = 'portal'
10443                    )";
10444          }          }
10445    
10446          $listeDemandeursNotifiable = array();          $listeDemandeursNotifiable = array();
10447    
10448          // Requête de récupération des demandeurs          // Requête de récupération des demandeurs
10449          $sql = sprintf(          $qres = $this->f->get_all_results_from_db_query(
10450              'SELECT              sprintf(
10451                  demandeur.demandeur,                  'SELECT
10452                  CASE                      demandeur.demandeur,
10453                      WHEN demandeur.qualite=\'particulier\'                      CASE
10454                      THEN TRIM(CONCAT(demandeur.particulier_nom, \' \', demandeur.particulier_prenom, \' \', demandeur.courriel))                          WHEN demandeur.qualite=\'particulier\'
10455                  ELSE                          THEN TRIM(CONCAT(demandeur.particulier_nom, \' \', demandeur.particulier_prenom, \' \', demandeur.courriel))
10456                      TRIM(CONCAT(demandeur.personne_morale_raison_sociale, \' \', demandeur.personne_morale_denomination, \' \', demandeur.courriel))                      ELSE
10457                  END AS destinataire,                          TRIM(CONCAT(demandeur.personne_morale_raison_sociale, \' \', demandeur.personne_morale_denomination, \' \', demandeur.courriel))
10458                  demandeur.courriel                      END AS destinataire,
10459              FROM                      demandeur.courriel,
10460                  %1$sdossier                      petitionnaire_principal
10461                  INNER JOIN %1$slien_dossier_demandeur                  FROM
10462                      ON dossier.dossier = lien_dossier_demandeur.dossier                      %1$sdossier
10463                  INNER JOIN %1$sdemandeur                      INNER JOIN %1$slien_dossier_demandeur
10464                      ON lien_dossier_demandeur.demandeur = demandeur.demandeur                          ON dossier.dossier = lien_dossier_demandeur.dossier
10465              WHERE                      INNER JOIN %1$sdemandeur
10466                  dossier.dossier = \'%2$s\' AND                          ON lien_dossier_demandeur.demandeur = demandeur.demandeur
10467                  notification = \'t\' AND                      -- Récupération de la plus ancienne demande associée au dossier (la demande
10468                  courriel IS NOT NULL                      -- de création du dossier)
10469                  %3$s',                      INNER JOIN (
10470              DB_PREFIXE,                          SELECT
10471              $idDossier,                              demande,
10472              $sqlPetitionnairePrincipal                              dossier_instruction,
10473                                source_depot
10474                            FROM
10475                                %1$sdemande
10476                            WHERE
10477                                dossier_instruction = \'%2$s\'
10478                            ORDER BY
10479                                demande ASC
10480                            LIMIT 1
10481                        ) as demande
10482                            ON dossier.dossier = demande.dossier_instruction
10483                    WHERE
10484                        dossier.dossier = \'%2$s\'
10485                        %3$s
10486                        %4$s',
10487                    DB_PREFIXE,
10488                    $this->f->db->escapeSimple($idDossier),
10489                    $condition_demandeur,
10490                    $sqlPetitionnairePrincipal
10491                ),
10492                array(
10493                    "origin" => __METHOD__
10494                )
10495          );          );
         $res = $this->f->db->query($sql);  
         $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);  
         $this->f->isDatabaseError($res);  
10496          // Récupération des infos des demandeurs et stockage dans un tableau          // Récupération des infos des demandeurs et stockage dans un tableau
10497          // ayant pour clé les id des demandeurs          // ayant pour clé les id des demandeurs
10498          while($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {          foreach ($qres['result'] as $row) {
10499              $listeDemandeursNotifiable[$row['demandeur']] = $row;              $listeDemandeursNotifiable[$row['demandeur']] = $row;
10500          }          }
10501    
# Line 8379  class instruction extends instruction_ge Line 10508  class instruction extends instruction_ge
10508       * @param integer id de l'instruction dont on cherche les notifications       * @param integer id de l'instruction dont on cherche les notifications
10509       * @return array liste des instruction_notification liés à l'instruction       * @return array liste des instruction_notification liés à l'instruction
10510       */       */
10511      public function get_instruction_notification($id_instruction) {      public function get_instruction_notification($id_instruction, $typeNotification = null, $nonLieTache = false) {
10512            $whereTypeTache = '';
10513            $sqlTaskNull = 'INNER';
10514            // Défini si on veux que la requête récupère également les notifications qui n'ont pas
10515            // de tâches associées. C'est le cas pour les notifications de demandeurs lorsque la
10516            // notification du demandeur principal n'a pas pu être envoyée à cause d'un mauvais
10517            // paramétrage
10518            if(is_bool($nonLieTache) && $nonLieTache === true) {
10519                $sqlTaskNull = 'LEFT';
10520            }
10521            if ($typeNotification != null) {
10522                if (is_array($typeNotification)) {
10523                    $whereTypeTache = sprintf(
10524                        'AND (task.type IN (%1$s))',
10525                        "'".implode("', '", $typeNotification)."'"
10526                    );
10527                } else {
10528                    $whereTypeTache = sprintf(
10529                        'AND (task.type = \'%1$s\')',
10530                        $typeNotification
10531                    );
10532                }
10533            }
10534          $listeInstrNotif = array();          $listeInstrNotif = array();
10535          $sql = sprintf('          $qres = $this->f->get_all_results_from_db_query(
10536              SELECT              sprintf('
10537                  instruction_notification.instruction_notification                  SELECT
10538              FROM                      instruction_notification.instruction_notification
10539                  %1$sinstruction_notification                  FROM
10540              WHERE                      %1$sinstruction_notification
10541                  instruction = %2$s',                      %4$s JOIN %1$stask
10542              DB_PREFIXE,                          ON instruction_notification.instruction_notification::CHARACTER VARYING = task.object_id
10543              $id_instruction                          %3$s
10544                    WHERE
10545                        instruction = %2$s',
10546                    DB_PREFIXE,
10547                    intval($id_instruction),
10548                    $whereTypeTache,
10549                    $sqlTaskNull
10550                ),
10551                array(
10552                    "origin" => __METHOD__
10553                )
10554          );          );
10555          $res = $this->f->db->query($sql);          foreach ($qres['result'] as $row) {
         $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);  
         $this->f->isDatabaseError($res);  
         while ($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {  
10556              $listeInstrNotif[] = $row['instruction_notification'];              $listeInstrNotif[] = $row['instruction_notification'];
10557          }          }
10558          return $listeInstrNotif;          return $listeInstrNotif;
# Line 8435  class instruction extends instruction_ge Line 10593  class instruction extends instruction_ge
10593       * @return integer|null       * @return integer|null
10594       */       */
10595      protected function getUidDocumentInstructionWithKey($cleGen) {      protected function getUidDocumentInstructionWithKey($cleGen) {
10596          $query = sprintf(          $qres = $this->f->get_one_result_from_db_query(
10597              'SELECT              sprintf(
10598                  instruction.om_fichier_instruction                  'SELECT
10599              FROM                      instruction.om_fichier_instruction
10600                  %1$sinstruction_notification_document                  FROM
10601                  LEFT JOIN %1$sinstruction ON instruction_notification_document.instruction = instruction.instruction                      %1$sinstruction_notification_document
10602              WHERE                      LEFT JOIN %1$sinstruction
10603                  instruction_notification_document.cle = \'%2$s\'',                          ON instruction_notification_document.instruction = instruction.instruction
10604              DB_PREFIXE,                  WHERE
10605              $this->f->db->escapeSimple($cleGen)                      instruction_notification_document.cle = \'%2$s\'',
10606                    DB_PREFIXE,
10607                    $this->f->db->escapeSimple($cleGen)
10608                ),
10609                array(
10610                    "origin" => __METHOD__,
10611                )
10612          );          );
10613            
10614          $res = $this->f->db->getOne($query);          return $qres['result'];
         $this->addToLog(__METHOD__.": db->getOne(\"".$query."\");", VERBOSE_MODE);  
         $this->f->isDatabaseError($res);  
         return $res;  
10615      }      }
10616    
10617      /**      /**
# Line 8461  class instruction extends instruction_ge Line 10622  class instruction extends instruction_ge
10622       * @return instruction_notification       * @return instruction_notification
10623       */       */
10624      protected function getInstanceNotificationWithKey($key) {      protected function getInstanceNotificationWithKey($key) {
10625          $sql = sprintf(          $qres = $this->f->get_one_result_from_db_query(
10626              "SELECT              sprintf(
10627                  instruction_notification                  'SELECT
10628              FROM                      instruction_notification
10629                  %1\$sinstruction_notification_document                  FROM
10630              WHERE                      %1$sinstruction_notification_document
10631                  cle = '%2\$s'",                  WHERE
10632              DB_PREFIXE,                      cle = \'%2$s\'',
10633              $this->f->db->escapeSimple($key)                  DB_PREFIXE,
10634                    $this->f->db->escapeSimple($key)
10635                ),
10636                array(
10637                    "origin" => __METHOD__,
10638                )
10639          );          );
         $res = $this->f->db->getOne($sql);  
         $this->addToLog(__METHOD__.": db->getOne(\"".$sql."\");", VERBOSE_MODE);  
         $this->f->isDatabaseError($res);  
10640    
10641          // Récupération de l'instance de notification          // Récupération de l'instance de notification
10642          $instNotif = $this->f->get_inst__om_dbform(array(          $instNotif = $this->f->get_inst__om_dbform(array(
10643              "obj" => "instruction_notification",              "obj" => "instruction_notification",
10644              "idx" => $res,              "idx" => $qres['result'],
10645          ));          ));
10646          return $instNotif;          return $instNotif;
10647      }      }
# Line 8562  class instruction extends instruction_ge Line 10725  class instruction extends instruction_ge
10725          // TO_CHAR() introduit un espace avant l'affichage du nombre          // TO_CHAR() introduit un espace avant l'affichage du nombre
10726          // comme les espaces sont remplacé par des '_' dans le retour de la fonction          // comme les espaces sont remplacé par des '_' dans le retour de la fonction
10727          // il n'est pas nécessaire de mettre un '_' après le mot instruction.          // il n'est pas nécessaire de mettre un '_' après le mot instruction.
10728          $sql = sprintf(          $documentLibelle = $this->f->get_one_result_from_db_query(
10729              'SELECT              sprintf(
10730                  CONCAT(                  'SELECT
10731                      \'instruction\',                      CONCAT(
10732                      TO_CHAR(instruction.instruction, \'000\'),                          \'instruction\',
10733                      \'_\',                          TO_CHAR(instruction.instruction, \'000\'),
10734                      LOWER(om_lettretype.libelle)                          \'_\',
10735                  ) as nom_fichier                          LOWER(om_lettretype.libelle)
10736              FROM                      ) AS nom_fichier
10737                  %1$sinstruction                  FROM
10738                  LEFT JOIN %1$som_lettretype ON om_lettretype.id = instruction.lettretype                      %1$sinstruction
10739              WHERE                      LEFT JOIN %1$som_lettretype
10740                  instruction = %2$s',                          ON om_lettretype.id = instruction.lettretype
10741              DB_PREFIXE,                  WHERE
10742              $instruction                      instruction = %2$d',
10743                    DB_PREFIXE,
10744                    intval($instruction)
10745                ),
10746                array(
10747                    "origin" => __METHOD__,
10748                )
10749          );          );
10750          $documentLibelle = $this->f->db->getOne($sql);  
10751          $this->addToLog("getDocumentTitre(): db->getOne(\"".$sql."\");", VERBOSE_MODE);          $documentLibelle = $documentLibelle['result'];
         if (database::isError($documentLibelle)) {  
             die();  
         }  
10752    
10753          // Transforamtion des ' ' en '_', des accents en lettres sans accents et des          // Transforamtion des ' ' en '_', des accents en lettres sans accents et des
10754          // caractères spéciaux en '_'          // caractères spéciaux en '_'
# Line 8632  class instruction extends instruction_ge Line 10798  class instruction extends instruction_ge
10798       * l'overlay de notification des demandeurs.       * l'overlay de notification des demandeurs.
10799       */       */
10800      function getSubFormTitle($ent) {      function getSubFormTitle($ent) {
10801          if ($this->getParameter('maj') == '411') {          $actionSansPath = array('411', '420', '430');
10802            if (in_array($this->getParameter('maj'), $actionSansPath)) {
10803              return '';              return '';
10804          }          }
10805          return parent::getSubFormTitle($ent);          return parent::getSubFormTitle($ent);
10806      }      }
10807  }// fin classe      
10808        /**
10809         * Traitement de la notification automatique des tiers consulté.
10810         *
10811         * Récupère la liste des adresses mails des tiers notifiables. Pour chaque adresses
10812         * récupérées ajoute une notification et une tâche de notification par mail.
10813         * La création de la tâche de notification par mail déclenchera l'envoi du mail
10814         * et la mise à jour du suivi.
10815         *
10816         * Les tiers notifiables sont ceux :
10817         *   - n’ayant pas un ID PLAT’AU correspondant à l’ID PLAT’AU du service consultant
10818         *   - ayant une habilitation dont le type est listé dans les paramètres de
10819         *     notification de l’événement,
10820         *   - intervenant sur la commune ou le département du dossier
10821         *   - ayant au moins une adresse mail valide
10822         *
10823         * @param evenement instance de l'événement associée à l'instruction
10824         * @param dossier instance du dossier de l'instruction
10825         * @return boolean indique si le traitement à réussi
10826         */
10827        protected function traitement_notification_automatique_tiers_consulte($evenement, $dossier) {
10828            // Récupération de l'identifiant plat'au du service consultant
10829            $consultationEntrante = $dossier->get_inst_consultation_entrante();
10830            // Récupération de la liste des types d'habilitations autorisées pour
10831            // cette notification
10832            $typesHabilitationsNotifiable = $evenement->get_types_habilitation_notifiable();
10833            // Récupération du département et de la commune du dossier
10834            $commune = $dossier->getVal('commune');
10835            // Le département est récupéré à partir de la commune du dossier donc si la
10836            // commune n'a pas pu être récupéré on ne récupère pas non plus le département.
10837            $idDepartement = null;
10838            if (! empty($commune)) {
10839                $departement = $dossier->get_inst_departement_dossier();
10840                $idDepartement = $departement->getVal($departement->clePrimaire);
10841            }
10842            // Récupération des courriels des tiers notifiables
10843            $tiersANotifier = $this->get_courriels_tiers_notifiable(
10844                $typesHabilitationsNotifiable,
10845                $consultationEntrante->getVal('service_consultant_id'),
10846                $commune,
10847                $idDepartement
10848            );
10849            // Traitement de chacune des listes de diffusion pour extraire les
10850            // courriels, vérifier la validité des courriels et envoyer la
10851            // notification
10852            $notificationSend = false;
10853            if (empty($tiersANotifier)) {
10854                $this->addToLog(
10855                    sprintf(
10856                        '%s() : %s %s : %s',
10857                        __METHOD__,
10858                        __("La récupération des tiers à échoué."),
10859                        __('Paramétrage'),
10860                        var_export(
10861                            array(
10862                                'types_habilitations_notifiable' => $typesHabilitationsNotifiable,
10863                                'service_consultant' => $consultationEntrante->getVal('service_consultant_id'),
10864                                'id_commune' => $commune,
10865                                'id_departement' => $idDepartement
10866                            ),
10867                            true
10868                        )
10869                    ),
10870                    DEBUG_MODE
10871                );
10872                return false;
10873            }
10874            foreach($tiersANotifier as $tierANotifier) {
10875                // Découpe la liste de diffusion pour stocker les adresses mails
10876                // des tiers dans un tableau
10877                $courriels =
10878                    array_filter(
10879                        array_map(
10880                            'trim',
10881                            preg_split("/\r\n|\n|\r/", $tierANotifier['liste_diffusion'])));
10882                    
10883                foreach ($courriels as $courriel) {
10884                    // Pour chaque adresse mail vérifie si l'adresse est valide
10885                    if (! $this->f->checkValidEmailAddress($courriel)) {
10886                        continue;
10887                    }
10888                    $destinataire = array(
10889                        'destinataire' => $tierANotifier['libelle'].' : '.$courriel,
10890                        'courriel' => $courriel
10891                    );
10892                    // Si l'adresse est valide ajoute une nouvelle notification
10893                    // et une tâche d'envoi de mails
10894                    $idNotif = $this->ajouter_notification(
10895                        $this->getVal($this->clePrimaire),
10896                        $this->f->get_connected_user_login_name(),
10897                        $destinataire,
10898                        $this->get_dossier_instruction_om_collectivite(),
10899                        array(),
10900                        true
10901                    );
10902                    if ($idNotif === false) {
10903                        $this->addToLog(
10904                            __METHOD__.
10905                            __("L'ajout de la notification a échoué."),
10906                            DEBUG_MODE
10907                        );
10908                        return false;
10909                    }
10910                    // Création de la tache en lui donnant l'id de la notification
10911                    $notification_by_task = $this->notification_by_task(
10912                        $idNotif,
10913                        $dossier->getVal('dossier'),
10914                        'mail',
10915                        'notification_tiers_consulte'
10916                    );
10917                    if ($notification_by_task === false) {
10918                        $this->addToLog(
10919                            __METHOD__.
10920                            __("L'ajout de la tâche de notification a échoué."),
10921                            DEBUG_MODE
10922                        );
10923                        $this->addToMessage(
10924                            __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
10925                        );
10926                        return false;
10927                    }
10928                    $notificationSend = true;
10929                }
10930            }
10931            // Si aucune notification n'a été envoyé car il n'y a pas de courriels
10932            // valide, affiche un message dans les logs pour avoir un suivi.
10933            if (! $notificationSend) {
10934                $this->addToLog(
10935                    sprintf(
10936                        '%s %s : %s %s : %s',
10937                        __METHOD__,
10938                        __("Il n'y a pas de tiers notifiable pour l'instruction"),
10939                        $evenement->getVal('libelle'),
10940                        __("du dossier"),
10941                        $this->getVal('dossier')
10942                    ),
10943                    DEBUG_MODE
10944                );
10945            }
10946            return true;
10947        }
10948    
10949        /**
10950         * Récupère, à l'aide d'une requête, la liste de diffusion des tiers
10951         * respectant les conditions suvantes :
10952         *   - le tiers consulté dois accepté les notifications
10953         *   - la liste de diffusion ne dois pas être vide
10954         *   - l'uid du tiers consulté ne dois pas être celui passé en paramètre
10955         *     si pas d'uid passé en paramètre alors on ne filtre pas selon l'uid
10956         *     du tiers
10957         *   - le type d'habilitation des tiers dois appartenir à la liste
10958         *     fournie en paramètre
10959         *   - le tiers dois être associé à la commune ou au département passé
10960         *     en paramètre
10961         *
10962         * @param array $typesHabilitations tableau contenant la liste des types d'habilitation
10963         *              pouvant être notifiée
10964         * @param integer $idPlautau uid de l'acteur plat'au du dossier qui ne dois pas être notifié
10965         * @param integer $commune identifiant de la commune du dossier
10966         * @param integer $departement identifiant du département du dossier
10967         *
10968         * @return array listes de diffusion des tiers notifiable
10969         */
10970        protected function get_courriels_tiers_notifiable(array $typesHabilitations, $idPlatau, $commune, $departement) {
10971            // Si paramètre non renseigné alors ne renvoie rien
10972            if (empty($typesHabilitations) || empty($commune) || empty($departement)) {
10973                return false;
10974            }
10975            // Si il n'y a pas d'acteur associé au dossier alors on ne filtre pas sur l'uid de l'acteur
10976            $filtreServiceConsulteDI = '';
10977            if (! empty($idPlatau)) {
10978                $filtreServiceConsulteDI = sprintf(
10979                    "-- Filtre les tiers ayant une ligne correspondante a l uid platau du service
10980                    -- en charge du dossier
10981                    AND (tiers_consulte.uid_platau_acteur !~ ('\y' || '%s' || '\y')
10982                        OR tiers_consulte.uid_platau_acteur IS NULL)",
10983                    $this->f->db->escapeSimple($idPlatau)
10984                );
10985            }
10986            $rst = $this->f->get_all_results_from_db_query(
10987                sprintf(
10988                    'SELECT
10989                        -- Tiers notifiables lié à la commune du dossier
10990                        tiers_consulte.liste_diffusion,
10991                        tiers_consulte.libelle
10992                    FROM
10993                        %1$shabilitation_tiers_consulte
10994                        LEFT JOIN %1$stiers_consulte
10995                            ON habilitation_tiers_consulte.tiers_consulte = tiers_consulte.tiers_consulte
10996                        LEFT JOIN %1$slien_habilitation_tiers_consulte_commune
10997                            ON habilitation_tiers_consulte.habilitation_tiers_consulte = lien_habilitation_tiers_consulte_commune.habilitation_tiers_consulte
10998                        -- Conservation uniquement des tiers acteur de dossiers
10999                        JOIN %1$slien_dossier_tiers
11000                            ON tiers_consulte.tiers_consulte = lien_dossier_tiers.tiers
11001                    WHERE
11002                        tiers_consulte.accepte_notification_email IS TRUE
11003                        AND tiers_consulte.liste_diffusion IS NOT NULL
11004                        %3$s
11005                        AND habilitation_tiers_consulte.type_habilitation_tiers_consulte IN (%2$s)
11006                        AND lien_habilitation_tiers_consulte_commune.commune = %4$d
11007                        -- Filtre sur les tiers acteur du dossier
11008                        AND lien_dossier_tiers.dossier = \'%6$s\'
11009                    UNION
11010                    SELECT
11011                        -- Tiers notifiables lié au département du dossier
11012                        tiers_consulte.liste_diffusion,
11013                        tiers_consulte.libelle
11014                    FROM
11015                        %1$shabilitation_tiers_consulte
11016                        LEFT JOIN %1$stiers_consulte
11017                            ON habilitation_tiers_consulte.tiers_consulte = tiers_consulte.tiers_consulte
11018                        LEFT JOIN %1$slien_habilitation_tiers_consulte_departement
11019                            ON habilitation_tiers_consulte.habilitation_tiers_consulte = lien_habilitation_tiers_consulte_departement.habilitation_tiers_consulte
11020                        -- Conservation uniquement des tiers acteur de dossiers
11021                        JOIN %1$slien_dossier_tiers
11022                            ON tiers_consulte.tiers_consulte = lien_dossier_tiers.tiers
11023                    WHERE
11024                        tiers_consulte.accepte_notification_email IS TRUE
11025                        AND tiers_consulte.liste_diffusion IS NOT NULL
11026                        %3$s
11027                        AND habilitation_tiers_consulte.type_habilitation_tiers_consulte IN (%2$s)
11028                        AND lien_habilitation_tiers_consulte_departement.departement = %5$d
11029                        -- Filtre sur les tiers acteur du dossier
11030                        AND lien_dossier_tiers.dossier = \'%6$s\'',
11031                    DB_PREFIXE,
11032                    implode(', ', $typesHabilitations),
11033                    $filtreServiceConsulteDI,
11034                    intval($commune),
11035                    intval($departement),
11036                    $this->f->db->escapeSimple($this->getVal('dossier'))
11037                ),
11038                array(
11039                    "origin" => __METHOD__
11040                )
11041            );
11042            // Faire un order by sur un union ne fonctionne pas. A la place
11043            // c'est le tableau des résultats qui est ordonné.
11044            usort($rst['result'], function($a, $b) {
11045                return strcmp($a['libelle'], $b['libelle']);
11046            });
11047            return $rst['result'];
11048        }
11049    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26