View Javadoc

1   /**
2    * Copyright 2004-2013 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.hr.lm.leave.web;
17  
18  import java.sql.Date;
19  import java.util.HashMap;
20  import java.util.LinkedList;
21  import java.util.List;
22  import java.util.Map;
23  
24  import javax.servlet.http.HttpServletRequest;
25  import javax.servlet.http.HttpServletResponse;
26  
27  import org.apache.commons.lang.StringUtils;
28  import org.apache.log4j.Logger;
29  import org.apache.struts.action.ActionForm;
30  import org.apache.struts.action.ActionForward;
31  import org.apache.struts.action.ActionMapping;
32  import org.joda.time.DateTime;
33  import org.json.simple.JSONArray;
34  import org.json.simple.JSONValue;
35  import org.kuali.hr.lm.LMConstants;
36  import org.kuali.hr.lm.accrual.AccrualCategory;
37  import org.kuali.hr.lm.leaveSummary.LeaveSummary;
38  import org.kuali.hr.lm.leavecalendar.LeaveCalendarDocument;
39  import org.kuali.hr.lm.leavecalendar.validation.LeaveCalendarValidationUtil;
40  import org.kuali.hr.lm.leavecalendar.web.LeaveCalendarForm;
41  import org.kuali.hr.time.assignment.Assignment;
42  import org.kuali.hr.time.assignment.AssignmentDescriptionKey;
43  import org.kuali.hr.time.base.web.TkAction;
44  import org.kuali.hr.time.calendar.CalendarEntries;
45  import org.kuali.hr.time.detail.web.ActionFormUtils;
46  import org.kuali.hr.time.earncode.EarnCode;
47  import org.kuali.hr.time.service.base.TkServiceLocator;
48  import org.kuali.hr.time.util.TKContext;
49  import org.kuali.hr.time.util.TKUser;
50  import org.kuali.hr.time.util.TKUtils;
51  
52  public class LeaveCalendarWSAction extends TkAction {
53  
54      private static final Logger LOG = Logger.getLogger(LeaveCalendarWSAction.class);
55  
56      @Override
57      public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
58          //return super.execute(mapping, form, request, response);
59          LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
60  
61          String documentId = lcf.getDocumentId();
62          // if the reload was trigger by changing of the selectedPayPeriod, use the passed in parameter as the calendar entry id
63          String calendarEntryId = StringUtils.isNotBlank(request.getParameter("selectedPP")) ? request.getParameter("selectedPP") : lcf.getCalEntryId();
64  
65          // Here - viewPrincipal will be the principal of the user we intend to
66          // view, be it target user, backdoor or otherwise.
67          String viewPrincipal = TKUser.getCurrentTargetPersonId();
68          CalendarEntries calendarEntry = null;
69  
70          LeaveCalendarDocument lcd = null;
71          // By handling the prev/next in the execute method, we are saving one
72          // fetch/construction of a TimesheetDocument. If it were broken out into
73          // methods, we would first fetch the current document, and then fetch
74          // the next one instead of doing it in the single action.
75          if (StringUtils.isNotBlank(documentId)) {
76              lcd = TkServiceLocator.getLeaveCalendarService()
77                      .getLeaveCalendarDocument(documentId);
78              if (lcd != null) {
79                  calendarEntry = lcd.getCalendarEntry();
80              }
81          } else if (StringUtils.isNotBlank(calendarEntryId)) {
82              // do further procedure
83              calendarEntry = TkServiceLocator.getCalendarEntriesService()
84                      .getCalendarEntries(calendarEntryId);
85              lcd = TkServiceLocator.getLeaveCalendarService()
86                      .getLeaveCalendarDocument(viewPrincipal, calendarEntry);
87          } else {
88              // Default to whatever is active for "today".
89              Date currentDate = TKUtils.getTimelessDate(null);
90              calendarEntry = TkServiceLocator.getCalendarService()
91                      .getCurrentCalendarDatesForLeaveCalendar(viewPrincipal, currentDate);
92              lcd = TkServiceLocator.getLeaveCalendarService()
93                      .openLeaveCalendarDocument(viewPrincipal, calendarEntry);
94          }
95  
96          lcf.setCalendarEntry(calendarEntry);
97          lcf.setAssignmentDescriptions(TkServiceLocator.getAssignmentService().getAssignmentDescriptions(lcd));
98  
99          if (lcd != null) {
100             setupDocumentOnFormContext(lcf, lcd);
101         } else {
102             LOG.error("Null leave calendar document in LeaveCalendarAction.");
103         }
104 
105         ActionForward forward = super.execute(mapping, form, request, response);
106         if (forward.getRedirect()) {
107             return forward;
108         }
109 
110         return forward;
111     }
112 
113         
114     public ActionForward getEarnCodeInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
115     	LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
116         LOG.info(lcf.toString());
117         EarnCode earnCode = TkServiceLocator.getEarnCodeService().getEarnCodeById(lcf.getSelectedEarnCode());
118     	String unitTime = ActionFormUtils.getUnitOfTimeForEarnCode(earnCode);
119         Map<String, Object> earnCodeMap = new HashMap<String, Object>();
120         earnCodeMap.put("unitOfTime", unitTime);
121         earnCodeMap.put("defaultAmountofTime", earnCode.getDefaultAmountofTime());
122         earnCodeMap.put("fractionalTimeAllowed", earnCode.getFractionalTimeAllowed());
123         lcf.setOutputString(JSONValue.toJSONString(earnCodeMap));
124         return mapping.findForward("ws");
125     }
126 
127     public ActionForward getEarnCodeJson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
128         //TODO: copied from TimeDetailWSAction.  Need to reduce code duplication
129         LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
130 
131 
132         if(request.getParameter("selectedPayPeriod") != null) {
133             lcf.setSelectedPayPeriod(request.getParameter("selectedPayPeriod"));
134             CalendarEntries ce = TkServiceLocator.getCalendarEntriesService().getCalendarEntries(request.getParameter("selectedPayPeriod"));
135             lcf.setCalendarEntry(ce);
136         }
137         lcf.setPrincipalId(TKUser.getCurrentTargetPersonId());
138         boolean isPlanningCal = TkServiceLocator.getLeaveCalendarService().isLeavePlanningCalendar(lcf.getPrincipalId(), lcf.getCalendarEntry().getBeginPeriodDateTime(), lcf.getCalendarEntry().getEndPeriodDateTime());
139         lcf.setLeavePlanningCalendar(isPlanningCal);
140 
141         List<Map<String, Object>> earnCodeList = new LinkedList<Map<String, Object>>();
142 
143         if (StringUtils.isNotBlank(lcf.getSelectedAssignment())) {
144             List<Assignment> assignments = lcf.getLeaveCalendarDocument().getAssignments();
145             AssignmentDescriptionKey key = new AssignmentDescriptionKey(lcf.getSelectedAssignment());
146             for (Assignment assignment : assignments) {
147             	if (assignment.getJobNumber().compareTo(key.getJobNumber()) == 0 &&
148                         assignment.getWorkArea().compareTo(key.getWorkArea()) == 0 &&
149                         assignment.getTask().compareTo(key.getTask()) == 0) {
150                 	List<EarnCode> earnCodes = TkServiceLocator.getEarnCodeService().getEarnCodesForLeave(assignment, new java.sql.Date(TKUtils.convertDateStringToTimestamp(lcf.getStartDate()).getTime()), lcf.isLeavePlanningCalendar());
151                     for (EarnCode earnCode : earnCodes) {
152                         Map<String, Object> earnCodeMap = new HashMap<String, Object>();
153                         earnCodeMap.put("assignment", assignment.getAssignmentKey());
154                         earnCodeMap.put("earnCode", earnCode.getEarnCode());
155                         earnCodeMap.put("desc", earnCode.getDescription());
156                         earnCodeMap.put("type", earnCode.getEarnCodeType());
157                         earnCodeMap.put("earnCodeId", earnCode.getHrEarnCodeId());
158                         earnCodeMap.put("unitOfTime", earnCode.getRecordMethod());
159                         earnCodeMap.put("defaultAmountofTime", earnCode.getDefaultAmountofTime());
160                         earnCodeMap.put("fractionalTimeAllowed", earnCode.getFractionalTimeAllowed());
161                         earnCodeList.add(earnCodeMap);
162                     }
163                 }
164             }
165         }
166         //LOG.info(lcf.toString());
167         lcf.setOutputString(JSONValue.toJSONString(earnCodeList));
168         return mapping.findForward("ws");
169     }
170     
171     /**
172      * This is an ajax call triggered after a user submits the leave entry form.
173      * If there is any error, it will return error messages as a json object.
174      *
175      * @param mapping
176      * @param form
177      * @param request
178      * @param response
179      * @return jsonObj
180      * @throws Exception
181      */
182     @SuppressWarnings("unchecked")
183     public ActionForward validateLeaveEntry(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
184     	LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
185     	JSONArray errorMsgList = new JSONArray();
186 
187     	if(lcf.getLeaveSummary() == null && lcf.getCalendarEntry() != null) {
188     		LeaveSummary ls = TkServiceLocator.getLeaveSummaryService().getLeaveSummary(TKContext.getTargetPrincipalId(), lcf.getCalendarEntry());
189 		    lcf.setLeaveSummary(ls);
190     	}
191     	
192     	errorMsgList.addAll(LeaveCalendarValidationUtil.validateParametersAccordingToSelectedEarnCodeRecordMethod(lcf));
193     	
194     	errorMsgList.addAll(LeaveCalendarValidationUtil.validateAvailableLeaveBalance(lcf));
195     	//KPME-1263
196         errorMsgList.addAll(LeaveCalendarValidationUtil.validateLeaveAccrualRuleMaxUsage(lcf));
197 
198         //KPME-2010                
199         errorMsgList.addAll(LeaveCalendarValidationUtil.validateSpanningWeeks(lcf));
200         
201         lcf.setOutputString(JSONValue.toJSONString(errorMsgList));
202         
203         return mapping.findForward("ws");
204     }
205 
206     protected void setupDocumentOnFormContext(LeaveCalendarForm leaveForm,
207                                               LeaveCalendarDocument lcd) {
208         leaveForm.setLeaveCalendarDocument(lcd);
209     }
210 
211 }