View Javadoc
1   /*
2    * Copyright (c) 2002-2018, Mairie de 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.appointment.web;
35  
36  import java.io.FileNotFoundException;
37  import java.io.IOException;
38  import java.time.LocalDate;
39  import java.time.LocalTime;
40  import java.util.ArrayList;
41  import java.util.HashMap;
42  import java.util.List;
43  import java.util.Locale;
44  import java.util.Map;
45  import java.util.StringJoiner;
46  import java.util.stream.Collectors;
47  
48  import javax.servlet.http.HttpServletRequest;
49  import javax.servlet.http.HttpSession;
50  
51  import org.apache.commons.collections.CollectionUtils;
52  import org.apache.commons.fileupload.FileItem;
53  import org.apache.commons.lang3.StringUtils;
54  
55  import fr.paris.lutece.plugins.appointment.business.appointment.Appointment;
56  import fr.paris.lutece.plugins.appointment.business.calendar.CalendarTemplateHome;
57  import fr.paris.lutece.plugins.appointment.business.form.Form;
58  import fr.paris.lutece.plugins.appointment.business.message.FormMessage;
59  import fr.paris.lutece.plugins.appointment.business.message.FormMessageHome;
60  import fr.paris.lutece.plugins.appointment.business.slot.Slot;
61  import fr.paris.lutece.plugins.appointment.log.LogUtilities;
62  import fr.paris.lutece.plugins.appointment.service.AppointmentResourceIdService;
63  import fr.paris.lutece.plugins.appointment.service.AppointmentService;
64  import fr.paris.lutece.plugins.appointment.service.AppointmentUtilities;
65  import fr.paris.lutece.plugins.appointment.service.CategoryService;
66  import fr.paris.lutece.plugins.appointment.service.ClosingDayService;
67  import fr.paris.lutece.plugins.appointment.service.EntryService;
68  import fr.paris.lutece.plugins.appointment.service.FormMessageService;
69  import fr.paris.lutece.plugins.appointment.service.FormService;
70  import fr.paris.lutece.plugins.appointment.service.SlotService;
71  import fr.paris.lutece.plugins.appointment.service.Utilities;
72  import fr.paris.lutece.plugins.appointment.web.dto.AppointmentFormDTO;
73  import fr.paris.lutece.portal.business.user.AdminUser;
74  import fr.paris.lutece.portal.service.admin.AccessDeniedException;
75  import fr.paris.lutece.portal.service.admin.AdminUserService;
76  import fr.paris.lutece.portal.service.captcha.CaptchaSecurityService;
77  import fr.paris.lutece.portal.service.i18n.I18nService;
78  import fr.paris.lutece.portal.service.image.ImageResource;
79  import fr.paris.lutece.portal.service.message.AdminMessage;
80  import fr.paris.lutece.portal.service.message.AdminMessageService;
81  import fr.paris.lutece.portal.service.plugin.Plugin;
82  import fr.paris.lutece.portal.service.plugin.PluginService;
83  import fr.paris.lutece.portal.service.rbac.RBACService;
84  import fr.paris.lutece.portal.service.util.AppLogService;
85  import fr.paris.lutece.portal.service.util.AppPathService;
86  import fr.paris.lutece.portal.service.util.AppPropertiesService;
87  import fr.paris.lutece.portal.service.workflow.WorkflowService;
88  import fr.paris.lutece.portal.service.workgroup.AdminWorkgroupService;
89  import fr.paris.lutece.portal.util.mvc.admin.annotations.Controller;
90  import fr.paris.lutece.portal.util.mvc.commons.annotations.Action;
91  import fr.paris.lutece.portal.util.mvc.commons.annotations.View;
92  import fr.paris.lutece.portal.util.mvc.utils.MVCUtils;
93  import fr.paris.lutece.portal.web.upload.MultipartHttpServletRequest;
94  import fr.paris.lutece.portal.web.util.LocalizedPaginator;
95  import fr.paris.lutece.util.html.Paginator;
96  import fr.paris.lutece.util.url.UrlItem;
97  
98  /**
99   * This class provides the user interface to manage AppointmentForm features ( manage, create, modify, copy, remove )
100  * 
101  * @author L.Payen
102  * 
103  */
104 @Controller( controllerJsp = "ManageAppointmentForms.jsp", controllerPath = "jsp/admin/plugins/appointment/", right = AppointmentFormJspBean.RIGHT_MANAGEAPPOINTMENTFORM )
105 public class AppointmentFormJspBean extends AbstractAppointmentFormAndSlotJspBean
106 {
107 
108     /**
109      * Right to manage appointment forms
110      */
111     public static final String RIGHT_MANAGEAPPOINTMENTFORM = "APPOINTMENT_FORM_MANAGEMENT";
112     private static final long serialVersionUID = -615061018633136997L;
113     private static final CaptchaSecurityService _captchaSecurityService = new CaptchaSecurityService( );
114     private final EntryService _entryService = EntryService.getService( );
115     private int _nDefaultItemsPerPage;
116 
117     // templates
118     private static final String TEMPLATE_MANAGE_APPOINTMENTFORMS = "/admin/plugins/appointment/appointmentform/manage_appointmentforms.html";
119     private static final String TEMPLATE_CREATE_APPOINTMENTFORM = "/admin/plugins/appointment/appointmentform/create_appointmentform.html";
120     private static final String TEMPLATE_MODIFY_APPOINTMENTFORM = "/admin/plugins/appointment/appointmentform/modify_appointmentform.html";
121     private static final String TEMPLATE_MODIFY_APPOINTMENTFORM_MESSAGES = "/admin/plugins/appointment/appointmentform/modify_appointmentform_messages.html";
122 
123     // Parameters
124     private static final String PARAMETER_ID_FORM = "id_form";
125     private static final String PARAMETER_ERROR = "error";
126     private static final String PARAMETER_BACK = "back";
127     private static final String PARAMETER_PAGE_INDEX = "page_index";
128     private static final String PARAMETER_FROM_DASHBOARD = "fromDashboard";
129     private static final String PARAMETER_ICON_RESSOURCE = "image_resource";
130     private static final String PARAMETER_DELETE_ICON = "deleteIcon";
131     private static final String PARAMETER_GEOLOC_ADDRESS = "geoloc_address";
132     private static final String PARAMETER_GEOLOC_LATITUDE = "geoloc_latitude";
133     private static final String PARAMETER_GEOLOC_LONGITUDE = "geoloc_longitude";
134 
135     // Properties for page titles
136     private static final String PROPERTY_PAGE_TITLE_MANAGE_APPOINTMENTFORMS = "appointment.manage.appointmentforms.title";
137     private static final String PROPERTY_PAGE_TITLE_GENERAL_SETTINGS = "appointment.modifyAppointmentForm.titleAlterablesParameters";
138     private static final String PROPERTY_PAGE_TITLE_CREATE_APPOINTMENTFORM = "appointment.manage.appointmentforms.title";
139     private static final String PROPERTY_PAGE_TITLE_MODIFY_APPOINTMENTFORM_MESSAGES = "appointment.modifyAppointmentFormMessages.pageTitle";
140 
141     // Markers
142     private static final String MARK_WEBAPP_URL = "webapp_url";
143     private static final String MARK_APPOINTMENTFORM_LIST = "appointmentform_list";
144     private static final String MARK_APPOINTMENT_FORM = "appointmentform";
145     private static final String MARK_PAGINATOR = "paginator";
146     private static final String MARK_NB_ITEMS_PER_PAGE = "nb_items_per_page";
147     private static final String MARK_LIST_WORKFLOWS = "listWorkflows";
148     private static final String MARK_IS_CAPTCHA_ENABLED = "isCaptchaEnabled";
149     private static final String MARK_FORM_MESSAGE = "formMessage";
150     private static final String MARK_REF_LIST_CALENDAR_TEMPLATES = "refListCalendarTemplates";
151     private static final String MARK_LIST_CATEGORIES = "listCategories";
152     private static final String MARK_NULL = "NULL";
153     private static final String MARK_FALSE = "false";
154     private static final String MARK_LOCALE = "language";
155     private static final String MARK_LOCALE_TINY = "locale";
156     private static final String MARK_FILE_CLOSING_DAYS = "fileClosingDays";
157     private static final String MARK_USER_WORKGROUP_REF_LIST = "user_workgroup_list";
158     private static final String MARK_APPOINTMENT_RESOURCE_ENABLED = "isResourceInstalled";
159     private static final String MARK_PERMISSION_CREATE = "permission_create";
160 
161     // Jsp
162     private static final String JSP_MANAGE_APPOINTMENTFORMS = "jsp/admin/plugins/appointment/ManageAppointmentForms.jsp";
163 
164     // Properties
165     private static final String MESSAGE_CONFIRM_REMOVE_APPOINTMENTFORM = "appointment.message.confirmRemoveAppointmentForm";
166     public static final String PROPERTY_DEFAULT_LIST_APPOINTMENTFORM_PER_PAGE = "appointment.listAppointmentForms.itemsPerPage";
167     private static final String VALIDATION_ATTRIBUTES_PREFIX = "appointment.model.entity.appointmentform.attribute.";
168     private static final String PROPERTY_MODULE_APPOINTMENT_RESOURCE_NAME = "appointment.moduleAppointmentResource.name";
169 
170     private static final String PROPERTY_COPY_OF_FORM = "appointment.manageAppointmentForms.Copy";
171     private static final String MESSAGE_ERROR_EMPTY_FILE = "appointment.message.error.closingDayErrorImport";
172     private static final String MESSAGE_ERROR_OPEN_SLOTS = "appointment.message.error.openSlots";
173     private static final String MESSAGE_INFO_IMPORTED_CLOSING_DAYS = "appointment.info.appointmentform.closingDayImport";
174 
175     // Views
176     private static final String VIEW_MANAGE_APPOINTMENTFORMS = "manageAppointmentForms";
177     private static final String VIEW_CREATE_APPOINTMENTFORM = "createAppointmentForm";
178     private static final String VIEW_MODIFY_APPOINTMENTFORM = "modifyAppointmentForm";
179     private static final String VIEW_MODIFY_FORM_MESSAGES = "modifyAppointmentFormMessages";
180     private static final String VIEW_PERMISSIONS_FORM = "permissions";
181 
182     // Actions
183     private static final String ACTION_CREATE_APPOINTMENTFORM = "createAppointmentForm";
184     private static final String ACTION_MODIFY_APPOINTMENTFORM = "modifyAppointmentForm";
185     private static final String ACTION_REMOVE_APPOINTMENTFORM = "removeAppointmentForm";
186     private static final String ACTION_CONFIRM_REMOVE_APPOINTMENTFORM = "confirmRemoveAppointmentForm";
187     private static final String ACTION_DO_CHANGE_FORM_ACTIVATION = "doChangeFormActivation";
188     private static final String ACTION_DO_MODIFY_FORM_MESSAGES = "doModifyAppointmentFormMessages";
189     private static final String ACTION_DO_COPY_FORM = "doCopyAppointmentForm";
190 
191     // Infos
192     private static final String INFO_APPOINTMENTFORM_CREATED = "appointment.info.appointmentform.created";
193     private static final String INFO_APPOINTMENTFORM_UPDATED = "appointment.info.appointmentform.updated";
194     private static final String INFO_APPOINTMENTFORM_REMOVED = "appointment.info.appointmentform.removed";
195     private static final String INFO_APPOINTMENTFORM_MESSAGES_MODIFIED = "appointment.info.appointmentFormMessages.updated";
196     private static final String ERROR_APPOINTMENTFORM_ENDING_VALIDITY_DATE_BEFORE_NOW = "appointment.error.appointmentform.endingValidityDateBeforeNow";
197 
198     // Session variable to store working values
199     private static final String SESSION_ATTRIBUTE_APPOINTMENT_FORM = "appointment.session.appointmentForm";
200     private static final String SESSION_CURRENT_PAGE_INDEX = "appointment.session.appointmentForm.currentPageIndex";
201     private static final String SESSION_ITEMS_PER_PAGE = "appointment.session.appointmentForm.itemsPerPage";
202     private static final String DEFAULT_CURRENT_PAGE = "1";
203 
204     /**
205      * Default constructor
206      */
207     public AppointmentFormJspBean( )
208     {
209         _nDefaultItemsPerPage = AppPropertiesService.getPropertyInt( PROPERTY_DEFAULT_LIST_APPOINTMENTFORM_PER_PAGE, 50 );
210     }
211 
212     /**
213      * Get the page to manage appointment forms
214      * 
215      * @param request
216      *            the request
217      * @return The HTML content to display
218      */
219     @View( value = VIEW_MANAGE_APPOINTMENTFORMS, defaultView = true )
220     public String getManageAppointmentForms( HttpServletRequest request )
221     {
222         AdminUser adminUser = getUser( );
223         String strCurrentPageIndex = Paginator.getPageIndex( request, Paginator.PARAMETER_PAGE_INDEX,
224                 (String) request.getSession( ).getAttribute( SESSION_CURRENT_PAGE_INDEX ) );
225         if ( strCurrentPageIndex == null )
226         {
227             strCurrentPageIndex = DEFAULT_CURRENT_PAGE;
228         }
229         request.getSession( ).setAttribute( SESSION_CURRENT_PAGE_INDEX, strCurrentPageIndex );
230         int nItemsPerPage = Paginator.getItemsPerPage( request, Paginator.PARAMETER_ITEMS_PER_PAGE,
231                 getIntSessionAttribute( request.getSession( ), SESSION_ITEMS_PER_PAGE ), _nDefaultItemsPerPage );
232         request.getSession( ).setAttribute( SESSION_ITEMS_PER_PAGE, nItemsPerPage );
233         request.getSession( ).removeAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM );
234         UrlItem url = new UrlItem( JSP_MANAGE_APPOINTMENTFORMS );
235         String strUrl = url.getUrl( );
236         List<AppointmentFormDTO> listAppointmentForm = FormService.buildAllAppointmentFormLight( );
237         listAppointmentForm = (List<AppointmentFormDTO>) AdminWorkgroupService.getAuthorizedCollection( listAppointmentForm, adminUser );
238         listAppointmentForm = listAppointmentForm.stream( ).sorted( ( a1, a2 ) -> a1.getTitle( ).compareTo( a2.getTitle( ) ) ).collect( Collectors.toList( ) );
239         LocalizedPaginator<AppointmentFormDTO> paginator = new LocalizedPaginator<AppointmentFormDTO>( listAppointmentForm, nItemsPerPage, strUrl,
240                 PARAMETER_PAGE_INDEX, strCurrentPageIndex, getLocale( ) );
241         AdminUser user = AdminUserService.getAdminUser( request );
242         Map<String, Object> model = getModel( );
243         model.put( MARK_NB_ITEMS_PER_PAGE, Integer.toString( nItemsPerPage ) );
244         model.put( MARK_PAGINATOR, paginator );
245         model.put(
246                 MARK_APPOINTMENTFORM_LIST,
247                 RBACService.getAuthorizedCollection( paginator.getPageItems( ), AppointmentResourceIdService.PERMISSION_VIEW_FORM,
248                         AdminUserService.getAdminUser( request ) ) );
249         model.put( VIEW_PERMISSIONS_FORM, AppointmentUtilities.getPermissions( paginator.getPageItems( ), user ) );
250         model.put( MARK_PERMISSION_CREATE, String.valueOf( RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE_CREATE, "0",
251                 AppointmentResourceIdService.PERMISSION_CREATE_FORM, user ) ) );
252         return getPage( PROPERTY_PAGE_TITLE_MANAGE_APPOINTMENTFORMS, TEMPLATE_MANAGE_APPOINTMENTFORMS, model );
253     }
254 
255     /**
256      * Returns the form to create an appointment form
257      *
258      * @param request
259      *            The HTTP request
260      * @return the HTML code of the appointment form
261      * @throws AccessDeniedException
262      *             If the user is not authorized to create appointment forms
263      */
264     @View( VIEW_CREATE_APPOINTMENTFORM )
265     public String getCreateAppointmentForm( HttpServletRequest request ) throws AccessDeniedException
266     {
267         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE_CREATE, "0", AppointmentResourceIdService.PERMISSION_CREATE_FORM,
268                 AdminUserService.getAdminUser( request ) ) )
269         {
270             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_CREATE_FORM );
271         }
272         AppointmentFormDTO appointmentForm = null;
273         String strError = request.getParameter( PARAMETER_ERROR );
274         if ( StringUtils.isNotEmpty( strError ) )
275         {
276             appointmentForm = (AppointmentFormDTO) request.getSession( ).getAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM );
277         }
278         if ( appointmentForm == null )
279         {
280             appointmentForm = new AppointmentFormDTO( );
281         }
282         Map<String, Object> model = getModel( );
283         addElementsToModel( request, appointmentForm, getUser( ), getLocale( ), model );
284         return getPage( PROPERTY_PAGE_TITLE_CREATE_APPOINTMENTFORM, TEMPLATE_CREATE_APPOINTMENTFORM, model );
285     }
286 
287     /**
288      * Process the data capture form of a new appointment form
289      * 
290      * @param request
291      *            The HTTP Request
292      * @return The JSP URL of the process result
293      * @throws AccessDeniedException
294      *             If the user is not authorized to create appointment forms
295      * @throws FileNotFoundException
296      */
297     @Action( ACTION_CREATE_APPOINTMENTFORM )
298     public String doCreateAppointmentForm( HttpServletRequest request ) throws AccessDeniedException, FileNotFoundException
299     {
300         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE_CREATE, "0", AppointmentResourceIdService.PERMISSION_CREATE_FORM,
301                 AdminUserService.getAdminUser( request ) ) )
302         {
303             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_CREATE_FORM );
304         }
305         AppointmentFormDTO appointmentForm = (AppointmentFormDTO) request.getSession( ).getAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM );
306         if ( appointmentForm == null )
307         {
308             appointmentForm = new AppointmentFormDTO( );
309         }
310         populate( appointmentForm, request );
311         populateAddress( appointmentForm, request );
312         if ( !validateBean( appointmentForm, VALIDATION_ATTRIBUTES_PREFIX ) || !checkConstraints( appointmentForm ) )
313         {
314             return redirect( request, VIEW_CREATE_APPOINTMENTFORM, PARAMETER_ID_FORM, appointmentForm.getIdForm( ), PARAMETER_ERROR, 1 );
315         }
316         appointmentForm.setIcon( buildImageResource( (MultipartHttpServletRequest) request ) );
317         int nIdForm = FormService.createAppointmentForm( appointmentForm );
318         AppLogService.info( LogUtilities.buildLog( ACTION_CREATE_APPOINTMENTFORM, Integer.toString( nIdForm ), getUser( ) ) );
319         request.getSession( ).removeAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM );
320         addInfo( INFO_APPOINTMENTFORM_CREATED, getLocale( ) );
321         return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
322     }
323 
324     /**
325      * Manages the removal form of a appointment form whose identifier is in the HTTP request
326      * 
327      * @param request
328      *            The HTTP request
329      * @return the HTML code to confirm
330      * @throws AccessDeniedException
331      *             If the user is not authorized to delete this appointment form
332      */
333     @Action( ACTION_CONFIRM_REMOVE_APPOINTMENTFORM )
334     public String getConfirmRemoveAppointmentForm( HttpServletRequest request ) throws AccessDeniedException
335     {
336         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
337         if ( StringUtils.isEmpty( strIdForm ) )
338         {
339             return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
340         }
341         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE, strIdForm, AppointmentResourceIdService.PERMISSION_DELETE_FORM,
342                 AdminUserService.getAdminUser( request ) ) )
343         {
344             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_DELETE_FORM );
345         }
346         int nIdForm = Integer.parseInt( request.getParameter( PARAMETER_ID_FORM ) );
347         UrlItem url = new UrlItem( getActionUrl( ACTION_REMOVE_APPOINTMENTFORM ) );
348         url.addParameter( PARAMETER_ID_FORM, nIdForm );
349         String strMessageUrl = AdminMessageService.getMessageUrl( request, MESSAGE_CONFIRM_REMOVE_APPOINTMENTFORM, url.getUrl( ),
350                 AdminMessage.TYPE_CONFIRMATION );
351         return redirect( request, strMessageUrl );
352     }
353 
354     /**
355      * Handles the removal form of an appointment form
356      * 
357      * @param request
358      *            The HTTP request
359      * @return the JSP URL to display the form to manage appointment forms
360      * @throws AccessDeniedException
361      *             If the user is not authorized to delete this appointment form
362      */
363     @Action( ACTION_REMOVE_APPOINTMENTFORM )
364     public String doRemoveAppointmentForm( HttpServletRequest request ) throws AccessDeniedException
365     {
366         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
367         if ( StringUtils.isEmpty( strIdForm ) )
368         {
369             return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
370         }
371         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE, request.getParameter( PARAMETER_ID_FORM ),
372                 AppointmentResourceIdService.PERMISSION_DELETE_FORM, AdminUserService.getAdminUser( request ) ) )
373         {
374             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_DELETE_FORM );
375         }
376         int nIdForm = Integer.parseInt( request.getParameter( PARAMETER_ID_FORM ) );
377         FormService.removeForm( nIdForm );
378         AppLogService.info( LogUtilities.buildLog( ACTION_REMOVE_APPOINTMENTFORM, strIdForm, getUser( ) ) );
379         _entryService.removeEntriesByIdAppointmentForm( nIdForm );
380         addInfo( INFO_APPOINTMENTFORM_REMOVED, getLocale( ) );
381         return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
382     }
383 
384     /**
385      * Returns the form to update info about a appointment form
386      * 
387      * @param request
388      *            The HTTP request
389      * @return The HTML form to update info
390      * @throws AccessDeniedException
391      *             If the user is not authorized to modify this appointment form
392      */
393     @View( VIEW_MODIFY_APPOINTMENTFORM )
394     public String getModifyAppointmentForm( HttpServletRequest request ) throws AccessDeniedException
395     {
396         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
397         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE, strIdForm, AppointmentResourceIdService.PERMISSION_MODIFY_FORM,
398                 AdminUserService.getAdminUser( request ) ) )
399         {
400             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_MODIFY_FORM );
401         }
402         int nIdForm = Integer.parseInt( request.getParameter( PARAMETER_ID_FORM ) );
403         AppointmentFormDTO appointmentForm = (AppointmentFormDTO) request.getSession( ).getAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM );
404         if ( ( appointmentForm == null ) || ( nIdForm != appointmentForm.getIdForm( ) ) )
405         {
406             appointmentForm = FormService.buildAppointmentForm( nIdForm, 0, 0 );
407         }
408         Map<String, Object> model = getModel( );
409         addElementsToModel( request, appointmentForm, getUser( ), getLocale( ), model );
410         return getPage( PROPERTY_PAGE_TITLE_GENERAL_SETTINGS, TEMPLATE_MODIFY_APPOINTMENTFORM, model );
411     }
412 
413     /**
414      * Process the change form of a appointment form
415      * 
416      * @param request
417      *            The HTTP request
418      * @return The JSP URL of the process result
419      * @throws AccessDeniedException
420      *             If the user is not authorized to modify this appointment form
421      */
422     @Action( ACTION_MODIFY_APPOINTMENTFORM )
423     public String doModifyAppointmentForm( HttpServletRequest request ) throws AccessDeniedException
424     {
425         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
426         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE, strIdForm, AppointmentResourceIdService.PERMISSION_MODIFY_FORM,
427                 AdminUserService.getAdminUser( request ) ) )
428         {
429             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_MODIFY_FORM );
430         }
431         int nIdForm = Integer.parseInt( strIdForm );
432         AppointmentFormDTO appointmentForm = (AppointmentFormDTO) request.getSession( ).getAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM );
433         if ( ( appointmentForm == null ) || ( nIdForm != appointmentForm.getIdForm( ) ) )
434         {
435             appointmentForm = FormService.buildAppointmentFormLight( nIdForm );
436         }
437         populate( appointmentForm, request );
438         populateAddress( appointmentForm, request );
439         AppointmentFormDTO appointmentFormDb = FormService.buildAppointmentForm( nIdForm, 0, 0 );
440         String strDeleteIcon = ( request.getParameter( PARAMETER_DELETE_ICON ) == null ) ? MARK_FALSE : request.getParameter( PARAMETER_DELETE_ICON );
441         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
442         if ( Boolean.parseBoolean( strDeleteIcon ) && ( appointmentForm.getIcon( ).getImage( ) != null ) )
443         {
444             ImageResource img = new ImageResource( );
445             img.setImage( null );
446             img.setMimeType( null );
447             appointmentForm.setIcon( img );
448         }
449         else
450         {
451             ImageResource imageResource = buildImageResource( mRequest );
452             if ( !StringUtils.equals( MARK_NULL, imageResource.getMimeType( ) ) )
453             {
454                 appointmentForm.setIcon( imageResource );
455             }
456         }
457         // Import of the closing days file
458         importClosingDayFile( mRequest, nIdForm );
459         setParametersDays( appointmentForm, appointmentFormDb );
460         if ( !validateBean( appointmentForm, VALIDATION_ATTRIBUTES_PREFIX ) || !checkConstraints( appointmentForm ) )
461         {
462             request.getSession( ).setAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM, appointmentForm );
463             return redirect( request, VIEW_MODIFY_APPOINTMENTFORM, PARAMETER_ID_FORM, nIdForm );
464         }
465         appointmentForm.setIsActive( appointmentFormDb.getIsActive( ) );
466         FormService.updateGlobalParameters( appointmentForm );
467         AppLogService.info( LogUtilities.buildLog( ACTION_MODIFY_APPOINTMENTFORM, strIdForm, getUser( ) ) );
468         request.getSession( ).removeAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM );
469         addInfo( INFO_APPOINTMENTFORM_UPDATED, getLocale( ) );
470         return redirect( request, VIEW_MODIFY_APPOINTMENTFORM, PARAMETER_ID_FORM, nIdForm );
471     }
472 
473     /**
474      * Change the enabling of an appointment form
475      * 
476      * @param request
477      *            The request
478      * @return The next URL to redirect to
479      * @throws AccessDeniedException
480      *             If the user is not authorized to change the activation of this appointment form
481      */
482     @Action( ACTION_DO_CHANGE_FORM_ACTIVATION )
483     public String doChangeFormActivation( HttpServletRequest request ) throws AccessDeniedException
484     {
485         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
486         if ( StringUtils.isEmpty( strIdForm ) )
487         {
488             return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
489         }
490         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE, strIdForm, AppointmentResourceIdService.PERMISSION_CHANGE_STATE,
491                 AdminUserService.getAdminUser( request ) ) )
492         {
493             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_CHANGE_STATE );
494         }
495         int nIdForm = Integer.parseInt( strIdForm );
496         Form form = FormService.findFormLightByPrimaryKey( nIdForm );
497         if ( form != null )
498         {
499             if ( !form.getIsActive( ) )
500             {
501                 if ( form.getStartingValidityDate( ) == null )
502                 {
503                     form.setStartingValidityDate( LocalDate.now( ) );
504                 }
505                 if ( ( form.getEndingValidityDate( ) != null ) && ( form.getEndingValidityDate( ).isBefore( LocalDate.now( ) ) ) )
506                 {
507                     addError( ERROR_APPOINTMENTFORM_ENDING_VALIDITY_DATE_BEFORE_NOW, getLocale( ) );
508                     if ( Boolean.valueOf( request.getParameter( PARAMETER_FROM_DASHBOARD ) ) )
509                     {
510                         return redirect( request, AppPathService.getBaseUrl( request ) + AppPathService.getAdminMenuUrl( ) );
511                     }
512                     else
513                     {
514                         return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
515                     }
516                 }
517             }
518             else
519             {
520                 form.setStartingValidityDate( null );
521             }
522             form.setIsActive( !form.getIsActive( ) );
523             FormService.updateForm( form );
524             AppLogService.info( LogUtilities.buildLog( ACTION_DO_CHANGE_FORM_ACTIVATION, strIdForm, getUser( ) ) );
525         }
526         if ( Boolean.valueOf( request.getParameter( PARAMETER_FROM_DASHBOARD ) ) )
527         {
528             return redirect( request, AppPathService.getBaseUrl( request ) + AppPathService.getAdminMenuUrl( ) );
529         }
530         return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
531     }
532 
533     /**
534      * Do copy a form
535      * 
536      * @param request
537      *            the request
538      * @return the JSP URL to display the form to manage appointment forms
539      * @throws AccessDeniedException
540      */
541     @Action( ACTION_DO_COPY_FORM )
542     public String doCopyAppointmentForm( HttpServletRequest request ) throws AccessDeniedException
543     {
544         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE_CREATE, "0", AppointmentResourceIdService.PERMISSION_CREATE_FORM,
545                 AdminUserService.getAdminUser( request ) ) )
546         {
547             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_CREATE_FORM );
548         }
549         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
550         if ( StringUtils.isEmpty( strIdForm ) )
551         {
552             return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
553         }
554         int nIdForm = Integer.parseInt( strIdForm );
555         Form formToCopy = FormService.findFormLightByPrimaryKey( nIdForm );
556         if ( formToCopy != null )
557         {
558             String newNameForCopy = I18nService.getLocalizedString( PROPERTY_COPY_OF_FORM, request.getLocale( ) ) + formToCopy.getTitle( );
559             int nIdCopyForm = FormService.copyForm( nIdForm, newNameForCopy );
560             AppLogService.info( LogUtilities.buildLog( ACTION_DO_COPY_FORM, String.valueOf( nIdCopyForm ), getUser( ) ) );
561         }
562         return getManageAppointmentForms( request );
563     }
564 
565     /**
566      * Get the page to modify an appointment form message
567      * 
568      * @param request
569      *            The request
570      * @return The HTML content to display
571      * @throws AccessDeniedException
572      *             If the user is not authorized to modify this appointment form
573      */
574     @View( VIEW_MODIFY_FORM_MESSAGES )
575     public String getModifyAppointmentFormMessages( HttpServletRequest request ) throws AccessDeniedException
576     {
577         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
578         if ( StringUtils.isEmpty( strIdForm ) )
579         {
580             return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
581         }
582         if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE, strIdForm, AppointmentResourceIdService.PERMISSION_MODIFY_FORM,
583                 AdminUserService.getAdminUser( request ) ) )
584         {
585             throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_MODIFY_FORM );
586         }
587         int nIdForm = Integer.parseInt( strIdForm );
588         FormMessage formMessage = FormMessageService.findFormMessageByIdForm( nIdForm );
589         Map<String, Object> model = new HashMap<String, Object>( );
590         model.put( MARK_FORM_MESSAGE, formMessage );
591         model.put( MARK_WEBAPP_URL, AppPathService.getBaseUrl( request ) );
592         model.put( MARK_LOCALE, getLocale( ) );
593         model.put( MARK_LOCALE_TINY, getLocale( ) );
594         return getPage( PROPERTY_PAGE_TITLE_MODIFY_APPOINTMENTFORM_MESSAGES, TEMPLATE_MODIFY_APPOINTMENTFORM_MESSAGES, model );
595     }
596 
597     /**
598      * Do modify an appointment form messages
599      * 
600      * @param request
601      *            The request
602      * @return The next URL to redirect to
603      * @throws AccessDeniedException
604      *             If the user is not authorized to modify this appointment form
605      */
606     @Action( ACTION_DO_MODIFY_FORM_MESSAGES )
607     public String doModifyAppointmentFormMessages( HttpServletRequest request ) throws AccessDeniedException
608     {
609         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
610         if ( StringUtils.isNotEmpty( strIdForm ) && StringUtils.isNumeric( strIdForm ) && ( request.getParameter( PARAMETER_BACK ) == null ) )
611         {
612             if ( !RBACService.isAuthorized( AppointmentFormDTO.RESOURCE_TYPE, strIdForm, AppointmentResourceIdService.PERMISSION_MODIFY_FORM,
613                     AdminUserService.getAdminUser( request ) ) )
614             {
615                 throw new AccessDeniedException( AppointmentResourceIdService.PERMISSION_MODIFY_FORM );
616             }
617             int nIdForm = Integer.parseInt( strIdForm );
618             UrlItem url = new UrlItem( getViewFullUrl( VIEW_MODIFY_FORM_MESSAGES ) );
619             url.addParameter( PARAMETER_ID_FORM, nIdForm );
620             FormMessage formMessage = FormMessageService.findFormMessageByIdForm( nIdForm );
621             populate( formMessage, request );
622             FormMessageHome.update( formMessage );
623             AppLogService.info( LogUtilities.buildLog( ACTION_DO_MODIFY_FORM_MESSAGES, strIdForm, getUser( ) ) );
624             addInfo( INFO_APPOINTMENTFORM_MESSAGES_MODIFIED, getLocale( ) );
625         }
626         return redirectView( request, VIEW_MANAGE_APPOINTMENTFORMS );
627     }
628 
629     /**
630      * Get the URL to manage appointment forms
631      * 
632      * @param request
633      *            The request
634      * @return The URL to manage appointment forms
635      */
636     public static String getURLManageAppointmentForms( HttpServletRequest request )
637     {
638         UrlItem urlItem = new UrlItem( AppPathService.getBaseUrl( request ) + JSP_MANAGE_APPOINTMENTFORMS );
639         urlItem.addParameter( MVCUtils.PARAMETER_VIEW, VIEW_MANAGE_APPOINTMENTFORMS );
640         return urlItem.getUrl( );
641     }
642 
643     /**
644      * Add elements to the model to display the left column to modify an appointment form
645      * 
646      * @param request
647      *            The request to store the appointment form in session
648      * @param appointmentForm
649      *            The appointment form
650      * @param user
651      *            The user
652      * @param locale
653      *            The locale
654      * @param model
655      *            the model to add elements in
656      */
657     public static void addElementsToModel( HttpServletRequest request, AppointmentFormDTO appointmentForm, AdminUser user, Locale locale,
658             Map<String, Object> model )
659     {
660         model.put( MARK_APPOINTMENT_FORM, appointmentForm );
661         model.put( MARK_LOCALE, locale );
662         model.put( MARK_LIST_WORKFLOWS, WorkflowService.getInstance( ).getWorkflowsEnabled( user, locale ) );
663         model.put( MARK_IS_CAPTCHA_ENABLED, _captchaSecurityService.isAvailable( ) );
664         model.put( MARK_REF_LIST_CALENDAR_TEMPLATES, CalendarTemplateHome.findAllInReferenceList( ) );
665         model.put( MARK_LIST_CATEGORIES, CategoryService.findAllInReferenceList( ) );
666         model.put( MARK_USER_WORKGROUP_REF_LIST, AdminWorkgroupService.getUserWorkgroups( user, locale ) );
667         Plugin pluginAppointmentResource = PluginService.getPlugin( AppPropertiesService.getProperty( PROPERTY_MODULE_APPOINTMENT_RESOURCE_NAME ) );
668         model.put( MARK_APPOINTMENT_RESOURCE_ENABLED, ( pluginAppointmentResource != null ) && pluginAppointmentResource.isInstalled( ) );
669         request.getSession( ).setAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FORM, appointmentForm );
670     }
671 
672     /**
673      * Get an integer attribute from the session
674      * 
675      * @param session
676      *            The session
677      * @param strSessionKey
678      *            The session key of the item
679      * @return The value of the attribute, or 0 if the key is not associated with any value
680      */
681     private int getIntSessionAttribute( HttpSession session, String strSessionKey )
682     {
683         Integer nAttr = (Integer) session.getAttribute( strSessionKey );
684         if ( nAttr != null )
685         {
686             return nAttr;
687         }
688         return 0;
689     }
690 
691     /**
692      * Build an image resource (icon)
693      * 
694      * @param mRequest
695      *            the request
696      * @return the image resource
697      */
698     public static ImageResource buildImageResource( MultipartHttpServletRequest mRequest )
699     {
700         ImageResource img = new ImageResource( );
701         byte [ ] bytes = new byte [ ] { };
702         String strMimeType = MARK_NULL;
703         FileItem item = mRequest.getFile( PARAMETER_ICON_RESSOURCE );
704         if ( ( item != null ) && StringUtils.isNotEmpty( item.getName( ) ) )
705         {
706             bytes = item.get( );
707             strMimeType = item.getContentType( );
708         }
709         img.setImage( bytes );
710         img.setMimeType( strMimeType );
711         return img;
712     }
713 
714     /**
715      * Set the days to the appointment form DTO
716      * 
717      * @param appointmentForm
718      *            the appointmentForm DTO
719      * @param appointmentFormTmp
720      *            the appointmentForm temp DTO
721      */
722     private void setParametersDays( AppointmentFormDTO appointmentForm, AppointmentFormDTO appointmentFormTmp )
723     {
724         appointmentForm.setIsOpenMonday( appointmentFormTmp.getIsOpenMonday( ) );
725         appointmentForm.setIsOpenTuesday( appointmentFormTmp.getIsOpenTuesday( ) );
726         appointmentForm.setIsOpenWednesday( appointmentFormTmp.getIsOpenWednesday( ) );
727         appointmentForm.setIsOpenThursday( appointmentFormTmp.getIsOpenThursday( ) );
728         appointmentForm.setIsOpenFriday( appointmentFormTmp.getIsOpenFriday( ) );
729         appointmentForm.setIsOpenSaturday( appointmentFormTmp.getIsOpenSaturday( ) );
730         appointmentForm.setIsOpenSunday( appointmentFormTmp.getIsOpenSunday( ) );
731     }
732 
733     /**
734      * Import the file of the closing days
735      * 
736      * @param mRequest
737      *            the request
738      * @param nIdForm
739      *            the form Id
740      * @return false if there is an error during the import
741      */
742     private void importClosingDayFile( MultipartHttpServletRequest mRequest, int nIdForm )
743     {
744         String strPathFile = StringUtils.EMPTY;
745         FileItem item = mRequest.getFile( MARK_FILE_CLOSING_DAYS );
746         if ( item != null && StringUtils.isNotEmpty( item.getName( ) ) )
747         {
748             strPathFile = item.getName( );
749         }
750         if ( StringUtils.isNotEmpty( strPathFile ) )
751         {
752             List<LocalDate> listClosingDaysDb = ClosingDayService.findListDateOfClosingDayByIdForm( nIdForm );
753             List<LocalDate> listDateImported = new ArrayList<>( );
754             List<LocalDate> listDateToSave = new ArrayList<>( );
755             try
756             {
757                 listDateImported = ClosingDayService.getImportClosingDays( item );
758             }
759             catch( IOException e )
760             {
761             }
762             if ( CollectionUtils.isEmpty( listDateImported ) )
763             {
764                 addError( MESSAGE_ERROR_EMPTY_FILE, getLocale( ) );
765             }
766             else
767             {
768                 List<Slot> listSlotsImpacted;
769                 List<LocalDate> listDateWithError = new ArrayList<>( );
770                 List<Slot> listSlotsToDelete = new ArrayList<>( );
771                 List<Appointment> listAppointmentsImpacted;
772                 for ( LocalDate closingDate : listDateImported )
773                 {
774                     if ( !listClosingDaysDb.contains( closingDate ) )
775                     {
776                         listSlotsImpacted = SlotService
777                                 .findSlotsByIdFormAndDateRange( nIdForm, closingDate.atStartOfDay( ), closingDate.atTime( LocalTime.MAX ) );
778                         // Check if there is appointments on this slots
779                         listAppointmentsImpacted = AppointmentService.findListAppointmentByListSlot( listSlotsImpacted );
780                         if ( CollectionUtils.isNotEmpty( listAppointmentsImpacted ) )
781                         {
782                             listDateWithError.add( closingDate );
783                         }
784                         else
785                         {
786                             listSlotsToDelete.addAll( listSlotsImpacted );
787                             listDateToSave.add( closingDate );
788                         }
789                     }
790                 }
791                 if ( CollectionUtils.isNotEmpty( listDateWithError ) )
792                 {
793                     StringJoiner stbListDate = new StringJoiner( StringUtils.SPACE );
794                     for ( LocalDate dateWithError : listDateWithError )
795                     {
796                         stbListDate.add( Utilities.getFormatter( ).format( dateWithError ) ).add( "," );
797                     }
798                     String strListdate = stbListDate.toString( );
799                     strListdate = strListdate.substring( 0, strListdate.length( ) - 1 );
800                     Object [ ] tabEntryErrorDate = {
801                         strListdate
802                     };
803                     String strErrorMessageDateWithAppointments = I18nService.getLocalizedString( MESSAGE_ERROR_OPEN_SLOTS, tabEntryErrorDate, getLocale( ) );
804                     addError( strErrorMessageDateWithAppointments );
805                 }
806                 SlotService.deleteListSlots( listSlotsToDelete );
807                 ClosingDayService.saveListClosingDay( nIdForm, listDateToSave );
808                 addInfo( MESSAGE_INFO_IMPORTED_CLOSING_DAYS, getLocale( ) );
809             }
810         }
811     }
812 
813     private void populateAddress( AppointmentFormDTO appointmentForm, HttpServletRequest request )
814     {
815         String strGeolocAddress = request.getParameter( PARAMETER_GEOLOC_ADDRESS );
816         String strGeolocLatitude = request.getParameter( PARAMETER_GEOLOC_LATITUDE );
817         String strGeolocLongitude = request.getParameter( PARAMETER_GEOLOC_LONGITUDE );
818         if ( StringUtils.isNotBlank( strGeolocAddress ) && StringUtils.isNotBlank( strGeolocLatitude ) && StringUtils.isNotBlank( strGeolocLongitude ) )
819         {
820             appointmentForm.setAddress( strGeolocAddress );
821             appointmentForm.setLatitude( Double.valueOf( strGeolocLatitude ) );
822             appointmentForm.setLongitude( Double.valueOf( strGeolocLongitude ) );
823         }
824         else
825         {
826             appointmentForm.setAddress( null );
827             appointmentForm.setLatitude( null );
828             appointmentForm.setLongitude( null );
829         }
830     }
831 
832 }