View Javadoc
1   /*
2    * Copyright (c) 2002-2021, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.ctv.util;
35  
36  import java.io.File;
37  import java.io.IOException;
38  import java.sql.Connection;
39  import java.sql.SQLException;
40  import java.text.SimpleDateFormat;
41  import java.util.Date;
42  import java.util.HashMap;
43  import java.util.List;
44  import java.util.Map;
45  
46  import org.apache.commons.io.FilenameUtils;
47  
48  import fr.paris.lutece.plugins.ctv.bo.ChantierOccupation;
49  import fr.paris.lutece.plugins.ctv.bo.Emprise;
50  import fr.paris.lutece.plugins.ctv.bo.InfosSuperviseur;
51  import fr.paris.lutece.plugins.ctv.bo.InfosSuperviseur.Autorisation;
52  import fr.paris.lutece.plugins.ctv.bo.InfosSuperviseur.AutorisationIntervention;
53  import fr.paris.lutece.plugins.ctv.bo.Prolongation;
54  import fr.paris.lutece.plugins.ctv.business.IChantierService;
55  import fr.paris.lutece.plugins.ctv.business.IDemandeService;
56  import fr.paris.lutece.plugins.ctv.business.IEmpriseService;
57  import fr.paris.lutece.plugins.ctv.business.IInfosSuperviseurService;
58  import fr.paris.lutece.plugins.ctv.business.IProlongationService;
59  import fr.paris.lutece.plugins.ctv.business.IReferentielsService;
60  import fr.paris.lutece.plugins.ctv.constant.TypeDemande;
61  import fr.paris.lutece.plugins.ctv.service.IEditionService;
62  import fr.paris.lutece.plugins.ctv.view.object.DemandeReading;
63  import fr.paris.lutece.plugins.unittree.service.unit.IUnitService;
64  import fr.paris.lutece.portal.service.database.AppConnectionService;
65  import fr.paris.lutece.portal.service.spring.SpringContextService;
66  import fr.paris.lutece.portal.service.util.AppLogService;
67  import fr.paris.lutece.portal.service.util.AppPropertiesService;
68  
69  public class GestionPDFUtil
70  {
71  
72      private static final IUnitService unitService = SpringContextService.getBean( IUnitService.BEAN_UNIT_SERVICE );
73      private static final IChantierService chantierService = SpringContextService.getBean( "chantierService" );
74      private static final IReferentielsService referentielsService = SpringContextService.getBean( "referentielsService" );
75      private static final IEmpriseService empriseService = SpringContextService.getBean( "empriseService" );
76      private static final IEditionService editionService = SpringContextService.getBean( "editionService" );
77      private static final IProlongationService prolongationService = SpringContextService.getBean( "prolongationService" );
78      private static final IInfosSuperviseurService infosSuperviseurService = SpringContextService.getBean( "infosSuperviseurService" );
79      private static final IDemandeService demandeService = SpringContextService.getBean( "demandeService" );
80  
81      public static final String MARK_ERROR_GEN_PDF = "error_gen_pdf";
82      public static final String MARK_TYPE_DEMANDE = "D";
83      public static final String MARK_TYPE_PROLONGATION = "P";
84      public static final String MARK_TYPE_ANNULATION = "A";
85      public static final String MARK_TYPE_GARANTIE = "G";
86  
87  
88      private static int nbDocToGen = 0;
89  
90      public static int gestionPDF( DemandeReading demande, String type, String empriseId, String contextPath )
91      {
92          int errorNumber = 0;
93          int numDemande = demande.getDemandeNumero( );
94          InfosSuperviseur infos = infosSuperviseurService.findByNumDemande( numDemande );
95          Autorisation typeAutorisationOccupation = infos.getInfosSuperviseurAutorisation( );
96          AutorisationIntervention typeAutorisationIntervention = infos.getInfosSuperviseurTypeAutorisation( );
97  
98          if ( ( typeAutorisationOccupation != null ) || ( typeAutorisationIntervention != null ) || MARK_TYPE_ANNULATION.equals( type ) )
99          {
100             nbDocToGen = 0;
101             Map<Integer, byte [ ]> editions = generationAutorisations( numDemande,
102                     typeAutorisationOccupation != null ? typeAutorisationOccupation : typeAutorisationIntervention, type, contextPath, empriseId );
103             for ( byte [ ] edition : editions.values( ) )
104             {
105                 if ( edition.length <= 2000 )
106                 {
107                     // erreur de génération du PDF
108                     errorNumber = 1;
109                 }
110             }
111             if ( editions.size( ) < nbDocToGen )
112             {
113                 // erreur de génération du PDF
114                 errorNumber = 1;
115             }
116             if ( errorNumber == 0 )
117             {
118                 try
119                 {
120                     writeEditionsOnServer( editions, demande, type, empriseId );
121                 }
122                 catch( IOException e )
123                 {
124                     // erreur de dépot du PDF
125                     errorNumber = 2;
126                 }
127             }
128         }
129         return errorNumber;
130     }
131 
132     private static Map<Integer, byte [ ]> generationAutorisations( int numDemande, Enum typeAutorisation, String type, String contextUrl, String idEmprise )
133     {
134         Map<Integer, byte [ ]> editions = new HashMap<Integer, byte [ ]>( );
135         Connection connection = AppConnectionService.getDefaultConnectionService( ).getConnection( );
136 
137         DemandeReading demande = demandeService.findByNumDemande( numDemande );
138         TypeDemande typeDemande = demande.getDemandeType( );
139 
140         if ( type.equals( MARK_TYPE_DEMANDE ) )
141 
142         {
143             List<Emprise> emprises = empriseService.findEmprisesByDemandeId( numDemande );
144             for ( Emprise empriseRead : emprises )
145             {
146                 int empriseId = empriseRead.getEmpriseId( );
147                 nbDocToGen++;
148                 if ( typeAutorisation.equals( Autorisation.PERMISSION_VOIRIE ) )
149                 {
150                     editions.put( empriseId, editionService.getPermissionVoirie( connection, contextUrl, numDemande, empriseId ) );
151                 }
152                 else
153                     if ( typeAutorisation.equals( Autorisation.PERMIS_STATIONNEMENT ) )
154                     {
155                         editions.put( empriseId, editionService.getPermisStationnement( connection, contextUrl, numDemande, empriseId ) );
156                     }
157                     else
158                         if ( typeAutorisation.equals( AutorisationIntervention.BARRAGE ) || typeAutorisation.equals( AutorisationIntervention.FOUILLE )
159                                 || typeAutorisation.equals( AutorisationIntervention.AUTORISATION_DISPENSEE ) )
160                         {
161                             editions.put( empriseId, editionService.getAutorisationIntervention( connection, contextUrl, numDemande, empriseId ) );
162                         }
163             }
164         }
165         else
166             if ( type.equals( MARK_TYPE_PROLONGATION ) )
167             {
168                 int empriseId = Integer.parseInt( idEmprise );
169                 Prolongation prolongation = prolongationService.findLastProlongationByEmpriseId( empriseId );
170                 nbDocToGen++;
171                 int prolongationNum = prolongation.getProlongationNumero( );
172 
173                 if ( TypeDemande.OCCUPATION.equals( typeDemande ) )
174                 {
175                     editions.put( empriseId,
176                             editionService.getPermissionProlongationOccupation( connection, contextUrl, numDemande, empriseId, prolongationNum ) );
177                 }
178                 else
179                     if ( TypeDemande.INTERVENTION.equals( typeDemande ) )
180                     {
181                         editions.put( empriseId,
182                                 editionService.getAutorisationProlongationIntervention( connection, contextUrl, numDemande, empriseId, prolongationNum ) );
183                     }
184 
185             }
186             else
187                 if ( type.equals( MARK_TYPE_ANNULATION ) )
188                 {
189                     int empriseId = Integer.parseInt( idEmprise );
190                     nbDocToGen++;
191                     editions.put( empriseId, editionService.getAnnulationEmprise( connection, contextUrl, numDemande, empriseId ) );
192                 } else if ( type.equals( MARK_TYPE_GARANTIE ) )
193 
194                 {
195                     int empriseId = Integer.parseInt( idEmprise );
196                     nbDocToGen++;
197                     editions.put( empriseId, editionService.getInfoEmpriseGarantie(connection, contextUrl, numDemande, empriseId) );
198                 }
199 
200         try
201         {
202             connection.close();
203         } catch ( SQLException e )
204         {
205             AppLogService.error( "Erreur lors de la fermeture de la connexion" + e );
206         }
207 
208         return editions;
209     }
210 
211     private static boolean ravalementSansToitureGen( String nature, Date dateDebut, Date dateFin, TypeDemande typeDemande )
212     {
213         int diffInDays = (int) ( ( dateFin.getTime( ) - dateDebut.getTime( ) ) / ( 1000 * 60 * 60 * 24 ) );
214         if ( nature.equals( "Ravalement sans toiture" ) )
215         {
216             if ( ( diffInDays > 90 ) && typeDemande.equals( TypeDemande.OCCUPATION ) )
217             {
218                 return true;
219             }
220             else
221             {
222                 return false;
223             }
224         }
225         else
226         {
227             return true;
228         }
229     }
230 
231     private static void writeEditionsOnServer( Map<Integer, byte [ ]> editions, DemandeReading demande, String type, String idEmprise ) throws IOException
232     {
233         String path = AppPropertiesService.getProperty( "repertoire.depot.autorisation.pdf" );
234         String pathUpload = AppPropertiesService.getProperty( "ctv.directory.upload" );
235         String sectorLabel = unitService.findBySectorIdWithoutChildren( demande.getDemandeSectorId( ) ).getLabel( );
236         String fullPath = path + "/" + sectorLabel;
237         String today = new SimpleDateFormat( "yyyyMMdd" ).format( new Date( ) );
238         int demandeId = demande.getDemandeNumero( );
239         TypeDemande typeDemande = demande.getDemandeType( );
240 
241         createDirectories( fullPath );
242         if ( type.equals( MARK_TYPE_ANNULATION ) )
243         {
244             for ( int empriseId : editions.keySet( ) )
245             {
246                 Emprise emprise = empriseService.findEmpriseById( empriseId );
247 
248                 ChantierOccupation chantier = chantierService.getChantierOccupationByNumDemande( demandeId );
249                 String nature = "";
250                 Date dateDebut = emprise.getEmpriseDateDebut( );
251                 Date dateFin = emprise.getEmpriseDateFin( );
252                 Date dateFinGestion = emprise.getEmpriseDateFinRemiseEnCirculationGestion( );
253                 byte [ ] edition = editions.get( empriseId );
254                 String fullPathCTV = getUploadDirectoryByChronology( pathUpload, emprise.getEmpriseDateCreation( ), empriseId );
255                 createDirectories( fullPathCTV );
256                 boolean genOK;
257                 if ( chantier.getChantierNature( ) != null )
258                 {
259                     String natureId = chantier.getChantierNature( );
260                     if ( !natureId.equals( "autre" ) )
261                     {
262                         nature = referentielsService.findItemById( Integer.parseInt( natureId ) ).getValue( );
263                     }
264                 }
265                 if ( dateFinGestion == null )
266                 {
267                     genOK = ravalementSansToitureGen( nature, dateDebut, dateFin, typeDemande );
268                 }
269                 else
270                 {
271                     genOK = ravalementSansToitureGen( nature, dateDebut, dateFinGestion, typeDemande );
272                 }
273                 String fileCTV = fullPathCTV + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + emprise.getEmpriseNumero( ) + "-" + type + ".pdf";
274                 editionService.writeEditionOnServeur( edition, fileCTV );
275 
276                 if ( genOK && TypeDemande.OCCUPATION.equals( typeDemande ) )
277                 {
278                     String fileDU = fullPath + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + emprise.getEmpriseNumero( ) + "-" + type + ".pdf";
279                     editionService.writeEditionOnServeur( edition, fileDU );
280                 }
281 
282             }
283         }
284         else
285             if ( type.equals( MARK_TYPE_DEMANDE ) )
286             {
287                 for ( int empriseId : editions.keySet( ) )
288                 {
289                     Emprise emprise = empriseService.findEmpriseById( empriseId );
290                     Date dateDebut = emprise.getEmpriseDateDebut( );
291                     Date dateFin = emprise.getEmpriseDateFin( );
292                     ChantierOccupation chantier = chantierService.getChantierOccupationByNumDemande( demandeId );
293                     byte [ ] edition = editions.get( empriseId );
294                     String nature = "";
295                     if ( chantier.getChantierNature( ) != null )
296                     {
297                         String natureId = chantier.getChantierNature( );
298                         if ( !natureId.equals( "autre" ) )
299                         {
300                             nature = referentielsService.findItemById( Integer.parseInt( natureId ) ).getValue( );
301                         }
302                     }
303                     boolean genOK = ravalementSansToitureGen( nature, dateDebut, dateFin, typeDemande );
304                     if ( genOK && TypeDemande.OCCUPATION.equals( typeDemande ) )
305                     {
306                         String fileDU = fullPath + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + emprise.getEmpriseNumero( ) + "-" + type
307                                 + ".pdf";
308                         editionService.writeEditionOnServeur( edition, fileDU );
309                     }
310                     String fullPathCTV = getUploadDirectoryByChronology( pathUpload, emprise.getEmpriseDateCreation( ), empriseId );
311                     createDirectories( fullPathCTV );
312                     String fileCTV = fullPathCTV + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + emprise.getEmpriseNumero( ) + "-" + type
313                             + ".pdf";
314                     editionService.writeEditionOnServeur( edition, fileCTV );
315                 }
316 
317             }
318             else
319                 if ( type.equals( MARK_TYPE_PROLONGATION ) )
320                 {
321                     for ( byte [ ] edition : editions.values( ) )
322                     {
323                         int empriseId = Integer.parseInt( idEmprise );
324                         Emprise emprise = empriseService.findEmpriseById( empriseId );
325                         Prolongation prolongation = prolongationService.findLastProlongationByEmpriseId( empriseId );
326                         int prolongationNumero = prolongation.getProlongationNumero( );
327                         int empriseNumero = emprise.getEmpriseNumero( );
328                         Date dateDebut = emprise.getEmpriseDateDebut( );
329                         Date dateFin = emprise.getEmpriseDateFin( );
330                         Date dateFinGestion = emprise.getEmpriseDateFinRemiseEnCirculationGestion( );
331                         ChantierOccupation chantier = chantierService.getChantierOccupationByNumDemande( demandeId );
332                         String nature = "";
333                         boolean genOK;
334                         if ( chantier.getChantierNature( ) != null )
335                         {
336                             String natureId = chantier.getChantierNature( );
337                             if ( !natureId.equals( "autre" ) )
338                             {
339                                 nature = referentielsService.findItemById( Integer.parseInt( natureId ) ).getValue( );
340                             }
341                         }
342                         if ( dateFinGestion == null )
343                         {
344                             genOK = ravalementSansToitureGen( nature, dateDebut, dateFin, typeDemande );
345                         }
346                         else
347                         {
348                             genOK = ravalementSansToitureGen( nature, dateDebut, dateFinGestion, typeDemande );
349                         }
350 
351                         if ( genOK && TypeDemande.OCCUPATION.equals( typeDemande ) )
352                         {
353                             String fileDU = fullPath + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + empriseNumero + "-" + prolongationNumero
354                                     + "-" + type + ".pdf";
355                             editionService.writeEditionOnServeur( edition, fileDU );
356                         }
357                         String fullPathCTV = getUploadDirectoryByChronology( pathUpload, emprise.getEmpriseDateCreation( ), empriseId );
358                         createDirectories( fullPathCTV );
359                         String fileCTV = fullPathCTV + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + empriseNumero + "-" + prolongationNumero
360                                 + "-" + type + ".pdf";
361                         editionService.writeEditionOnServeur( edition, fileCTV );
362                     }
363                 } else if(MARK_TYPE_GARANTIE.equals(type)) {
364                 	for ( byte [ ] edition : editions.values( ) )
365                     {
366                         int empriseId = Integer.parseInt( idEmprise );
367                         Emprise emprise = empriseService.findEmpriseById( empriseId );
368                         
369                         String fileDU = fullPath + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + emprise.getEmpriseNumero( ) + "-" + type
370                                 + ".pdf";
371                         editionService.writeEditionOnServeur(edition, fileDU, true, true, demandeId, empriseId);
372                         
373                 		String fullPathCTV = getUploadDirectoryByChronology( pathUpload, emprise.getEmpriseDateCreation( ), empriseId );
374                         createDirectories( fullPathCTV );
375                         String fileCTV = fullPathCTV + "/" + sectorLabel + "-" + today + "-N_" + demandeId + "-" + emprise.getEmpriseNumero( ) + "-" + type
376                                 + ".pdf";
377                         editionService.writeEditionOnServeur(edition, fileCTV, true, false, demandeId, empriseId);
378                     }
379                 }
380     }
381 
382     private static void createDirectories( String fullPath )
383     {
384         File directory = new File( fullPath );
385         if ( !directory.exists( ) )
386         {
387             directory.mkdirs( );
388         }
389     }
390 
391     private static String getUploadDirectoryByChronology( String uploadDirectory, Date dateCreationDossier, int empriseId )
392     {
393         uploadDirectory = FilenameUtils.concat( uploadDirectory, "emprises" );
394         if ( dateCreationDossier != null )
395         {
396             SimpleDateFormat yearFormat = new SimpleDateFormat( "yyyy" );
397             SimpleDateFormat monthFormat = new SimpleDateFormat( "MM" );
398             String year = yearFormat.format( dateCreationDossier );
399             uploadDirectory = FilenameUtils.concat( uploadDirectory, year );
400             String month = monthFormat.format( dateCreationDossier );
401             uploadDirectory = FilenameUtils.concat( uploadDirectory, month );
402         }
403         uploadDirectory = FilenameUtils.concat( uploadDirectory, Integer.toString( empriseId ) );
404         uploadDirectory = FilenameUtils.concat( uploadDirectory, "autorisations" );
405         return uploadDirectory;
406     }
407 }