/[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 702 by nhaye, Thu Nov 15 15:24:34 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              return $this->BAD_DATA;          // 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          // check that the date is valid              && !empty($this->metier_instance->errors['db_debuginfo'])) {
57          $date = explode("/", $date_str);              $this->setMessage("Erreur lors de la récupération de la".
58          if (!checkdate($date[1], $date[0], $date[2])) {                                " consultation '".$id."'.");
59              $this->setMessage("Le date de retour fourni pour la consultation ".              return $this->KO;
60                                $id." n'est pas bon (en bon format)");          }
61              return $this->BAD_DATA;  
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          if (!$this->dateInsideInterval($date_str,          // on retourne un résultat d'erreur
65                      $this->metier_instance->valF['date_envoi'],          if ($id != $this->getMetierInstanceValForPrimaryKey()) {
66                      $this->metier_instance->valF['date_limite'])) {              $this->setMessage("Aucune consultation '".$id."'.");
             $this->setMessage("Le date de retour fourni pour la consultation ".  
                               $id." n'est pas entre le date d'envoi ".  
                               "et le date limite de la demande de consultation");  
67              return $this->BAD_DATA;              return $this->BAD_DATA;
68          }          }
         return $this->OK;  
     }  
69    
70            // Si la consultation possède déjà une date de retour ou un avis ou une
71            // motivation alors on ajoute un message d'informations et on retourne
72            // un résultat d'erreur
73            $date_retour = $this->getMetierInstanceValForField("date_retour");
74            $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;
80            }
81    
82      /*          // Le format de la date de retour valide est 'JJ/MM/AAAA'
83       * Verifies that the avis received in the incomming data corresponds          // Si la donnée fournie n'est pas valide alors on ajoute
84       * to one of the avis found in DB.          // un message d'informations et on retourne un résultat d'erreur
85       * @param string $avis The avis recived in the request          $date_retour = explode("/", $data['date_retour']);
86       * @param string $id The discussion id          if (count($date_retour)!= 3
87       * @return string OK on success, KO otherwise              || !checkdate($date_retour[1], $date_retour[0], $date_retour[2])) {
88       */              $this->setMessage("Le format de la date de retour d'avis fournie".
89      private function avisValid($avis, $id) {                                " pour la consultation '".$id."' n'est pas".
90          // get all of the decisions possible from table avis_decision                                " correct.");
91          $sql = "SELECT libelle, avis_consultation FROM avis_consultation";              return $this->BAD_DATA;
         $res = $this->db->query($sql);  
         if ($this->checkDBError($res, 'Erreur lors de recuperation des avis '.  
                 'possibles pendant traitement de la consultation '.$id)) {  
             return $this->KO;  
92          }          }
93    
94          $this->decisions = array();          // Si la date de retour de l'avis ne se situe pas entre la date d'envoi
95          while ($row =& $res->fetchRow(DB_FETCHMODE_ORDERED)) {          // de la consultation et la date limite de retour d'avis alors on ajoute
96              $this->decisions[$row[0]] = $row[1];          // 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;
106          }          }
107          $res->free();  
108                    // => DATE DE RETOUR
109          // check that the decision received corresponds to a decision in DB          $this->metier_instance->valF['date_retour'] = $data['date_retour'];
110          if (!in_array($avis, array_keys($this->decisions))) {  
111              $this->setMessage(          // Si l'avis fourni ne correspond pas à la liste d'avis valides alors
112                  "L'avis de consultation reçu n'est pas feasible");          // on ajoute un message d'informations et on retourne un résultat
113              return $this->KO;          // d'erreur
114            $avis = $data["avis"];
115            $avis_valid = array("Favorable",
116                                "Favorable avec réserve", "Défavorable", );
117            if (!in_array($avis, $avis_valid)) {
118                $this->setMessage("L'avis du retour d'avis fourni pour la".
119                                  " consultation '".$id."' n'est pas correct.");
120                return $this->BAD_DATA;
121          }          }
         return $this->OK;  
     }  
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       * Verifies that all the data concerning file to be stored (if any)          // correspondant au libellé transmis en paramètre
126       * are present in full or not present at all          $sql = " SELECT avis_consultation, libelle ";
127       * @param mixed $data The data recived in the request          $sql .= " FROM ".DB_PREFIXE."avis_consultation ";
128       * @param string $id The discussion id          $sql .= " WHERE ((avis_consultation.om_validite_debut IS NULL ";
129       * @return string OK on success, KO otherwise          $sql .= " AND (avis_consultation.om_validite_fin IS NULL ";
130       */          $sql .= " OR avis_consultation.om_validite_fin > CURRENT_DATE)) ";
131      private function fichierDataValid(&$data, $id) {          $sql .= " OR (avis_consultation.om_validite_debut <= CURRENT_DATE ";
132          // do the check          $sql .= " AND (avis_consultation.om_validite_fin IS NULL ";
133          if (!isset($data['nom_fichier']) && isset($data['fichier_base64'])          $sql .= " OR avis_consultation.om_validite_fin > CURRENT_DATE))) ";
134              || isset($data['nom_fichier']) && !isset($data['fichier_base64'])) {          $res = $this->db->query($sql);
135              $this->setMessage(          // Logger
136                      "Les données de fichier d'avis de la consultation ".$id.          $this->addToLog("consultationDecision(): db->query(\"".$sql."\")",
137                      " ne sont pas complètes ");                          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          }          }
         return $this->OK;  
     }  
