View Javadoc
1   /*
2    * Copyright (c) 2002-2023, 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.mailtask;
35  
36  import java.io.IOException;
37  import java.io.StringReader;
38  import java.io.StringWriter;
39  import java.io.Writer;
40  import java.text.DateFormat;
41  import java.text.SimpleDateFormat;
42  import java.util.Date;
43  import java.util.HashMap;
44  import java.util.List;
45  import java.util.Locale;
46  import java.util.Map;
47  
48  import javax.servlet.http.HttpServletRequest;
49  
50  import org.apache.commons.lang3.StringUtils;
51  import org.apache.commons.logging.Log;
52  import org.apache.commons.logging.LogFactory;
53  
54  import fr.paris.lutece.plugins.ctv.bo.Convention;
55  import fr.paris.lutece.plugins.ctv.bo.EmailConfig;
56  import fr.paris.lutece.plugins.ctv.bo.Emprise;
57  import fr.paris.lutece.plugins.ctv.bo.EntiteDemande;
58  import fr.paris.lutece.plugins.ctv.bo.EntiteDemande.ProfilEntite;
59  import fr.paris.lutece.plugins.ctv.bo.InfosSuperviseur;
60  import fr.paris.lutece.plugins.ctv.bo.ItemReferentiel;
61  import fr.paris.lutece.plugins.ctv.business.IConventionService;
62  import fr.paris.lutece.plugins.ctv.business.IDemandeService;
63  import fr.paris.lutece.plugins.ctv.business.IEmailConfigService;
64  import fr.paris.lutece.plugins.ctv.business.IEmpriseService;
65  import fr.paris.lutece.plugins.ctv.business.IEntiteDemandeService;
66  import fr.paris.lutece.plugins.ctv.business.IInfosSuperviseurService;
67  import fr.paris.lutece.plugins.ctv.business.IReferentielsService;
68  import fr.paris.lutece.plugins.ctv.constants.CtvConstants;
69  import fr.paris.lutece.plugins.ctv.view.object.DemandeReading;
70  import fr.paris.lutece.plugins.unittree.service.unit.IUnitUserService;
71  import fr.paris.lutece.portal.business.user.AdminUser;
72  import fr.paris.lutece.portal.service.mail.MailService;
73  import fr.paris.lutece.portal.service.spring.SpringContextService;
74  import fr.paris.lutece.portal.service.util.AppPropertiesService;
75  import freemarker.template.Configuration;
76  import freemarker.template.DefaultObjectWrapperBuilder;
77  import freemarker.template.Template;
78  import freemarker.template.TemplateException;
79  import freemarker.template.Version;
80  
81  public class EmailTask implements IEmailTask
82  {
83  
84      private static final Log LOGGER = LogFactory.getLog( EmailTask.class );
85  
86      private static final String PARAM_MESSAGE = "message";
87      private static final String PARAM_SUBJECT = "subject";
88      private static final String PARAM_BENEFICIAIRE = "beneficiaire";
89      private static final String BEAN_UNIT_USER_SERVICE = "unittree.unitUserService";
90  
91      private IEmailConfigService emailConfigService = SpringContextService.getBean( "emailConfigService" );
92      private IEntiteDemandeService entiteDemandeService = SpringContextService.getBean( "entiteDemandeService" );
93      private IEmpriseService empriseService = SpringContextService.getBean( "empriseService" );
94      private IDemandeService demandeService = SpringContextService.getBean( "demandeService" );
95      private IUnitUserService unitUserService = SpringContextService.getBean( BEAN_UNIT_USER_SERVICE );
96      private IInfosSuperviseurService infosSuperviseurService = SpringContextService.getBean( "infosSuperviseurService" );
97      private static final IReferentielsService referentielsService = SpringContextService.getBean( "referentielsService" );
98      private IConventionService conventionService = SpringContextService.getBean( "conventionService" );
99  
100     @Override
101     public void sendEmail( int mailId, int demandeId, Locale locale, HttpServletRequest request, int empriseId )
102     {
103 
104         EmailConfig emailConfig = emailConfigService.findEmailConfigById( mailId );
105         EntiteDemande demandeurTravaux = entiteDemandeService.getDemandeurByNumDemande( demandeId );
106         EntiteDemande executantTravaux = entiteDemandeService.getExecutantByNumDemande( demandeId );
107 
108         if ( demandeurTravaux.getReprensentantPrenom( ) != null )
109         {
110             demandeurTravaux.setRepresentantPrenom( demandeurTravaux.getReprensentantPrenom( ) );
111         }
112 
113         if ( demandeurTravaux.getReprensentantNom( ) != null )
114         {
115             demandeurTravaux.setRepresentantNom( demandeurTravaux.getReprensentantNom( ) );
116         }
117 
118         if ( demandeurTravaux.getReprensentantTitre( ) != null )
119         {
120             demandeurTravaux.setRepresentantTitre( demandeurTravaux.getReprensentantTitre( ) );
121         }
122 
123         if ( executantTravaux.getReprensentantPrenom( ) != null )
124         {
125             executantTravaux.setRepresentantPrenom( executantTravaux.getReprensentantPrenom( ) );
126         }
127 
128         if ( executantTravaux.getReprensentantNom( ) != null )
129         {
130             executantTravaux.setRepresentantNom( executantTravaux.getReprensentantNom( ) );
131         }
132 
133         if ( executantTravaux.getReprensentantTitre( ) != null )
134         {
135             executantTravaux.setRepresentantTitre( executantTravaux.getReprensentantTitre( ) );
136         }
137 
138         Map<String, String> processedMessage = new HashMap<String, String>( );
139         String mailDemandeurTravaux = demandeurTravaux.getContactCourriel( );
140         String mailExecutantTravaux = executantTravaux.getContactCourriel( );
141 
142         try
143         {
144             processedMessage = processMessageAndSubject( emailConfig, demandeurTravaux, executantTravaux, locale, demandeId, request, empriseId );
145             // Check if to send only to the admin fonc
146             if ( CtvConstants.EMAIL_SOUMISSION_CONVENTION == mailId )
147             {
148                 MailService.sendMailHtml( emailConfig.getRecipientsCc( ), emailConfig.getSender( ), emailConfig.getSenderEmail( ),
149                         processedMessage.get( PARAM_SUBJECT ), processedMessage.get( PARAM_MESSAGE ) );
150             }
151             // Check if there are multiple recipients
152             else
153                 if ( StringUtils.isEmpty( emailConfig.getRecipientsCc( ) ) && StringUtils.isEmpty( emailConfig.getRecipientsBcc( ) ) )
154                 {
155                     MailService.sendMailHtml( mailDemandeurTravaux, emailConfig.getSender( ), emailConfig.getSenderEmail( ),
156                             processedMessage.get( PARAM_SUBJECT ), processedMessage.get( PARAM_MESSAGE ) );
157 
158                     MailService.sendMailHtml( mailExecutantTravaux, emailConfig.getSender( ), emailConfig.getSenderEmail( ),
159                             processedMessage.get( PARAM_SUBJECT ), processedMessage.get( PARAM_MESSAGE ) );
160                 }
161                 else
162                 {
163                     MailService.sendMailHtml( mailDemandeurTravaux, emailConfig.getRecipientsCc( ), emailConfig.getRecipientsBcc( ), emailConfig.getSender( ),
164                             emailConfig.getSenderEmail( ), processedMessage.get( PARAM_SUBJECT ), processedMessage.get( PARAM_MESSAGE ) );
165 
166                     MailService.sendMailHtml( mailExecutantTravaux, emailConfig.getRecipientsCc( ), emailConfig.getRecipientsBcc( ), emailConfig.getSender( ),
167                             emailConfig.getSenderEmail( ), processedMessage.get( PARAM_SUBJECT ), processedMessage.get( PARAM_MESSAGE ) );
168                 }
169         }
170         catch( TemplateException | IOException e )
171         {
172             LOGGER.error( "template error", e );
173         }
174     }
175 
176     /**
177      * Process all the Freemarker variables inside the message
178      *
179      * @param empriseId
180      *            TODO
181      *
182      * @param emailConfig,
183      *            entiteDemande, locale
184      * @return processed message
185      * @throws IOException
186      * @throws TemplateException
187      */
188     public Map<String, String> processMessageAndSubject( EmailConfig emailConfig, EntiteDemande entiteDemande, EntiteDemande executantTravaux, Locale locale,
189             int demandeId, HttpServletRequest request, int empriseId ) throws TemplateException, IOException
190     {
191         Map<String, Object> model = new HashMap<String, Object>( );
192         Map<String, String> processedMessage = new HashMap<String, String>( );
193         String nameNatureChantier = "";
194         DemandeReading demande = demandeService.findByNumDemande( demandeId );
195         InfosSuperviseur infoSuperviseur = infosSuperviseurService.findByNumDemande( demandeId );
196 
197         List<ItemReferentiel> chantierNatureList = referentielsService.getNatureTravauxOccupation( );
198 
199         if ( !demande.getChantierNature( ).equals( "autre" ) )
200         {
201 
202             int idNatureChantier = Integer.parseInt( demande.getChantierNature( ) );
203 
204             for ( ItemReferentiel item : chantierNatureList )
205             {
206                 if ( item.getId( ) == idNatureChantier )
207                 {
208                     nameNatureChantier = item.getValue( );
209                 }
210             }
211 
212             demande.setChantierNature( nameNatureChantier );
213         }
214         else
215         {
216 
217             demande.setChantierNature( "Autre" );
218         }
219 
220         if ( infoSuperviseur != null )
221         {
222             if ( infoSuperviseur.getInfosSuperviseurDateRoc( ) != null )
223             {
224                 demande.setInfosSuperviseurDateRoc( infoSuperviseur.getInfosSuperviseurDateRoc( ) );
225             }
226 
227             if ( infoSuperviseur.getInfosSuperviseurCommentaireDemandeur( ) != null )
228             {
229                 demande.setInfosSuperviseurCommentaireDemandeur( infoSuperviseur.getInfosSuperviseurCommentaireDemandeur( ) );
230             }
231         }
232 
233         if ( entiteDemande.getProfilEntite( ) == ProfilEntite.PROFESSIONNEL )
234         {
235             demande.setBeneficiaireTravaux( entiteDemande.getRaisonSociale( ) );
236         }
237         else
238             if ( entiteDemande.getProfilEntite( ) == ProfilEntite.PARTICULIER )
239             {
240                 demande.setBeneficiaireTravaux( entiteDemande.getRepresentantNom( ) + " " + entiteDemande.getRepresentantPrenom( ) );
241             }
242 
243         if ( executantTravaux.getProfilEntite( ) == ProfilEntite.PROFESSIONNEL )
244         {
245             demande.setExecutantTravaux( executantTravaux.getRaisonSociale( ) );
246         }
247         else
248             if ( executantTravaux.getProfilEntite( ) == ProfilEntite.PARTICULIER )
249             {
250                 demande.setExecutantTravaux( executantTravaux.getRepresentantNom( ) + " " + executantTravaux.getRepresentantPrenom( ) );
251             }
252 
253         // Lien vers la demande d'occupation
254         String urlHeader = AppPropertiesService.getProperty( "email.lien.demande" );
255         String demandeLink = urlHeader + request.getContextPath( ) + "/jsp/site/Portal.jsp?page=mon_espace&action=complete&demande_id="
256                 + Integer.toString( demandeId );
257 
258         // Freemarker configuration
259         Version version = new Version( 2, 3, 21 );
260         Configuration configuration = new Configuration( version );
261         configuration.setDefaultEncoding( "UTF-8" );
262         configuration.setObjectWrapper( new DefaultObjectWrapperBuilder( version ).build( ) );
263         configuration.setLocale( locale );
264         configuration.setDateFormat( CtvConstants.EMAIL_DATE_FORMAT );
265         configuration.setDateTimeFormat( CtvConstants.EMAIL_DATE_FORMAT );
266 
267         // Emprise
268         if ( empriseId != -1 )
269         {
270             Emprise currentEmprise = empriseService.findEmpriseById( empriseId );
271             int empriseNumero = currentEmprise.getEmpriseNumero( );
272             String empriseAdresseDebut = currentEmprise.getEmpriseAdresseDebut( );
273             String empriseAdresseFin = currentEmprise.getEmpriseAdresseFin( );
274             String empriseCompleteAdresse = "";
275             Date dateFinProposee = currentEmprise.getEmpriseDateFinRemiseEnCirculationGestion( );
276             DateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy" );
277             String dateFinProposeeString = "";
278             if ( dateFinProposee != null )
279             {
280                 dateFinProposeeString = dateFormat.format( dateFinProposee );
281             }
282             if ( empriseAdresseFin.isEmpty( ) )
283             {
284                 empriseCompleteAdresse = empriseAdresseDebut;
285             }
286             else
287             {
288                 empriseCompleteAdresse = empriseAdresseDebut + " au " + empriseAdresseFin;
289             }
290             model.put( "empriseNumero", empriseNumero );
291             model.put( "empriseAdresse", empriseCompleteAdresse );
292             model.put( "empriseDateFinProposee", dateFinProposeeString );
293         }
294 
295         // infos Instructeur
296         if ( ( demandeService.getIdLastInstructeur( demandeId ) != null ) && ( demandeService.getIdLastInstructeur( demandeId ) != 0 ) )
297         {
298             int idLastInstructeur = demandeService.getIdLastInstructeur( demandeId );
299             AdminUser lastInstructeur = unitUserService.getUser( idLastInstructeur );
300             String firstName = lastInstructeur.getFirstName( );
301             String lastName = lastInstructeur.getLastName( );
302             model.put( "lastInstructeurFirstName", firstName );
303             model.put( "lastInstructeurLastName", lastName );
304         }
305 
306         // infos Convention
307         if ( ( conventionService.getAllConventionByDemandeId( demandeId ) != null ) && !conventionService.getAllConventionByDemandeId( demandeId ).isEmpty( ) )
308         {
309             Convention lastConvention = conventionService.getAllConventionByDemandeId( demandeId ).get( 0 );
310             model.put( "lastCommentaireUsagerConvention", lastConvention.getConventionCommentaireUsager( ) );
311         }
312 
313         // Adds the beneficiaire argument
314         model.put( PARAM_BENEFICIAIRE, entiteDemande );
315         model.put( "demandeId", String.valueOf( demandeId ) );
316         model.put( "demande", demande );
317         model.put( "lienDemande", demandeLink );
318 
319         // Creating a template from the task's message
320         Template template = new Template( CtvConstants.EMAIL_DEFAULT_TEMPLATE_NAME, new StringReader( emailConfig.getMessage( ) ), configuration );
321         Writer writer = new StringWriter( );
322 
323         // Replaces in the message the arguments by their values
324         template.process( model, writer );
325         processedMessage.put( PARAM_MESSAGE, writer.toString( ) );
326 
327         // Now processing the mail subject
328         template = new Template( CtvConstants.EMAIL_DEFAULT_TEMPLATE_NAME, new StringReader( emailConfig.getSubject( ) ), configuration );
329         writer = new StringWriter( );
330         template.process( model, writer );
331         processedMessage.put( PARAM_SUBJECT, writer.toString( ) );
332 
333         return processedMessage;
334     }
335 }