/[openfoncier]/trunk/services/metier/consultationmanager.php
ViewVC logotype

Diff of /trunk/services/metier/consultationmanager.php

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

revision 577 by mlimic, Fri Nov 2 10:10:56 2012 UTC revision 778 by fmichon, Tue Nov 20 16:14:25 2012 UTC
# Line 1  Line 1 
1  <?php  <?php
2    /**
3  /*   * Ce fichier permet de déclarer la classe ConsultationManager, qui effectue les
4   * Processes requests received via services which concern consultations (by   * traitements pour la ressource 'consultations'.
  * ERP or other services).  
  *  
  * @author Mirna Limic <[email protected]>  
  * Date: 18/10/2012  
5   *   *
6   * Follow-up:   * @package openfoncier
7   * Bugs:   * @version SVN : $Id$
8   */   */
9    
10    // Inclusion de la classe de base MetierManager
11    require_once("./metier/metiermanager.php");
12    
13  require_once ("./metier/metiermanager.php");  // Inclusion de la classe métier consultation
14  require_once("../obj/consultation.class.php");  require_once("../obj/consultation.class.php");
15    
16    /**
17     * Cette classe hérite de la classe MetierManager. Elle permet d'effectuer des
18     * traitements pour la ressource 'consultations'. Le traitement permet de
19     * rendre un retour d'avis sur une consultation existante par un service
20     * interne à la mairie directement depuis son application.
21     *
22     * @todo XXX Traduire et commenter toutes les méthodes
23     */
24  class ConsultationManager extends MetierManager {  class ConsultationManager extends MetierManager {
       
25    
26      /*      /**
      * Constructor.  
27       *       *
28       * Calls it's parent constructor to establish a DB connection       */
29       * and initializes the instance variables      var $metier_instance = null;
30       */          var $filename_prefix = null;
31      public function __construct() {      var $filename = null;
32          parent::__construct();  
33          /*$this->date_limite = null;      /**
34          $this->date_retour = null;       * Cette méthode permet de modifier une consultation existante pour lui
35          $this->date_envoi = null;       * ajouter les informations de retour d'avis.
36          $this->dossier_id = null;*/       *
37          $this->decisions = null;       * @param mixed $request_data Les données JSON reçues
38          $this->metier_instance = null;       * @param string $id L'identifiant de la ressource
39          $this->filename_prefix = null;       */
40          $this->filename = null;      public function consultationDecision($data, $id) {
     }  
       
       
     /*  
      * Destructor  
      *  
      * Call's its parent's destructor.  
      */      
     public function __destruct() {  
         parent::__destruct();  
     }  
       
41    
42      /*          // Si l'identifiant envoyé n'est pas un numérique alors on ajoute un
43       * Verifies that the date_retour received in the incomming data          // message d'informations et on retourne un résultat d'erreur
44       * is in the (date_envoi, date_limite) interval. Also, check that          if (!is_numeric($id)) {
45       * there is no date_retour set for the consultation, as well as the              $this->setMessage("L'identifiant '".$id."' fourni est incorrect.");
      * validity of the date itself  
      * @param string $date_str The date_retour recived in the request  
      * @param string $id The discussion id  
      * @return string OK on success, BAD_DATA if the data sent is invalid,  
      * KO otherwise  
      */      
     private function checkDates($date_str, $id) {  
         // check that the consultation exists in DB  
         if (empty($this->metier_instance->valF['date_limite'])) {  
             $this->setMessage("La consultation ".$id." n'était pas trouvé");  
46              return $this->BAD_DATA;              return $this->BAD_DATA;
47          }          }
48    
49          // check that the date_retour does not already exist          // On instancie la consultation sur laquelle porte la requête
50          if (!empty($this->metier_instance->valF['date_retour'])) {          $this->metier_instance = new consultation($id, $this->db, 0);
51              $this->setMessage("Le date de retour de la consultation ".$id.  
52                  " existe déjà");          // On vérifie si l'instanciation a produit une erreur de base de données
53            // alors on ajoute un message d'informations et on retourne un résultat
54            // d'erreur
55            if (isset($this->metier_instance->errors['db_debuginfo'])
56                && !empty($this->metier_instance->errors['db_debuginfo'])) {
57                $this->setMessage("Erreur lors de la récupération de la".
58                                  " consultation '".$id."'.");
59                return $this->KO;
60            }
61    
62            // Si l'identifiant de la consultation instanciée est différent de
63            // l'identifiant envoyé alors on ajoute un message d'informations et
64            // on retourne un résultat d'erreur
65            if ($id != $this->getMetierInstanceValForPrimaryKey()) {
66                $this->setMessage("Aucune consultation '".$id."'.");
67              return $this->BAD_DATA;              return $this->BAD_DATA;
68          }          }
69            
70          // check that the date is valid          // Si la consultation possède déjà une date de retour ou un avis ou une
71          $date = explode("/", $date_str);          // motivation alors on ajoute un message d'informations et on retourne
72          if (!checkdate($date[1], $date[0], $date[2])) {          // un résultat d'erreur
73              $this->setMessage("Le date de retour fourni pour la consultation ".          $date_retour = $this->getMetierInstanceValForField("date_retour");
74                                $id." n'est pas bon (en bon format)");          $avis = $this->getMetierInstanceValForField("avis");
75            $motivation = $this->getMetierInstanceValForField("motivation");
76            if (!empty($date_retour) || !empty($avis) || !empty($motivation)) {
77                $this->setMessage("Un retour d'avis a déjà été rendu pour la".
78                                  " consultation '".$id."'.");
79              return $this->BAD_DATA;              return $this->BAD_DATA;
80          }          }
81            
82          if (!$this->dateInsideInterval($date_str,          // Le format de la date de retour valide est 'JJ/MM/AAAA'
83                      $this->metier_instance->valF['date_envoi'],          // Si la donnée fournie n'est pas valide alors on ajoute
84                      $this->metier_instance->valF['date_limite'])) {          // un message d'informations et on retourne un résultat d'erreur
85              $this->setMessage("Le date de retour fourni pour la consultation ".          $date_retour = explode("/", $data['date_retour']);
86                                $id." n'est pas entre le date d'envoi ".          if (count($date_retour)!= 3
87                                "et le date limite de la demande de consultation");              || !checkdate($date_retour[1], $date_retour[0], $date_retour[2])) {
88                $this->setMessage("Le format de la date de retour d'avis fournie".
89                                  " pour la consultation '".$id."' n'est pas".
90                                  " correct.");
91                return $this->BAD_DATA;
92            }
93    
94            // Si la date de retour de l'avis ne se situe pas entre la date d'envoi
95            // de la consultation et la date limite de retour d'avis alors on ajoute
96            // un message d'informations et on retourne un résultat d'erreur
97            $date_retour = $data['date_retour'];
98            $date_envoi = $this->getMetierInstanceValForField("date_envoi");
99            $date_limite = $this->getMetierInstanceValForField("date_limite");
100            if (!$this->dateInsideInterval($date_retour,
101                                           $date_envoi, $date_limite)) {
102                $this->setMessage("La date de retour d'avis fournie pour la".
103                                  " consultation '".$id."' ne se trouve pas entre".
104                                  " la date d'envoi et la date limite.");
105              return $this->BAD_DATA;              return $this->BAD_DATA;
106          }          }
         return $this->OK;  
     }  
107    
108            // => DATE DE RETOUR
109            $this->metier_instance->valF['date_retour'] = $data['date_retour'];
110    
111      /*          // Si l'avis fourni ne correspond pas à la liste d'avis valides alors
112       * Verifies that the avis received in the incomming data corresponds          // on ajoute un message d'informations et on retourne un résultat
113       * to one of the avis found in DB.          // d'erreur
114       * @param string $avis The avis recived in the request          $avis = $data["avis"];
115       * @param string $id The discussion id          $avis_valid = array("Favorable",
116       * @return string OK on success, KO otherwise                              "Favorable avec réserve", "Défavorable", );
117       */          if (!in_array($avis, $avis_valid)) {
118      private function avisValid($avis, $id) {              $this->setMessage("L'avis du retour d'avis fourni pour la".
119          // get all of the decisions possible from table avis_decision                                " consultation '".$id."' n'est pas correct.");
120          $sql = "SELECT libelle, avis_consultation FROM avis_consultation";              return $this->BAD_DATA;
121            }
122    
123            // Récupération de la référence vers un avis_consultation existant
124            // On liste les avis possibles et on récupère l'identifiant
125            // correspondant au libellé transmis en paramètre
126            $sql = " SELECT avis_consultation, libelle ";
127            $sql .= " FROM ".DB_PREFIXE."avis_consultation ";
128            $sql .= " WHERE ((avis_consultation.om_validite_debut IS NULL ";
129            $sql .= " AND (avis_consultation.om_validite_fin IS NULL ";
130            $sql .= " OR avis_consultation.om_validite_fin > CURRENT_DATE)) ";
131            $sql .= " OR (avis_consultation.om_validite_debut <= CURRENT_DATE ";
132            $sql .= " AND (avis_consultation.om_validite_fin IS NULL ";
133            $sql .= " OR avis_consultation.om_validite_fin > CURRENT_DATE))) ";
134          $res = $this->db->query($sql);          $res = $this->db->query($sql);
135          if ($this->checkDBError($res, 'Erreur lors de recuperation des avis '.          // Logger
136                  'possibles pendant traitement de la consultation '.$id)) {          $this->addToLog("consultationDecision(): db->query(\"".$sql."\")",
137                            VERBOSE_MODE);
138    
139            // Si une erreur de base de données se produit sur cette requête
140            // alors on retourne un résultat d'erreur
141            if ($this->f->isDatabaseError($res, true)) {
142                $this->setMessage("Erreur lors de la récupération des avis pour la".
143                                  " consultation '".$id."'.");
144              return $this->KO;              return $this->KO;
145          }          }
146    
147          $this->decisions = array();          // Récupération de la référence vers un avis_consultation existant
148          while ($row =& $res->fetchRow(DB_FETCHMODE_ORDERED)) {          // On liste les avis possibles et on récupère l'identifiant
149              $this->decisions[$row[0]] = $row[1];          // correspondant au libellé transmis en paramètre
150            $avis = $data["avis"];
151            $avis_id = NULL;
152            while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
153                if ($avis == $row["libelle"]) {
154                    $avis_id = $row["avis_consultation"];
155                    break;
156                }
157          }          }
158          $res->free();          $res->free();
159            
160          // check that the decision received corresponds to a decision in DB          // Si la décision n'existe pas dans la base de données alors on ajoute
161          if (!in_array($avis, array_keys($this->decisions))) {          // un message d'informations et on retourne un résultat d'erreur
162              $this->setMessage(          if (is_null($avis_id)) {
163                  "L'avis de consultation reçu n'est pas feasible");              $this->setMessage("L'avis n'existe pas.");
164              return $this->KO;              return $this->KO;
165          }          }
         return $this->OK;  
     }  
166    
167                // => AVIS
168      /*          $this->metier_instance->valF['avis_consultation'] = $avis_id;
169       * Verifies that all the data concerning file to be stored (if any)  
170       * are present in full or not present at all          // Si un nom de fichier (nom_fichier) est fourni mais pas un contenu de
171       * @param mixed $data The data recived in the request          // fichier (fichier_base64) alors on ajoute un message d'informations
172       * @param string $id The discussion id          // et on retourne un résultat d'erreur
173       * @return string OK on success, KO otherwise          if (isset($data['nom_fichier']) && !isset($data['fichier_base64'])
174       */              || isset($data['fichier_base64']) && !isset($data['nom_fichier'])) {
175      private function fichierDataValid(&$data, $id) {              $this->setMessage("Les informations du fichier de retour d'avis".
176          // do the check                                " fournies pour la consultation '".$id."' ne".
177          if (!isset($data['nom_fichier']) && isset($data['fichier_base64'])                                " sont pas correctes.");
178              || isset($data['nom_fichier']) && !isset($data['fichier_base64'])) {              return $this->BAD_DATA;
             $this->setMessage(  
                     "Les données de fichier d'avis de la consultation ".$id.  
                     " ne sont pas complètes ");  
             return $this->KO;  
179          }          }
         return $this->OK;  
     }  
180    
181            //
182            $this->filename_prefix = "consultation_".$id."_";
183    
184      /*          //
      * Store the data recived in the request into a file on the  
      * local filesystem.  
      * @todo This function will need to be changed for the save to  
      * be on GED  
      * @param mixed $data The data received with the request  
      * @param string $id The consultation ID  
      * @return string OK on success, KO otherwise  
      */  
     private function storeDecisionFile(&$data, $id) {  
185          if (isset($data['fichier_base64'])) {          if (isset($data['fichier_base64'])) {
186              $dir = dirname(__FILE__).'/../../trs/'.$this->dossier_id;              //
187                            if ($file_content = base64_decode($data['fichier_base64'], true)) {
188              // if a file already exists by that name and it                  //
189              // is not a directory, back out                  $r = $this->f->storeDecisionFile($file_content,
190              if (file_exists($dir) && !is_dir($dir)) {                      $data['nom_fichier'],
191                  $this->setMessage("Fichier d'avis ne peut pas être ".                      $this->getMetierInstanceValForField("dossier"),
192                  "enregistré pour la consultation ".$id);                      $this->filename_prefix);
193                  return $this->KO;                        // XXX Vérifier le retour d'erreur de la méthode
194              }                  // StoreDecisionFile
195              // if a dirextory by that name exists, make sure it does                  if ($r !== true) {
196              // not already contain an avis de consultation                      return $r;
             if (file_exists($dir) && is_dir($dir)) {  
                 $dir_contents = trim(shell_exec('ls '.$dir));  
                 if (strpos($dir_contents, ' ') != false) {  
                     $dir_contents = explode(' ', $dir_contents);  
                 } else {  
                     $dir_contents = array($dir_contents);  
                 }  
                 foreach ($dir_contents as $filename) {  
                     if (strspn($filename, $this->filename_prefix, 0) > 0) {  
                         $this->setMessage("Un fichier d'avis existe déjà ".  
                         "pour la consultation ".$id);  
                         return $this->KO;  
                     }  
197                  }                  }
198                } else {
199                    $this->setMessage("Le contenu du fichier n'est pas valide.");
200                    return $this->BAD_DATA;
201              }              }
             // if no file by that name exists, create the directory  
             if (!file_exists($dir)) {  
                 if (!mkdir($dir, 0775)) {  
                     $this->setMessage("Erreur dans la création de répertoire ".  
                     "pour la sauvegarde de l'avis de la consultation ".$id);  
                     return $this->KO;  
                 }  
             }  
   
               
             // store the file contents into the file named:  
             //      consultation_<ID>_<file_name_received>  
             $file_len = strlen($data['fichier_base64']);  
             $filename = $dir.$this->metier_instance->valF['dossier'].'/'.  
                     $this->filename_prefix.$data['nom_fichier'];  
             $this->filename = $filename;  
             $file = fopen($filename, 'w');  
             if (!$file) {  
                 $this->setMessage("Echec en création de pointeur de fichier ".  
                     "pour la sauvegarde de l'avis de la consultation ".$id);  
                 return $this->KO;  
             }  
             // check that the number of bytes written is equal to the length  
             // of the data received  
             $num_written = fwrite($file, $data['fichier_base64'], $file_len);  
             if (!$num_written || $num_written != $file_len) {  
                 $this->setMessage("Sauvegarde de fichier d'avis pour la ".  
                 "consultation ".$id." a échouée");  
                 // remove the file  
                 // the return value from shell can't be used for checking since  
                 // one can not know if the NULL returned is because there was no  
                 // output or because there was an error  
                 $ret = shell_exec("rm -f $filename 2>&1");  
                 //if ($ret == NULL) { // an error occured while deleting the file  
                 //    $msg = $this->getMessage();  
                 //    $this->setMessage($msg . ' Problème pendent la suppression '.  
                 //            'des données corrompues');  
                 //}  
                 return $this->KO;  
             }  
             fclose($file);  
         }  
         return $this->OK;  
     }  
       
     /*  
      * Called when one of the external services sends its recommendation  
      * as a responde to a demand issued by openfoncier.  
      * @param mixed $data The array containing building number.  
      * @param string $id The ID of the dossier.  
      * @return bool 'OK'  
      */  
     public function consultationDecision($data, $id) {  
         
         // get all of the dates for the consultation from DB  
         // and check the date received is ok with respect to the  
         // time interval set by (date_envoi, date_limite)  
         // equally extract the dossier ID while at it  
         $this->metier_instance = new consultation($id, $this->db, 0);  
           
         // check that the consultation was found  
         if (isset($this->metier_instance->errors['db_debuginfo'])  
             && !empty($consultation->errors['db_debuginfo'])) {  
             $this->setMessage("Erreur lors de recuperation de la ".  
                         "consultation $id");  
             return $this->KO;  
         }  
           
         // check that the date sent is applicable  
         $res = $this->checkDates($data['date_retour'], $id);  
         if ($res != $this->OK) {  
             return $res;  
202          }          }
203    
204          // set the prefix for the filename to use in case file data          // => FICHIER
         // was received  
         $this->filename_prefix = "consultation_".$id."_";  
         // check that data regarding fichier is complete  
         $res = $this->fichierDataValid($data, $id);  
         if ($res != $this->OK) {  
             return $res;  
         }  
           
         // check that the decision sent is one of the decisions found in DB  
         // and store the possible decisions in $this->decisions  
         $res = $this->avisValid($data['avis'], $id);  
         if ($res != $this->OK) {  
             return $res;  
         }          
         // first store the file if needed  
         $res = $this->storeDecisionFile($data, $id);  
         if ($res != $this->OK) {  
             return $res;  
         }  
         $this->metier_instance->valF['date_retour'] = $data['date_retour'];  
         $this->metier_instance->valF['avis_consultation'] = $this->decisions[$data['avis']];  
         $this->metier_instance->valF['lu'] = FALSE;  
