/[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 760 by fmichon, Tue Nov 20 10:00:16 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      /*      /**
27       * Constructor.       * Constructeur
28       *       *
29       * Calls it's parent constructor to establish a DB connection       * @todo XXX Ajouter la description des attributs
30       * and initializes the instance variables       */
      */      
31      public function __construct() {      public function __construct() {
32    
33            // Appel du constructeur parent
34          parent::__construct();          parent::__construct();
35          /*$this->date_limite = null;  
36          $this->date_retour = null;          //
         $this->date_envoi = null;  
         $this->dossier_id = null;*/  
         $this->decisions = null;  
37          $this->metier_instance = null;          $this->metier_instance = null;
38          $this->filename_prefix = null;          $this->filename_prefix = null;
39          $this->filename = null;          $this->filename = null;
40    
41      }      }
42        
43            /**
44      /*       * Destructeur
45       * Destructor       */
      *  
      * Call's its parent's destructor.  
      */      
46      public function __destruct() {      public function __destruct() {
47    
48            // Appel du destructeur parent
49          parent::__destruct();          parent::__destruct();
50    
51      }      }
       
52    
53      /*      /**
54       * Verifies that the date_retour received in the incomming data       * Cette méthode permet de modifier une consultation existante pour lui
55       * is in the (date_envoi, date_limite) interval. Also, check that       * ajouter les informations de retour d'avis.
56       * there is no date_retour set for the consultation, as well as the       *
57       * validity of the date itself       * @param mixed $request_data Les données JSON reçues
58       * @param string $date_str The date_retour recived in the request       * @param string $id L'identifiant de la ressource
59       * @param string $id The discussion id       */
60       * @return string OK on success, BAD_DATA if the data sent is invalid,      public function consultationDecision($data, $id) {
61       * KO otherwise  
62       */              // Si l'identifiant envoyé n'est pas un numérique alors on ajoute un
63      private function checkDates($date_str, $id) {          // message d'informations et on retourne un résultat d'erreur
64          // check that the consultation exists in DB          if (!is_numeric($id)) {
65          if (empty($this->metier_instance->valF['date_limite'])) {              $this->setMessage("L'identifiant '".$id."' fourni est incorrect.");
             $this->setMessage("La consultation ".$id." n'était pas trouvé");  
66              return $this->BAD_DATA;              return $this->BAD_DATA;
67          }          }
68    
69          // check that the date_retour does not already exist          // On instancie la consultation sur laquelle porte la requête
70          if (!empty($this->metier_instance->valF['date_retour'])) {          $this->metier_instance = new consultation($id, $this->db, 0);
71              $this->setMessage("Le date de retour de la consultation ".$id.  
72                  " existe déjà");          // On vérifie si l'instanciation a produit une erreur de base de données
73              return $this->BAD_DATA;          // alors on ajoute un message d'informations et on retourne un résultat
74          }          // d'erreur
75                    if (isset($this->metier_instance->errors['db_debuginfo'])
76          // check that the date is valid              && !empty($this->metier_instance->errors['db_debuginfo'])) {
77          $date = explode("/", $date_str);              $this->setMessage("Erreur lors de la récupération de la".
78          if (!checkdate($date[1], $date[0], $date[2])) {                                " consultation '".$id."'.");
79              $this->setMessage("Le date de retour fourni pour la consultation ".              return $this->KO;
80                                $id." n'est pas bon (en bon format)");          }
81              return $this->BAD_DATA;  
82          }          // Si l'identifiant de la consultation instanciée est différent de
83                    // l'identifiant envoyé alors on ajoute un message d'informations et
84          if (!$this->dateInsideInterval($date_str,          // on retourne un résultat d'erreur
85                      $this->metier_instance->valF['date_envoi'],          if ($id != $this->getMetierInstancePrimaryKeyValue()) {
86                      $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");  
87              return $this->BAD_DATA;              return $this->BAD_DATA;
88          }          }
         return $this->OK;  
     }  
89    
90            // Si la consultation possède déjà une date de retour ou un avis ou une
91            // motivation alors on ajoute un message d'informations et on retourne
92            // un résultat d'erreur
93            $date_retour = $this->getMetierInstanceValForField("date_retour");
94            $avis = $this->getMetierInstanceValForField("avis");
95            $motivation = $this->getMetierInstanceValForField("motivation");
96            if (!empty($date_retour) || !empty($avis) || !empty($motivation)) {
97                $this->setMessage("Un retour d'avis a déjà été rendu pour la".
98                                  " consultation '".$id."'.");
99                return $this->BAD_DATA;
100            }
101    
102      /*          // Le format de la date de retour valide est 'JJ/MM/AAAA'
103       * Verifies that the avis received in the incomming data corresponds          // Si la donnée fournie n'est pas valide alors on ajoute
104       * to one of the avis found in DB.          // un message d'informations et on retourne un résultat d'erreur
105       * @param string $avis The avis recived in the request          $date_retour = explode("/", $data['date_retour']);
106       * @param string $id The discussion id          if (count($date_retour)!= 3
107       * @return string OK on success, KO otherwise              || !checkdate($date_retour[1], $date_retour[0], $date_retour[2])) {
108       */              $this->setMessage("Le format de la date de retour d'avis fournie".
109      private function avisValid($avis, $id) {                                " pour la consultation '".$id."' n'est pas".
110          // get all of the decisions possible from table avis_decision                                " correct.");
111          $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;  
112          }          }
113    
114          $this->decisions = array();          // Si la date de retour de l'avis ne se situe pas entre la date d'envoi
115          while ($row =& $res->fetchRow(DB_FETCHMODE_ORDERED)) {          // de la consultation et la date limite de retour d'avis alors on ajoute
116              $this->decisions[$row[0]] = $row[1];          // un message d'informations et on retourne un résultat d'erreur
117            $date_retour = $data['date_retour'];
118            $date_envoi = $this->getMetierInstanceValForField("date_envoi");
119            $date_limite = $this->getMetierInstanceValForField("date_limite");
120            if (!$this->dateInsideInterval($date_retour,
121                                           $date_envoi, $date_limite)) {
122                $this->setMessage("La date de retour d'avis fournie pour la".
123                                  " consultation '".$id."' ne se trouve pas entre".
124                                  " la date d'envoi et la date limite.");
125                return $this->BAD_DATA;
126          }          }
127          $res->free();  
128                    // => DATE DE RETOUR
129          // check that the decision received corresponds to a decision in DB          $this->metier_instance->valF['date_retour'] = $data['date_retour'];
130          if (!in_array($avis, array_keys($this->decisions))) {  
131              $this->setMessage(          // Si l'avis fourni ne correspond pas à la liste d'avis valides alors
132                  "L'avis de consultation reçu n'est pas feasible");          // on ajoute un message d'informations et on retourne un résultat
133              return $this->KO;          // d'erreur
134            $avis = $data["avis"];
135            $avis_valid = array("Favorable",
136                                "Favorable avec réserve", "Défavorable", );
137            if (!in_array($avis, $avis_valid)) {
138                $this->setMessage("L'avis du retour d'avis fourni pour la".
139                                  " consultation '".$id."' n'est pas correct.");
140                return $this->BAD_DATA;
141          }          }
         return $this->OK;  
     }  
142    
143                // Récupération de la référence vers un avis_consultation existant
144      /*          // On liste les avis possibles et on récupère l'identifiant
145       * Verifies that all the data concerning file to be stored (if any)          // correspondant au libellé transmis en paramètre
146       * are present in full or not present at all          $sql = " SELECT avis_consultation, libelle ";
147       * @param mixed $data The data recived in the request          $sql .= " FROM ".DB_PREFIXE."avis_consultation ";
148       * @param string $id The discussion id          $sql .= " WHERE ((avis_consultation.om_validite_debut IS NULL ";
149       * @return string OK on success, KO otherwise          $sql .= " AND (avis_consultation.om_validite_fin IS NULL ";
150       */          $sql .= " OR avis_consultation.om_validite_fin > CURRENT_DATE)) ";
151      private function fichierDataValid(&$data, $id) {          $sql .= " OR (avis_consultation.om_validite_debut <= CURRENT_DATE ";
152          // do the check          $sql .= " AND (avis_consultation.om_validite_fin IS NULL ";
153          if (!isset($data['nom_fichier']) && isset($data['fichier_base64'])          $sql .= " OR avis_consultation.om_validite_fin > CURRENT_DATE))) ";
154              || isset($data['nom_fichier']) && !isset($data['fichier_base64'])) {          $res = $this->db->query($sql);
155              $this->setMessage(          // Logger
156                      "Les données de fichier d'avis de la consultation ".$id.          $this->addToLog("consultationDecision(): db->query(\"".$sql."\")",
157                      " ne sont pas complètes ");                          VERBOSE_MODE);
158    
159            // Si une erreur de base de données se produit sur cette requête
160            // alors on retourne un résultat d'erreur
161            if ($this->f->isDatabaseError($res, true)) {
162                $this->setMessage("Erreur lors de la récupération des avis pour la".
163                                  " consultation '".$id."'.");
164              return $this->KO;              return $this->KO;
165          }          }
         return $this->OK;  
     }  
166    
167      /*          // Récupération de la référence vers un avis_consultation existant
168       * Called when one of the external services sends its recommendation          // On liste les avis possibles et on récupère l'identifiant
169       * as a responde to a demand issued by openfoncier.          // correspondant au libellé transmis en paramètre
170       * @param mixed $data The array containing building number.          $avis = $data["avis"];
171       * @param string $id The ID of the dossier.          $avis_id = NULL;
172       * @return bool 'OK'          while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
173       */              if ($avis == $row["libelle"]) {
174      public function consultationDecision($data, $id) {                  $avis_id = $row["avis_consultation"];
175                          break;
176          // get all of the dates for the consultation from DB              }
177          // and check the date received is ok with respect to the          }
178          // time interval set by (date_envoi, date_limite)          $res->free();
179          // equally extract the dossier ID while at it  
180          $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
181                    // un message d'informations et on retourne un résultat d'erreur
182          // check that the consultation was found          if (is_null($avis_id)) {
183          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");  
184              return $this->KO;              return $this->KO;
185          }          }
186            
187          // check that the date sent is applicable          // => AVIS
188          $res = $this->checkDates($data['date_retour'], $id);          $this->metier_instance->valF['avis_consultation'] = $avis_id;
189          if ($res != $this->OK) {  
190              return $res;          // Si un nom de fichier (nom_fichier) est fourni mais pas un contenu de
191            // fichier (fichier_base64) alors on ajoute un message d'informations
192            // et on retourne un résultat d'erreur
193            if (isset($data['nom_fichier']) && !isset($data['fichier_base64'])
194                || isset($data['fichier_base64']) && !isset($data['nom_fichier'])) {
195                $this->setMessage("Les informations du fichier de retour d'avis".
196                                  " fournies pour la consultation '".$id."' ne".
197                                  " sont pas correctes.");
198                return $this->BAD_DATA;
199          }          }
200    
201          // set the prefix for the filename to use in case file data          //
         // was received  
202          $this->filename_prefix = "consultation_".$id."_";          $this->filename_prefix = "consultation_".$id."_";
203          // check that data regarding fichier is complete  
204          $res = $this->fichierDataValid($data, $id);          //
205          if ($res != $this->OK) {          if (isset($data['fichier_base64'])) {
206              return $res;              //
207          }              if ($file_content = base64_decode($data['fichier_base64'], true)) {
208                            //
209          // check that the decision sent is one of the decisions found in DB                  $r = $this->f->storeDecisionFile($file_content,
210          // and store the possible decisions in $this->decisions                      $data['nom_fichier'],
211          $res = $this->avisValid($data['avis'], $id);                      $this->getMetierInstanceValForField("dossier"),
212          if ($res != $this->OK) {                      $this->filename_prefix);
213              return $res;                  // XXX Vérifier le retour d'erreur de la méthode
214          }                  // StoreDecisionFile
215          if( $file_content = base64_decode ( $data['fichier_base64'] , TRUE )) {                  if ($r !== true) {
216              // first store the file if needed                      return $r;
217              $res = $this->f->storeDecisionFile($file_content,                  }
218                                             $data['nom_fichier'],              } else {
219                                             $this->metier_instance->valF['dossier'],                  $this->setMessage("Le contenu du fichier n'est pas valide.");
220                                             $this->filename_prefix);                  return $this->BAD_DATA;
             if ($res !== true) {  
                 return $res;  
221              }              }
         } else {  
             return _("Le contenu du fichier n'est pas valide.");  
222          }          }
223    
224          $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;  
225          if (isset($data['nom_fichier'])) {          if (isset($data['nom_fichier'])) {
226              $this->metier_instance->valF['fichier'] = $this->filename_prefix . $data['nom_fichier'];              $this->metier_instance->valF['fichier'] = $this->filename_prefix.$data['nom_fichier'];
227          }          }
228    
229            // => MOTIVATION
230          if (isset($data['motivation'])) {          if (isset($data['motivation'])) {
231              $this->metier_instance->valF['motivation'] = $data['motivation'];              $this->metier_instance->valF['motivation'] = $data['motivation'];
232          }          }
233            
234            // => LU
235            $this->metier_instance->valF['lu'] = false;
236    
237            // Exécution du traitement
238          $ret = parent::modifier($this->metier_instance->valF,          $ret = parent::modifier($this->metier_instance->valF,
239              "L'avis de la consultation $id a été pris en compte",              "L'avis de la consultation $id a été pris en compte",
240              "Erreur pendant le traitemande de la demande pour la consultation $id");              "Erreur pendant le traitemande de la demande pour la consultation $id");
241    
242            // XXX vérifier ce retour car filename n'est jamais rempli
243          if ($ret != $this->OK) {          if ($ret != $this->OK) {
244              // delete the file on disk              // delete the file on disk
245              if (isset($data['nom_fichier'])) {              if (isset($data['nom_fichier'])) {
# Line 219  class ConsultationManager extends Metier Line 247  class ConsultationManager extends Metier
247              }              }
248          }          }
249          return $ret;          return $ret;
250    
251      }      }
252        
       
253  }  }
254    
255  ?>  ?>

Legend:
Removed from v.702  
changed lines
  Added in v.760

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26