View Javadoc
1   /**
2    * Copyright 2004-2014 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.kpme.tklm.leave.calendar.web;
17  
18  import org.apache.commons.collections.CollectionUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.apache.log4j.Logger;
21  import org.apache.struts.action.ActionForm;
22  import org.apache.struts.action.ActionForward;
23  import org.apache.struts.action.ActionMapping;
24  import org.joda.time.DateTime;
25  import org.joda.time.LocalDate;
26  import org.json.simple.JSONArray;
27  import org.json.simple.JSONValue;
28  import org.kuali.kpme.core.api.assignment.Assignment;
29  import org.kuali.kpme.core.api.assignment.AssignmentDescriptionKey;
30  import org.kuali.kpme.core.api.calendar.entry.CalendarEntry;
31  import org.kuali.kpme.core.api.earncode.EarnCode;
32  import org.kuali.kpme.core.service.HrServiceLocator;
33  import org.kuali.kpme.core.util.HrConstants;
34  import org.kuali.kpme.core.util.HrContext;
35  import org.kuali.kpme.core.util.TKUtils;
36  import org.kuali.kpme.tklm.leave.calendar.LeaveCalendarDocument;
37  import org.kuali.kpme.tklm.leave.calendar.validation.LeaveCalendarValidationUtil;
38  import org.kuali.kpme.tklm.leave.service.LmServiceLocator;
39  import org.kuali.kpme.tklm.time.detail.web.ActionFormUtils;
40  import org.kuali.kpme.tklm.time.detail.web.TimeDetailWSActionForm;
41  
42  import javax.servlet.http.HttpServletRequest;
43  import javax.servlet.http.HttpServletResponse;
44  
45  import java.util.ArrayList;
46  import java.util.HashMap;
47  import java.util.LinkedList;
48  import java.util.List;
49  import java.util.Map;
50  import java.util.Map.Entry;
51  
52  public class LeaveCalendarWSAction extends LeaveCalendarAction {
53  
54      private static final Logger LOG = Logger.getLogger(LeaveCalendarWSAction.class);
55          
56      public ActionForward getEarnCodeInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
57      	LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
58          LOG.info(lcf.toString());
59          EarnCode earnCode = HrServiceLocator.getEarnCodeService().getEarnCodeById(lcf.getSelectedEarnCode());
60      	String unitTime = ActionFormUtils.getUnitOfTimeForEarnCode(earnCode);
61          Map<String, Object> earnCodeMap = new HashMap<String, Object>();
62          earnCodeMap.put("unitOfTime", unitTime);
63          earnCodeMap.put("defaultAmountofTime", earnCode.getDefaultAmountofTime());
64          earnCodeMap.put("fractionalTimeAllowed", earnCode.getFractionalTimeAllowed());
65          lcf.setOutputString(JSONValue.toJSONString(earnCodeMap));
66          return mapping.findForward("ws");
67      }
68  
69      public ActionForward getEarnCodeJson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
70          LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
71  
72          List<Map<String, Object>> earnCodeList = new LinkedList<Map<String, Object>>();
73  
74          CalendarEntry calendarEntry = lcf.getCalendarEntry();
75          if (StringUtils.isNotBlank(lcf.getSelectedAssignment())) {
76              LocalDate asOfDate = calendarEntry.getEndPeriodFullDateTime().toLocalDate();
77  
78              if (lcf.getStartDate() != null) {
79                  try {
80                      DateTime utilDate = HrConstants.DateTimeFormats.BASIC_DATE_FORMAT.parseDateTime(lcf.getStartDate());
81                      asOfDate = utilDate.toLocalDate();
82                  } catch (Exception ex) {
83                      //ignore and use the timesheet as of date.
84                  }
85              }
86          	Map<LocalDate, List<Assignment>> assignments = HrServiceLocator.getAssignmentService().getAssignmentsByCalEntryForLeaveCalendar(HrContext.getTargetPrincipalId(), calendarEntry);
87          	boolean leavePlanningCalendar = LmServiceLocator.getLeaveCalendarService().isLeavePlanningCalendar(HrContext.getTargetPrincipalId(), calendarEntry.getBeginPeriodFullDateTime().toLocalDate(), calendarEntry.getEndPeriodFullDateTime().toLocalDate());
88              AssignmentDescriptionKey key = AssignmentDescriptionKey.get(lcf.getSelectedAssignment());
89              List<Assignment> dayAssigns = assignments.get(asOfDate);
90              for (Assignment assignment : dayAssigns) {
91              	if (assignment.getJobNumber().compareTo(key.getJobNumber()) == 0 &&
92                          assignment.getWorkArea().compareTo(key.getWorkArea()) == 0 &&
93                          assignment.getTask().compareTo(key.getTask()) == 0) {
94              		List<EarnCode> earnCodes = HrServiceLocator.getEarnCodeService().getEarnCodesForLeave(assignment,asOfDate , leavePlanningCalendar);
95                      for (EarnCode earnCode : earnCodes) {
96                          Map<String, Object> earnCodeMap = new HashMap<String, Object>();
97                          earnCodeMap.put("assignment", assignment.getAssignmentKey());
98                          earnCodeMap.put("earnCode", earnCode.getEarnCode());
99                          earnCodeMap.put("desc", earnCode.getDescription());
100                         earnCodeMap.put("type", earnCode.getEarnCodeType());
101                         earnCodeMap.put("earnCodeId", earnCode.getHrEarnCodeId());
102                         earnCodeMap.put("unitOfTime", earnCode.getRecordMethod());
103                         earnCodeMap.put("defaultAmountofTime", earnCode.getDefaultAmountofTime());
104                         earnCodeMap.put("fractionalTimeAllowed", earnCode.getFractionalTimeAllowed());
105                         earnCodeList.add(earnCodeMap);
106                     }
107                 }
108             }
109         }
110         
111         LOG.info(lcf.toString());
112         lcf.setOutputString(JSONValue.toJSONString(earnCodeList));
113         
114         return mapping.findForward("ws");
115     }
116     
117     /**
118      * This is an ajax call triggered after a user submits the leave entry form.
119      * If there is any error, it will return error messages as a json object.
120      *
121      * @param mapping
122      * @param form
123      * @param request
124      * @param response
125      * @return jsonObj
126      * @throws Exception
127      */
128     @SuppressWarnings("unchecked")
129     public ActionForward validateLeaveEntry(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
130     	LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
131     	JSONArray errorMsgList = new JSONArray();
132 
133     	errorMsgList.addAll(LeaveCalendarValidationUtil.validateLeaveEntry(lcf));
134 
135     	
136         lcf.setOutputString(JSONValue.toJSONString(errorMsgList));
137         
138         return mapping.findForward("ws");
139     }
140 
141     protected void setupDocumentOnFormContext(LeaveCalendarForm leaveForm,
142                                               LeaveCalendarDocument lcd) {
143         leaveForm.setLeaveCalendarDocument(lcd);
144     }
145     
146     
147     public ActionForward getValidAssignments(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
148 		TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
149 
150         //need an asOfDate here
151         LocalDate asOfDate = tdaf.getTimesheetDocument().getAsOfDate();
152 
153         if (tdaf.getStartDate() != null) {
154             try {
155                 DateTime utilDate = HrConstants.DateTimeFormats.BASIC_DATE_FORMAT.parseDateTime(tdaf.getStartDate());
156                 asOfDate = utilDate.toLocalDate();
157             } catch (Exception ex) {
158                 //ignore and use the timesheet as of date.
159             }
160         }
161 		String earnCode = tdaf.getSelectedEarnCode();
162 
163 		List<Map<String, Object>> assignments = new ArrayList<Map<String, Object>>();
164 		if (tdaf.getTimesheetDocument() != null && StringUtils.isNotEmpty(earnCode)) {
165 			assignments = getAssignmentsForRegEarnCode(tdaf.getTimesheetDocument().getAssignmentMap().get(asOfDate), earnCode, asOfDate);
166 		}
167 		tdaf.setOutputString(JSONValue.toJSONString(assignments));
168 		return mapping.findForward("ws");
169 	}
170     
171     protected List<Map<String, Object>> getAssignmentsForRegEarnCode(List<Assignment> assigns, String earnCode, LocalDate asOfDate) {
172         List<Map<String, Object>> assignments = new ArrayList<Map<String, Object>>();
173         if (CollectionUtils.isNotEmpty(assigns)) {
174 			for (Assignment a : assigns) {
175 				Map<String, Object> assignment = new HashMap<String, Object>();
176 				if (earnCode.equals(a.getJob().getPayTypeObj().getRegEarnCode())) {
177 					assignment.put("assignment", a.getAssignmentKey());
178                     assignment.put("desc", a.getAssignmentDescription());
179                     assignments.add(assignment);
180 				}
181 			}
182 		}
183 		return assignments;
184 	}
185     
186     public ActionForward getAssignmentJson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
187         LeaveCalendarWSForm lcf = (LeaveCalendarWSForm) form;
188         String earnCode = lcf.getSelectedEarnCode();
189         LocalDate asOfDate = null;
190         if (lcf.getStartDate() != null) {
191             try {
192                 DateTime utilDate = HrConstants.DateTimeFormats.BASIC_DATE_FORMAT.parseDateTime(lcf.getStartDate());
193                 asOfDate = utilDate.toLocalDate();
194             } catch (Exception ex) {
195                 //ignore and use the leaveCalendar as of date.
196             }
197         }
198         List<Map<String, Object>> assignments = new ArrayList<Map<String, Object>>();
199         if (asOfDate == null) {
200             Map<String, Object> assignmentMap = new HashMap<String, Object>(2);
201             assignmentMap.put("assignment", "");
202             assignmentMap.put("desc", "-- enter valid date range --");
203             assignments.add(assignmentMap);
204         }
205         lcf.setLeaveCalendarDocument(LmServiceLocator.getLeaveCalendarService().getLeaveCalendarDocument(lcf.getDocumentId()));
206         if (lcf.getLeaveCalendarDocument()!=null && asOfDate != null) {
207             //check date to see if assignment is active
208             String principalId = lcf.getLeaveCalendarDocument().getPrincipalId();
209             CalendarEntry ce = lcf.getLeaveCalendarDocument().getCalendarEntry();
210             Map<LocalDate, List<Assignment>> history = lcf.getLeaveCalendarDocument().getAssignmentMap();
211             List<Assignment> dayAssignments = history.get(asOfDate);
212             dayAssignments = HrServiceLocator.getAssignmentService().filterAssignmentListForUser(HrContext.getPrincipalId(), dayAssignments);
213             if (CollectionUtils.isNotEmpty(dayAssignments)) {
214                 if (dayAssignments.size() > 1) {
215                     Map<String, Object> assignmentMap = new HashMap<String, Object>(2);
216                     assignmentMap.put("assignment", "");
217                     assignmentMap.put("desc", "-- select an assignment --");
218                     assignments.add(assignmentMap);
219                 }
220                 for (Assignment a : dayAssignments) {
221                     Map<String, Object> assignmentMap = new HashMap<String, Object>(2);
222                     assignmentMap.put("assignment", a.getAssignmentKey());
223                     assignmentMap.put("desc", HrServiceLocator.getAssignmentService().getAssignmentDescriptionForAssignment(a, asOfDate));
224                     assignments.add(assignmentMap);
225                 }
226             }
227         }
228 
229         lcf.setOutputString(JSONValue.toJSONString(assignments));
230         return mapping.findForward("ws");
231     }
232 
233 }