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.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( ), processedMessage.get( PARAM_SUBJECT ),
149                         processedMessage.get( PARAM_MESSAGE ) );
150             }
151             // Check if there are multiple recipients
152             else if ( StringUtils.isEmpty( emailConfig.getRecipientsCc( ) ) && StringUtils.isEmpty( emailConfig.getRecipientsBcc( ) ) )
153             {
154                 MailService.sendMailHtml( mailDemandeurTravaux, emailConfig.getSender( ), emailConfig.getSenderEmail( ), processedMessage.get( PARAM_SUBJECT ),
155                         processedMessage.get( PARAM_MESSAGE ) );
156 
157                 MailService.sendMailHtml( mailExecutantTravaux, emailConfig.getSender( ), emailConfig.getSenderEmail( ), processedMessage.get( PARAM_SUBJECT ),
158                         processedMessage.get( PARAM_MESSAGE ) );
159             }
160             else
161             {
162                 MailService.sendMailHtml( mailDemandeurTravaux, emailConfig.getRecipientsCc( ), emailConfig.getRecipientsBcc( ), emailConfig.getSender( ),
163                         emailConfig.getSenderEmail( ), processedMessage.get( PARAM_SUBJECT ), processedMessage.get( PARAM_MESSAGE ) );
164 
165                 MailService.sendMailHtml( mailExecutantTravaux, emailConfig.getRecipientsCc( ), emailConfig.getRecipientsBcc( ), emailConfig.getSender( ),
166                         emailConfig.getSenderEmail( ), processedMessage.get( PARAM_SUBJECT ), processedMessage.get( PARAM_MESSAGE ) );
167             }
168         }
169         catch( TemplateException | IOException e )
170         {
171             LOGGER.error( "template error", e );
172         }
173     }
174 
175     /**
176      * Process all the Freemarker variables inside the message
177      *
178      * @param empriseId
179      *            TODO
180      *
181      * @param emailConfig,
182      *            entiteDemande, locale
183      * @return processed message
184      * @throws IOException
185      * @throws TemplateException
186      */
187     public Map<String, String> processMessageAndSubject( EmailConfig emailConfig, EntiteDemande entiteDemande, EntiteDemande executantTravaux, Locale locale,
188             int demandeId, HttpServletRequest request, int empriseId ) throws TemplateException, IOException
189     {
190         Map<String, Object> model = new HashMap<String, Object>( );
191         Map<String, String> processedMessage = new HashMap<String, String>( );
192         String nameNatureChantier = "";
193         DemandeReading demande = demandeService.findByNumDemande( demandeId );
194         InfosSuperviseur infoSuperviseur = infosSuperviseurService.findByNumDemande( demandeId );
195 
196         List<ItemReferentiel> chantierNatureList = referentielsService.getNatureTravauxOccupation( );
197 
198         if ( !demande.getChantierNature( ).equals( "autre" ) )
199         {
200 
201             int idNatureChantier = Integer.parseInt( demande.getChantierNature( ) );
202 
203             for ( ItemReferentiel item : chantierNatureList )
204             {
205                 if ( item.getId( ) == idNatureChantier )
206                 {
207                     nameNatureChantier = item.getValue( );
208                 }
209             }
210 
211             demande.setChantierNature( nameNatureChantier );
212         }
213         else
214         {
215 
216             demande.setChantierNature( "Autre" );
217         }
218 
219         if ( infoSuperviseur != null )
220         {
221             if ( infoSuperviseur.getInfosSuperviseurDateRoc( ) != null )
222             {
223                 demande.setInfosSuperviseurDateRoc( infoSuperviseur.getInfosSuperviseurDateRoc( ) );
224             }
225 
226             if ( infoSuperviseur.getInfosSuperviseurCommentaireDemandeur( ) != null )
227             {
228                 demande.setInfosSuperviseurCommentaireDemandeur( infoSuperviseur.getInfosSuperviseurCommentaireDemandeur( ) );
229             }
230         }
231 
232         if ( entiteDemande.getProfilEntite( ) == ProfilEntite.PROFESSIONNEL )
233         {
234             demande.setBeneficiaireTravaux( entiteDemande.getRaisonSociale( ) );
235         }
236         else
237             if ( entiteDemande.getProfilEntite( ) == ProfilEntite.PARTICULIER )
238             {
239                 demande.setBeneficiaireTravaux( entiteDemande.getRepresentantNom( ) + " " + entiteDemande.getRepresentantPrenom( ) );
240             }
241 
242         if ( executantTravaux.getProfilEntite( ) == ProfilEntite.PROFESSIONNEL )
243         {
244             demande.setExecutantTravaux( executantTravaux.getRaisonSociale( ) );
245         }
246         else
247             if ( executantTravaux.getProfilEntite( ) == ProfilEntite.PARTICULIER )
248             {
249                 demande.setExecutantTravaux( executantTravaux.getRepresentantNom( ) + " " + executantTravaux.getRepresentantPrenom( ) );
250             }
251 
252         // Lien vers la demande d'occupation
253         String urlHeader = AppPropertiesService.getProperty( "email.lien.demande" );
254         String demandeLink = urlHeader + request.getContextPath( ) + "/jsp/site/Portal.jsp?page=mon_espace&action=complete&demande_id="
255                 + Integer.toString( demandeId );
256 
257         // Freemarker configuration
258         Version version = new Version( 2, 3, 21 );
259         Configuration configuration = new Configuration( version );
260         configuration.setDefaultEncoding( "UTF-8" );
261         configuration.setObjectWrapper( new DefaultObjectWrapperBuilder( version ).build( ) );
262         configuration.setLocale( locale );
263         configuration.setDateFormat( CtvConstants.EMAIL_DATE_FORMAT );
264         configuration.setDateTimeFormat( CtvConstants.EMAIL_DATE_FORMAT );
265 
266         // Emprise
267         if ( empriseId != -1 )
268         {
269             Emprise currentEmprise = empriseService.findEmpriseById( empriseId );
270             int empriseNumero = currentEmprise.getEmpriseNumero( );
271             String empriseAdresseDebut = currentEmprise.getEmpriseAdresseDebut( );
272             String empriseAdresseFin = currentEmprise.getEmpriseAdresseFin( );
273             String empriseCompleteAdresse = "";
274             Date dateFinProposee = currentEmprise.getEmpriseDateFinRemiseEnCirculationGestion( );
275             DateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy" );
276             String dateFinProposeeString = "";
277             if ( dateFinProposee != null )
278             {
279                 dateFinProposeeString = dateFormat.format( dateFinProposee );
280             }
281             if ( empriseAdresseFin.isEmpty( ) )
282             {
283                 empriseCompleteAdresse = empriseAdresseDebut;
284             }
285             else
286             {
287                 empriseCompleteAdresse = empriseAdresseDebut + " au " + empriseAdresseFin;
288             }
289             model.put( "empriseNumero", empriseNumero );
290             model.put( "empriseAdresse", empriseCompleteAdresse );
291             model.put( "empriseDateFinProposee", dateFinProposeeString );
292         }
293 
294         // infos Instructeur
295         if ( ( demandeService.getIdLastInstructeur( demandeId ) != null ) && ( demandeService.getIdLastInstructeur( demandeId ) != 0 ) )
296         {
297             int idLastInstructeur = demandeService.getIdLastInstructeur( demandeId );
298             AdminUser lastInstructeur = unitUserService.getUser( idLastInstructeur );
299             String firstName = lastInstructeur.getFirstName( );
300             String lastName = lastInstructeur.getLastName( );
301             model.put( "lastInstructeurFirstName", firstName );
302             model.put( "lastInstructeurLastName", lastName );
303         }
304 
305         // infos Convention
306         if ( ( conventionService.getAllConventionByDemandeId( demandeId ) != null) && !conventionService.getAllConventionByDemandeId( demandeId ).isEmpty( ))
307         {
308             Convention lastConvention = conventionService.getAllConventionByDemandeId( demandeId ).get( 0 );
309             model.put( "lastCommentaireUsagerConvention", lastConvention.getConventionCommentaireUsager( ) );
310         }
311 
312         // Adds the beneficiaire argument
313         model.put( PARAM_BENEFICIAIRE, entiteDemande );
314         model.put( "demandeId", String.valueOf( demandeId ) );
315         model.put( "demande", demande );
316         model.put( "lienDemande", demandeLink );
317 
318         // Creating a template from the task's message
319         Template template = new Template( CtvConstants.EMAIL_DEFAULT_TEMPLATE_NAME, new StringReader( emailConfig.getMessage( ) ), configuration );
320         Writer writer = new StringWriter( );
321 
322         // Replaces in the message the arguments by their values
323         template.process( model, writer );
324         processedMessage.put( PARAM_MESSAGE, writer.toString( ) );
325 
326         // Now processing the mail subject
327         template = new Template( CtvConstants.EMAIL_DEFAULT_TEMPLATE_NAME, new StringReader( emailConfig.getSubject( ) ), configuration );
328         writer = new StringWriter( );
329         template.process( model, writer );
330         processedMessage.put( PARAM_SUBJECT, writer.toString( ) );
331 
332         return processedMessage;
333     }
334 }