205          if (isset($data['nom_fichier'])) {          if (isset($data['nom_fichier'])) {
206              $this->metier_instance->valF['fichier'] = $this->filename_prefix . $data['nom_fichier'];              $this->metier_instance->valF['fichier'] = $this->filename_prefix.$data['nom_fichier'];
207          }          }
208    
209            // => MOTIVATION
210          if (isset($data['motivation'])) {          if (isset($data['motivation'])) {
211              $this->metier_instance->valF['motivation'] = $data['motivation'];              $this->metier_instance->valF['motivation'] = $data['motivation'];
212          }          }
213            
214            // => LU
215            $this->metier_instance->valF['lu'] = false;
216    
217            // Exécution du traitement
218          $ret = parent::modifier($this->metier_instance->valF,          $ret = parent::modifier($this->metier_instance->valF,
219              "L'avis de la consultation $id a été pris en compte",              "L'avis de la consultation $id a été pris en compte",
220              "Erreur pendant le traitemande de la demande pour la consultation $id");              "Erreur pendant le traitemande de la demande pour la consultation $id");
221    
222            // XXX vérifier ce retour car filename n'est jamais rempli
223          if ($ret != $this->OK) {          if ($ret != $this->OK) {
224              // delete the file on disk              // delete the file on disk
225              if (isset($data['nom_fichier'])) {              if (isset($data['nom_fichier'])) {
# Line 294  class ConsultationManager extends Metier Line 227  class ConsultationManager extends Metier
227              }              }
228          }          }
229          return $ret;          return $ret;
230    
231      }      }
232        
       
233  }  }
234    
235  ?>  ?>

Legend:
Removed from v.577  
changed lines
  Added in v.778

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26