146    
147      /*          // Récupération de la référence vers un avis_consultation existant
148       * Called when one of the external services sends its recommendation          // On liste les avis possibles et on récupère l'identifiant
149       * as a responde to a demand issued by openfoncier.          // correspondant au libellé transmis en paramètre
150       * @param mixed $data The array containing building number.          $avis = $data["avis"];
151       * @param string $id The ID of the dossier.          $avis_id = NULL;
152       * @return bool 'OK'          while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
153       */              if ($avis == $row["libelle"]) {
154      public function consultationDecision($data, $id) {                  $avis_id = $row["avis_consultation"];
155                          break;
156          // get all of the dates for the consultation from DB              }
157          // and check the date received is ok with respect to the          }
158          // time interval set by (date_envoi, date_limite)          $res->free();
159          // equally extract the dossier ID while at it  
160          $this->metier_instance = new consultation($id, $this->db, 0);          // Si la décision n'existe pas dans la base de données alors on ajoute
161                    // un message d'informations et on retourne un résultat d'erreur
162          // check that the consultation was found          if (is_null($avis_id)) {
163          if (isset($this->metier_instance->errors['db_debuginfo'])              $this->setMessage("L'avis n'existe pas.");
             && !empty($consultation->errors['db_debuginfo'])) {  
             $this->setMessage("Erreur lors de recuperation de la ".  
                         "consultation $id");  
164              return $this->KO;              return $this->KO;
165          }          }
166            
167          // check that the date sent is applicable          // => AVIS
168          $res = $this->checkDates($data['date_retour'], $id);          $this->metier_instance->valF['avis_consultation'] = $avis_id;
169          if ($res != $this->OK) {  
170              return $res;          // Si un nom de fichier (nom_fichier) est fourni mais pas un contenu de
171            // fichier (fichier_base64) alors on ajoute un message d'informations
172            // et on retourne un résultat d'erreur
173            if (isset($data['nom_fichier']) && !isset($data['fichier_base64'])
174                || isset($data['fichier_base64']) && !isset($data['nom_fichier'])) {
175                $this->setMessage("Les informations du fichier de retour d'avis".
176                                  " fournies pour la consultation '".$id."' ne".
177                                  " sont pas correctes.");
178                return $this->BAD_DATA;
179          }          }
180    
181          // set the prefix for the filename to use in case file data          //
         // was received  
182          $this->filename_prefix = "consultation_".$id."_";          $this->filename_prefix = "consultation_".$id."_";
183          // check that data regarding fichier is complete  
184          $res = $this->fichierDataValid($data, $id);          //
185          if ($res != $this->OK) {          if (isset($data['fichier_base64'])) {
186              return $res;              //
187          }              if ($file_content = base64_decode($data['fichier_base64'], true)) {
188                            //
189          // check that the decision sent is one of the decisions found in DB                  $r = $this->f->storeDecisionFile($file_content,
190          // and store the possible decisions in $this->decisions                      $data['nom_fichier'],
191          $res = $this->avisValid($data['avis'], $id);                      $this->getMetierInstanceValForField("dossier"),
192          if ($res != $this->OK) {                      $this->filename_prefix);
193              return $res;                  // XXX Vérifier le retour d'erreur de la méthode
194          }                  // StoreDecisionFile
195          if( $file_content = base64_decode ( $data['fichier_base64'] , TRUE )) {                  if ($r !== true) {
196              // first store the file if needed                      return $r;
197              $res = $this->f->storeDecisionFile($file_content,                  }
198                                             $data['nom_fichier'],              } else {
199                                             $this->metier_instance->valF['dossier'],                  $this->setMessage("Le contenu du fichier n'est pas valide.");
200                                             $this->filename_prefix);                  return $this->BAD_DATA;
             if ($res !== true) {  
                 return $res;  
201              }              }
         } else {  
             return _("Le contenu du fichier n'est pas valide.");  
202          }          }
203    
204          $this->metier_instance->valF['date_retour'] = $data['date_retour'];          // => FICHIER
         $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 219  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.702  
changed lines
  Added in v.778

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26