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.service;
35  
36  import java.time.DayOfWeek;
37  import java.time.LocalDate;
38  import java.time.LocalTime;
39  import java.util.ArrayList;
40  import java.util.List;
41  
42  import fr.paris.lutece.plugins.appointment.business.appointment.AppointmentHome;
43  import org.apache.commons.collections.CollectionUtils;
44  
45  import fr.paris.lutece.plugins.appointment.business.appointment.Appointment;
46  import fr.paris.lutece.plugins.appointment.business.display.Display;
47  import fr.paris.lutece.plugins.appointment.business.form.Form;
48  import fr.paris.lutece.plugins.appointment.business.form.FormHome;
49  import fr.paris.lutece.plugins.appointment.business.localization.Localization;
50  import fr.paris.lutece.plugins.appointment.business.message.FormMessage;
51  import fr.paris.lutece.plugins.appointment.business.planning.ClosingDay;
52  import fr.paris.lutece.plugins.appointment.business.planning.TimeSlot;
53  import fr.paris.lutece.plugins.appointment.business.planning.WeekDefinition;
54  import fr.paris.lutece.plugins.appointment.business.planning.WorkingDay;
55  import fr.paris.lutece.plugins.appointment.business.rule.FormRule;
56  import fr.paris.lutece.plugins.appointment.business.rule.ReservationRule;
57  import fr.paris.lutece.plugins.appointment.business.slot.Slot;
58  import fr.paris.lutece.plugins.appointment.service.listeners.AppointmentListenerManager;
59  import fr.paris.lutece.plugins.appointment.service.listeners.FormListenerManager;
60  import fr.paris.lutece.plugins.appointment.web.dto.AppointmentFormDTO;
61  import fr.paris.lutece.plugins.genericattributes.business.Entry;
62  import fr.paris.lutece.plugins.genericattributes.business.EntryFilter;
63  import fr.paris.lutece.plugins.genericattributes.business.EntryHome;
64  import fr.paris.lutece.util.ReferenceList;
65  
66  /**
67   * Service class for a form
68   * 
69   * @author Laurent Payen
70   *
71   */
72  public final class FormService
73  {
74  
75      /**
76       * Private constructor - this class does not need to be instantiated
77       */
78      private FormService( )
79      {
80      }
81  
82      /**
83       * Make a copy of form, with all its values
84       * 
85       * @param nIdForm
86       *            the Form Id to copy
87       * @param newNameForCopy
88       *            the new Name of the copy
89       * @return the id of the form created
90       */
91      public static int copyForm( int nIdForm, String newNameForCopy )
92      {
93          // Build the simple form to copy with the values of the original form
94          AppointmentFormDTO appointmentForm = buildAppointmentForm( nIdForm, 0, 0 );
95          appointmentForm.setTitle( newNameForCopy );
96          appointmentForm.setIsActive( Boolean.FALSE );
97          appointmentForm.setDateStartValidity( null );
98          appointmentForm.setDateEndValidity( null );
99          // Save it
100         Form form = FormService.createForm( appointmentForm );
101         int nIdNewForm = form.getIdForm( );
102         // Add the display
103         DisplayService.createDisplay( appointmentForm, nIdNewForm );
104         // Add the localization
105         LocalizationService.createLocalization( appointmentForm, nIdNewForm );
106         // Add the form rule
107         FormRuleService.createFormRule( appointmentForm, nIdNewForm );
108         // Get all the weekDefinitions, WorkingDays and TimeSlots of the
109         // original form and set the new id
110         // of the copy of the form and save them
111         WeekDefinition copyWeekDefinition;
112         int idCopyWeekDefinition;
113         WorkingDay copyWorkingDay;
114         int idCopyWorkingDay;
115         TimeSlot copyTimeSlot;
116         List<WeekDefinition> listWeekDefinitions = WeekDefinitionService.findListWeekDefinition( nIdForm );
117         List<WorkingDay> listWorkingDays;
118         List<TimeSlot> listTimeSlots;
119         for ( WeekDefinition weekDefinition : listWeekDefinitions )
120         {
121             copyWeekDefinition = weekDefinition;
122             copyWeekDefinition.setIdWeekDefinition( 0 );
123             copyWeekDefinition.setIdForm( nIdNewForm );
124             copyWeekDefinition = WeekDefinitionService.saveWeekDefinition( copyWeekDefinition );
125             listWorkingDays = weekDefinition.getListWorkingDay( );
126             idCopyWeekDefinition = copyWeekDefinition.getIdWeekDefinition( );
127             for ( WorkingDay workingDay : listWorkingDays )
128             {
129                 copyWorkingDay = workingDay;
130                 copyWorkingDay.setIdWorkingDay( 0 );
131                 copyWorkingDay.setIdWeekDefinition( idCopyWeekDefinition );
132                 copyWorkingDay = WorkingDayService.saveWorkingDay( copyWorkingDay );
133                 idCopyWorkingDay = copyWorkingDay.getIdWorkingDay( );
134                 listTimeSlots = workingDay.getListTimeSlot( );
135                 for ( TimeSlot timeSlot : listTimeSlots )
136                 {
137                     copyTimeSlot = timeSlot;
138                     copyTimeSlot.setIdTimeSlot( 0 );
139                     copyTimeSlot.setIdWorkingDay( idCopyWorkingDay );
140                     TimeSlotService.saveTimeSlot( copyTimeSlot );
141                 }
142             }
143         }
144         // Get all the reservation rules of the original form and set the new id
145         // of the copy of the form and save them
146         ReservationRule copyReservationRule;
147         List<ReservationRule> listReservationRules = ReservationRuleService.findListReservationRule( nIdForm );
148         for ( ReservationRule reservationRule : listReservationRules )
149         {
150             copyReservationRule = reservationRule;
151             copyReservationRule.setIdReservationRule( 0 );
152             copyReservationRule.setIdForm( nIdNewForm );
153             ReservationRuleService.saveReservationRule( copyReservationRule );
154         }
155         // Copy the messages of the original form and add them to the copy
156         FormMessage formMessage = FormMessageService.findFormMessageByIdForm( nIdForm );
157         FormMessage copyFormMessage = formMessage;
158         copyFormMessage.setIdFormMessage( 0 );
159         copyFormMessage.setIdForm( nIdNewForm );
160         FormMessageService.saveFormMessage( copyFormMessage );
161         // Get all the closing days of the original form and add them to the
162         // copy
163         List<ClosingDay> listClosingDays = ClosingDayService.findListClosingDay( nIdForm );
164         ClosingDay copyClosingDay;
165         for ( ClosingDay closingDay : listClosingDays )
166         {
167             copyClosingDay = closingDay;
168             copyClosingDay.setIdClosingDay( 0 );
169             copyClosingDay.setIdForm( nIdNewForm );
170             ClosingDayService.saveClosingDay( copyClosingDay );
171         }
172         // Get all the specific slots of the original form and copy them for the
173         // new form
174         List<Slot> listSpecificSlots = SlotService.findSpecificSlotsByIdForm( nIdForm );
175         Slot copySpecificSlot;
176         for ( Slot specificSlot : listSpecificSlots )
177         {
178             copySpecificSlot = specificSlot;
179             copySpecificSlot.setIdSlot( 0 );
180             copySpecificSlot.setIdForm( nIdNewForm );
181             SlotService.saveSlot( copySpecificSlot );
182         }
183         // Copy the entries of the original form
184         EntryFilter entryFilter = new EntryFilter( );
185         entryFilter.setIdResource( nIdForm );
186         entryFilter.setResourceType( AppointmentFormDTO.RESOURCE_TYPE );
187         entryFilter.setEntryParentNull( EntryFilter.FILTER_TRUE );
188         entryFilter.setFieldDependNull( EntryFilter.FILTER_TRUE );
189         List<Entry> listEntries = EntryHome.getEntryList( entryFilter );
190         for ( Entry entry : listEntries )
191         {
192             entry.setIdResource( nIdNewForm );
193             EntryHome.copy( entry );
194         }
195         return nIdNewForm;
196     }
197 
198     /**
199      * Save a form in database
200      * 
201      * @param form
202      *            the form to save
203      * @return the form saved (with its id)
204      */
205     public static Form saveForm( Form form )
206     {
207         return FormHome.create( form );
208     }
209 
210     /**
211      * Create a form from an appointmentForm DTO
212      * 
213      * @param appointmentForm
214      *            the appointmentForm DTO
215      * @return the id of the form created
216      */
217     public static int createAppointmentForm( AppointmentFormDTO appointmentForm )
218     {
219         Form form = FormService.createForm( appointmentForm );
220         int nIdForm = form.getIdForm( );
221         FormMessageService.createFormMessageWithDefaultValues( nIdForm );
222         LocalDate dateNow = LocalDate.now( );
223         DisplayService.createDisplay( appointmentForm, nIdForm );
224         LocalizationService.createLocalization( appointmentForm, nIdForm );
225         FormRuleService.createFormRule( appointmentForm, nIdForm );
226         ReservationRule reservationRule = ReservationRuleService.createReservationRule( appointmentForm, nIdForm, dateNow );
227         int nMaxCapacity = reservationRule.getMaxCapacityPerSlot( );
228         WeekDefinition weekDefinition = WeekDefinitionService.createWeekDefinition( nIdForm, dateNow );
229         int nIdWeekDefinition = weekDefinition.getIdWeekDefinition( );
230         LocalTime startingTime = LocalTime.parse( appointmentForm.getTimeStart( ) );
231         LocalTime endingTime = LocalTime.parse( appointmentForm.getTimeEnd( ) );
232         int nDuration = appointmentForm.getDurationAppointments( );
233         for ( DayOfWeek dayOfWeek : WorkingDayService.getOpenDays( appointmentForm ) )
234         {
235             WorkingDayService.generateWorkingDayAndListTimeSlot( nIdWeekDefinition, dayOfWeek, startingTime, endingTime, nDuration, nMaxCapacity );
236         }
237         return nIdForm;
238     }
239 
240     /**
241      * Update a form with the new values of the Global Parameters of an appointmentForm DTO
242      * 
243      * @param appointmentForm
244      *            the appointmentForm DTO
245      * 
246      */
247     public static void updateGlobalParameters( AppointmentFormDTO appointmentForm )
248     {
249         Form form = FormService.updateForm( appointmentForm );
250         int nIdForm = form.getIdForm( );
251         DisplayService.updateDisplay( appointmentForm, nIdForm );
252         LocalizationService.updateLocalization( appointmentForm, nIdForm );
253         FormRuleService.updateFormRule( appointmentForm, nIdForm );
254     }
255 
256     /**
257      * Update a form with the new values of an appointmentForm DTO Advanced Parameters (with a date of application) --> new Typical Week
258      * 
259      * @param appointmentForm
260      *            the appointmentForm DTO
261      * @param dateOfModification
262      *            the date of the update
263      */
264     public static void updateAdvancedParameters( AppointmentFormDTO appointmentForm, LocalDate dateOfModification )
265     {
266         int nIdForm = appointmentForm.getIdForm( );
267         ReservationRule reservationRule = ReservationRuleService.updateReservationRule( appointmentForm, nIdForm, dateOfModification );
268         int nMaxCapacity = reservationRule.getMaxCapacityPerSlot( );
269         WeekDefinition weekDefinition = WeekDefinitionService.updateWeekDefinition( nIdForm, dateOfModification );
270         int nIdWeekDefinition = weekDefinition.getIdWeekDefinition( );
271         List<WorkingDay> listWorkingDay = WorkingDayService.findListWorkingDayByWeekDefinition( nIdWeekDefinition );
272         if ( CollectionUtils.isNotEmpty( listWorkingDay ) )
273         {
274             WorkingDayService.deleteListWorkingDay( listWorkingDay );
275         }
276         LocalTime startingHour = LocalTime.parse( appointmentForm.getTimeStart( ) );
277         LocalTime endingHour = LocalTime.parse( appointmentForm.getTimeEnd( ) );
278         int nDuration = appointmentForm.getDurationAppointments( );
279         for ( DayOfWeek dayOfWeek : WorkingDayService.getOpenDays( appointmentForm ) )
280         {
281             WorkingDayService.generateWorkingDayAndListTimeSlot( nIdWeekDefinition, dayOfWeek, startingHour, endingHour, nDuration, nMaxCapacity );
282         }
283     }
284 
285     /**
286      * Build all the active forms
287      * 
288      * @return the list of appointment form dto that are active
289      */
290     public static List<AppointmentFormDTO> buildAllActiveAppointmentForm( )
291     {
292         List<AppointmentFormDTO> listActiveAppointmentForm = new ArrayList<>( );
293         for ( Form form : FormHome.findActiveForms( ) )
294         {
295             listActiveAppointmentForm.add( buildAppointmentForm( form.getIdForm( ), 0, 0 ) );
296         }
297         return listActiveAppointmentForm;
298     }
299 
300     /**
301      * Build all the appointForm DTO of the database light because the appointFormDTO is only fill in with the form id, the title and if the form is active or
302      * not
303      * 
304      * @return the list of all the appointmentForm DTO
305      */
306     public static List<AppointmentFormDTO> buildAllAppointmentFormLight( )
307     {
308         List<AppointmentFormDTO> listAppointmentFormLight = new ArrayList<>( );
309         for ( Form form : FormService.findAllForms( ) )
310         {
311             checkValidityDate( form );
312             listAppointmentFormLight.add( buildAppointmentFormLight( form ) );
313         }
314         return listAppointmentFormLight;
315     }
316 
317     /**
318      * Build a list of all the forms (id, title)
319      * 
320      * @return the reference list
321      */
322     public static ReferenceList findAllInReferenceList( )
323     {
324         List<Form> listForm = findAllForms( );
325         ReferenceList refListForms = new ReferenceList( listForm.size( ) );
326         for ( Form form : listForm )
327         {
328             refListForms.addItem( form.getIdForm( ), form.getTitle( ) );
329         }
330         return refListForms;
331     }
332 
333     /**
334      * Build all the active forms of the database
335      * 
336      * @return a list of appointmentForm DTO
337      */
338     public static List<AppointmentFormDTO> buildAllActiveAndDisplayedOnPortletAppointmentForm( )
339     {
340         List<AppointmentFormDTO> listAppointmentForm = new ArrayList<>( );
341         for ( Form form : FormService.findAllActiveAndDisplayedOnPortletForms( ) )
342         {
343             listAppointmentForm.add( buildAppointmentForm( form.getIdForm( ), 0, 0 ) );
344         }
345         return listAppointmentForm;
346     }
347 
348     /**
349      * Build an appointmentFormDTO light
350      * 
351      * @param form
352      *            the form object
353      * @return the appointmentForm DTO
354      */
355     public static AppointmentFormDTO buildAppointmentFormLight( Form form )
356     {
357         AppointmentFormDTO appointmentForm = new AppointmentFormDTO( );
358         if ( form != null )
359         {
360             fillAppointmentFormWithFormPart( appointmentForm, form );
361         }
362         return appointmentForm;
363     }
364 
365     /**
366      * Build an appointmentForm light
367      * 
368      * @param nIdForm
369      *            the form Id
370      * @return the appointmentForm DTO
371      */
372     public static AppointmentFormDTO buildAppointmentFormLight( int nIdForm )
373     {
374         Form form = FormService.findFormLightByPrimaryKey( nIdForm );
375         return buildAppointmentFormLight( form );
376     }
377 
378     /**
379      * Build an appointmentForm DTO
380      * 
381      * @param nIdForm
382      *            the Form Id
383      * @param nIdReservationRule
384      *            the Reservation Rule Id
385      * @param nIdWeekDefinition
386      *            the WeekDefinition Id
387      * @return the apointmentForm DTO built
388      */
389     public static AppointmentFormDTO buildAppointmentForm( int nIdForm, int nIdReservationRule, int nIdWeekDefinition )
390     {
391         AppointmentFormDTO appointmentForm = new AppointmentFormDTO( );
392         Form form = FormService.findFormLightByPrimaryKey( nIdForm );
393         fillAppointmentFormWithFormPart( appointmentForm, form );
394         Display display = DisplayService.findDisplayWithFormId( nIdForm );
395         if ( display != null )
396         {
397             fillAppointmentFormWithDisplayPart( appointmentForm, display );
398         }
399         Localization localization = LocalizationService.findLocalizationWithFormId( nIdForm );
400         if ( localization != null )
401         {
402             fillAppointmentFormWithLocalizationPart( appointmentForm, localization );
403         }
404         FormRule formRule = FormRuleService.findFormRuleWithFormId( nIdForm );
405         if ( formRule != null )
406         {
407             fillAppointmentFormWithFormRulePart( appointmentForm, formRule );
408         }
409         ReservationRule reservationRule = null;
410         WeekDefinition weekDefinition = null;
411         LocalDate dateOfApply = LocalDate.now( );
412         if ( nIdReservationRule > 0 )
413         {
414             reservationRule = ReservationRuleService.findReservationRuleById( nIdReservationRule );
415             dateOfApply = reservationRule.getDateOfApply( );
416         }
417         if ( nIdWeekDefinition > 0 )
418         {
419             weekDefinition = WeekDefinitionService.findWeekDefinitionById( nIdWeekDefinition );
420             dateOfApply = weekDefinition.getDateOfApply( );
421         }
422         if ( reservationRule == null )
423         {
424             reservationRule = ReservationRuleService.findReservationRuleByIdFormAndClosestToDateOfApply( nIdForm, dateOfApply );
425         }
426         if ( weekDefinition == null )
427         {
428             weekDefinition = WeekDefinitionService.findWeekDefinitionByIdFormAndClosestToDateOfApply( nIdForm, dateOfApply );
429         }
430         if ( reservationRule != null )
431         {
432             fillAppointmentFormWithReservationRulePart( appointmentForm, reservationRule );
433         }
434         if ( weekDefinition != null )
435         {
436             fillAppointmentFormWithWeekDefinitionPart( appointmentForm, weekDefinition );
437         }
438         return appointmentForm;
439     }
440 
441     /**
442      * Fill the appointmentForm DTO with the WeekDefinition
443      * 
444      * @param appointmentForm
445      *            the appointmentForm DTO
446      * @param weekDefinition
447      *            the week definition
448      */
449     private static void fillAppointmentFormWithWeekDefinitionPart( AppointmentFormDTO appointmentForm, WeekDefinition weekDefinition )
450     {
451         List<WorkingDay> listWorkingDay = weekDefinition.getListWorkingDay( );
452         if ( CollectionUtils.isNotEmpty( listWorkingDay ) )
453         {
454             for ( WorkingDay workingDay : listWorkingDay )
455             {
456                 DayOfWeek dayOfWeek = DayOfWeek.of( workingDay.getDayOfWeek( ) );
457                 switch( dayOfWeek )
458                 {
459                     case MONDAY:
460                         appointmentForm.setIsOpenMonday( Boolean.TRUE );
461                         break;
462                     case TUESDAY:
463                         appointmentForm.setIsOpenTuesday( Boolean.TRUE );
464                         break;
465                     case WEDNESDAY:
466                         appointmentForm.setIsOpenWednesday( Boolean.TRUE );
467                         break;
468                     case THURSDAY:
469                         appointmentForm.setIsOpenThursday( Boolean.TRUE );
470                         break;
471                     case FRIDAY:
472                         appointmentForm.setIsOpenFriday( Boolean.TRUE );
473                         break;
474                     case SATURDAY:
475                         appointmentForm.setIsOpenSaturday( Boolean.TRUE );
476                         break;
477                     case SUNDAY:
478                         appointmentForm.setIsOpenSunday( Boolean.TRUE );
479                         break;
480                 }
481             }
482             // We suppose that all the days have the same opening and closing
483             // hours (it can be modified after)
484             LocalTime minStartingTime = WorkingDayService.getMinStartingTimeOfAListOfWorkingDay( listWorkingDay );
485             LocalTime maxEndingTime = WorkingDayService.getMaxEndingTimeOfAListOfWorkingDay( listWorkingDay );
486             int nDurationAppointment = WorkingDayService.getMinDurationTimeSlotOfAListOfWorkingDay( listWorkingDay );
487             appointmentForm.setTimeStart( minStartingTime.toString( ) );
488             appointmentForm.setTimeEnd( maxEndingTime.toString( ) );
489             appointmentForm.setDurationAppointments( nDurationAppointment );
490         }
491     }
492 
493     /**
494      * Fill the appointmentForm DTO with the Reservation Rule
495      * 
496      * @param appointmentForm
497      *            the appointmentForm DTO
498      * @param reservationRule
499      *            the reservation rule
500      */
501     private static void fillAppointmentFormWithReservationRulePart( AppointmentFormDTO appointmentForm, ReservationRule reservationRule )
502     {
503         appointmentForm.setIdReservationRule( reservationRule.getIdReservationRule( ) );
504         appointmentForm.setMaxCapacityPerSlot( reservationRule.getMaxCapacityPerSlot( ) );
505         appointmentForm.setMaxPeoplePerAppointment( reservationRule.getMaxPeoplePerAppointment( ) );
506     }
507 
508     /**
509      * Fill the appointmentForm DTO with the form rule
510      * 
511      * @param appointmentForm
512      *            the appointmentForm DTO
513      * @param formRule
514      *            the form rule
515      */
516     private static void fillAppointmentFormWithFormRulePart( AppointmentFormDTO appointmentForm, FormRule formRule )
517     {
518         appointmentForm.setEnableCaptcha( formRule.getIsCaptchaEnabled( ) );
519         appointmentForm.setEnableMandatoryEmail( formRule.getIsMandatoryEmailEnabled( ) );
520         appointmentForm.setActiveAuthentication( formRule.getIsActiveAuthentication( ) );
521         appointmentForm.setNbDaysBeforeNewAppointment( formRule.getNbDaysBeforeNewAppointment( ) );
522         appointmentForm.setMinTimeBeforeAppointment( formRule.getMinTimeBeforeAppointment( ) );
523         appointmentForm.setNbMaxAppointmentsPerUser( formRule.getNbMaxAppointmentsPerUser( ) );
524         appointmentForm.setNbDaysForMaxAppointmentsPerUser( formRule.getNbDaysForMaxAppointmentsPerUser( ) );
525     }
526 
527     /**
528      * Fill the appointmentForm DTO with the form
529      * 
530      * @param appointmentForm
531      *            the appointmentForm DTO
532      * @param form
533      *            the Form
534      */
535     private static void fillAppointmentFormWithFormPart( AppointmentFormDTO appointmentForm, Form form )
536     {
537         appointmentForm.setIdForm( form.getIdForm( ) );
538         appointmentForm.setTitle( form.getTitle( ) );
539         appointmentForm.setDescription( form.getDescription( ) );
540         appointmentForm.setReference( form.getReference( ) );
541         if ( form.getIdCategory( ) == null || form.getIdCategory( ) == 0 )
542         {
543             appointmentForm.setIdCategory( -1 );
544         }
545         else
546         {
547             appointmentForm.setIdCategory( form.getIdCategory( ) );
548         }
549         appointmentForm.setDateStartValidity( form.getStartingValiditySqlDate( ) );
550         appointmentForm.setDateEndValidity( form.getEndingValiditySqlDate( ) );
551         appointmentForm.setIdWorkflow( form.getIdWorkflow( ) );
552         appointmentForm.setWorkgroup( form.getWorkgroup( ) );
553         appointmentForm.setIsActive( form.getIsActive( ) );
554     }
555 
556     /**
557      * Fill the appointmentForm DTO with the display
558      * 
559      * @param appointmentForm
560      *            the appointmentForm DTO
561      * @param display
562      *            the display
563      */
564     private static void fillAppointmentFormWithDisplayPart( AppointmentFormDTO appointmentForm, Display display )
565     {
566         appointmentForm.setDisplayTitleFo( display.isDisplayTitleFo( ) );
567         appointmentForm.setIcon( display.getIcon( ) );
568         appointmentForm.setNbWeeksToDisplay( display.getNbWeeksToDisplay( ) );
569         appointmentForm.setIsDisplayedOnPortlet( display.isDisplayedOnPortlet( ) );
570         appointmentForm.setCalendarTemplateId( display.getIdCalendarTemplate( ) );
571     }
572 
573     /**
574      * Fill the appointmentForm DTO with the localization
575      * 
576      * @param appointmentForm
577      *            the appointmentForm DTO
578      * @param localization
579      *            the localization
580      */
581     private static void fillAppointmentFormWithLocalizationPart( AppointmentFormDTO appointmentForm, Localization localization )
582     {
583         if ( localization != null )
584         {
585             if ( localization.getLongitude( ) != null )
586             {
587                 appointmentForm.setLongitude( localization.getLongitude( ) );
588             }
589             if ( localization.getLatitude( ) != null )
590             {
591                 appointmentForm.setLatitude( localization.getLatitude( ) );
592             }
593             if ( localization.getAddress( ) != null )
594             {
595                 appointmentForm.setAddress( localization.getAddress( ) );
596             }
597         }
598 
599     }
600 
601     /**
602      * Check the validity of the form and update it if necessary
603      * 
604      * @param form
605      *            the form to check
606      */
607     private static void checkValidityDate( Form form )
608     {
609         LocalDate dateNow = LocalDate.now( );
610         if ( form.getStartingValidityDate( ) != null
611                 && !form.getIsActive( )
612                 && ( form.getStartingValidityDate( ).isBefore( dateNow ) || form.getStartingValidityDate( ).isEqual( dateNow ) )
613                 && ( form.getEndingValidityDate( ) == null || form.getEndingValidityDate( ).isAfter( dateNow ) || form.getEndingValidityDate( ).isEqual(
614                         dateNow ) ) )
615         {
616             form.setIsActive( true );
617             FormService.updateForm( form );
618 
619         }
620         else
621             if ( form.getEndingValidityDate( ) != null && form.getIsActive( ) && form.getEndingValidityDate( ).isBefore( dateNow ) )
622             {
623                 form.setIsActive( false );
624                 FormService.updateForm( form );
625             }
626     }
627 
628     /**
629      * Create a form from an appointmentForm DTO
630      * 
631      * @param appointmentForm
632      *            the appointmentForm DTO
633      * @return the Form created
634      */
635     public static Form createForm( AppointmentFormDTO appointmentForm )
636     {
637         Form form = new Form( );
638         form = fillInFormWithAppointmentForm( form, appointmentForm );
639         FormHome.create( form );
640         FormListenerManager.notifyListenersFormCreation( form.getIdForm( ) );
641         return form;
642     }
643 
644     /**
645      * Update a form object with the values of the appointmentForm DTO
646      * 
647      * @param appointmentForm
648      *            the appointmentForm DTO
649      * @return the Form object updated
650      */
651     public static Form updateForm( AppointmentFormDTO appointmentForm )
652     {
653         Form form = FormService.findFormLightByPrimaryKey( appointmentForm.getIdForm( ) );
654         form = fillInFormWithAppointmentForm( form, appointmentForm );
655         FormService.updateForm( form );
656         return form;
657     }
658 
659     /**
660      * Update a form
661      * 
662      * @param form
663      *            the form
664      * @return the form updated
665      */
666     public static Form updateForm( Form form )
667     {
668         Form formUpdated = FormHome.update( form );
669         FormListenerManager.notifyListenersFormChange( formUpdated.getIdForm( ) );
670         return formUpdated;
671     }
672 
673     /**
674      * Fill the form object with the values of the appointmentForm DTO
675      * 
676      * @param form
677      *            the form object
678      * @param appointmentForm
679      *            the appointmentForm DTO
680      * @return the form completed
681      */
682     public static Form fillInFormWithAppointmentForm( Form form, AppointmentFormDTO appointmentForm )
683     {
684         form.setTitle( appointmentForm.getTitle( ) );
685         form.setDescription( appointmentForm.getDescription( ) );
686         form.setReference( appointmentForm.getReference( ) );
687         if ( appointmentForm.getIdCategory( ) == -1 )
688         {
689             form.setIdCategory( null );
690         }
691         else
692         {
693             form.setIdCategory( appointmentForm.getIdCategory( ) );
694         }
695         form.setStartingValiditySqlDate( appointmentForm.getDateStartValidity( ) );
696         form.setEndingValiditySqlDate( appointmentForm.getDateEndValidity( ) );
697         form.setIsActive( appointmentForm.getIsActive( ) );
698         form.setIdWorkflow( appointmentForm.getIdWorkflow( ) );
699         form.setWorkgroup( appointmentForm.getWorkgroup( ) );
700         return form;
701     }
702 
703     /**
704      * Remove a Form from the database
705      * 
706      * @param nIdForm
707      *            the form id to remove
708      */
709     public static void removeForm( int nIdForm )
710     {
711         // Delete all the responses linked to all the appointments of the form
712         for ( Appointment appointment : AppointmentService.findListAppointmentByIdForm( nIdForm ) )
713         {
714             AppointmentResponseService.removeResponsesByIdAppointment( appointment.getIdAppointment( ) );
715         }
716         FormListenerManager.notifyListenersFormRemoval( nIdForm );
717         AppointmentListenerManager.notifyListenersAppointmentFormRemoval( nIdForm );
718         FormHome.delete( nIdForm );
719     }
720 
721     /**
722      * Find all the forms in the database
723      * 
724      * @return a list of all the forms
725      */
726     public static List<Form> findAllForms( )
727     {
728         return FormHome.findAllForms( );
729     }
730 
731     /**
732      * Find all the active forms in database
733      * 
734      * @return a list of all the active forms
735      */
736     public static List<Form> findAllActiveForms( )
737     {
738         return FormHome.findActiveForms( );
739     }
740 
741     /**
742      * Find all the active forms that have to be displayed on portlet in database
743      * 
744      * @return a list of all the found forms
745      */
746     public static List<Form> findAllActiveAndDisplayedOnPortletForms( )
747     {
748         return FormHome.findActiveAndDisplayedOnPortletForms( );
749     }
750 
751     /**
752      * find a form by its primary key
753      * 
754      * @param nIdForm
755      *            the form Id
756      * @return the Form
757      */
758     public static Form findFormLightByPrimaryKey( int nIdForm )
759     {
760         return FormHome.findByPrimaryKey( nIdForm );
761     }
762 
763     /**
764      * Find forms by the title
765      * 
766      * @param strTitle
767      *            the form title
768      * @return the Forms with this title
769      */
770     public static List<Form> findFormsByTitle( String strTitle )
771     {
772         return FormHome.findByTitle( strTitle );
773     }
774 
775 }