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.time.detail.web;
17  
18  import java.util.ArrayList;
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.collections.CollectionUtils;
28  import org.apache.commons.lang.StringUtils;
29  import org.apache.log4j.Logger;
30  import org.apache.struts.action.ActionForm;
31  import org.apache.struts.action.ActionForward;
32  import org.apache.struts.action.ActionMapping;
33  import org.joda.time.LocalDate;
34  import org.json.simple.JSONArray;
35  import org.json.simple.JSONValue;
36  import org.kuali.kpme.core.assignment.Assignment;
37  import org.kuali.kpme.core.assignment.AssignmentDescriptionKey;
38  import org.kuali.kpme.core.calendar.entry.CalendarEntry;
39  import org.kuali.kpme.core.earncode.EarnCode;
40  import org.kuali.kpme.core.earncode.security.EarnCodeSecurity;
41  import org.kuali.kpme.core.job.Job;
42  import org.kuali.kpme.core.paytype.PayType;
43  import org.kuali.kpme.core.service.HrServiceLocator;
44  import org.kuali.kpme.core.util.HrContext;
45  import org.kuali.kpme.core.util.TKUtils;
46  import org.kuali.kpme.tklm.leave.block.LeaveBlock;
47  import org.kuali.kpme.tklm.leave.calendar.validation.LeaveCalendarValidationUtil;
48  import org.kuali.kpme.tklm.leave.service.LmServiceLocator;
49  import org.kuali.kpme.tklm.leave.summary.LeaveSummary;
50  import org.kuali.kpme.tklm.time.detail.validation.TimeDetailValidationUtil;
51  import org.kuali.kpme.tklm.time.service.TkServiceLocator;
52  import org.kuali.kpme.tklm.time.timeblock.TimeBlock;
53  import org.kuali.kpme.tklm.time.timesheet.TimesheetDocument;
54  import org.kuali.kpme.tklm.time.timesheet.web.TimesheetAction;
55  import org.kuali.rice.kns.web.struts.form.KualiMaintenanceForm;
56  import org.kuali.rice.krad.util.ObjectUtils;
57  
58  public class TimeDetailWSAction extends TimesheetAction {
59  
60      private static final Logger LOG = Logger.getLogger(TimeDetailWSAction.class);
61  
62      /**
63       * This is an ajax call triggered after a user submits the time entry form.
64       * If there is any error, it will return error messages as a json object.
65       *
66       * @param mapping
67       * @param form
68       * @param request
69       * @param response
70       * @return jsonObj
71       * @throws Exception
72       */
73      @SuppressWarnings("unchecked")
74      public ActionForward validateTimeEntry(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
75          TimeDetailActionFormBase tdaf = (TimeDetailActionFormBase) form;
76          JSONArray errorMsgList = new JSONArray();
77          List<String> errors;
78          
79          // validates the selected earn code exists on every day within the date range
80          errors = TimeDetailValidationUtil.validateEarnCode(tdaf.getSelectedEarnCode(), tdaf.getStartDate(), tdaf.getEndDate());
81          if(errors.isEmpty()) {
82              EarnCode ec = HrServiceLocator.getEarnCodeService().getEarnCode(tdaf.getSelectedEarnCode(),
83              																TKUtils.formatDateTimeStringNoTimezone(tdaf.getEndDate()).toLocalDate());
84  	        if(ec != null && ec.getLeavePlan() != null) {    // leave blocks changes
85  	    		errors = TimeDetailValidationUtil.validateLeaveEntry(tdaf);
86  	    	} else {	// time blocks changes
87  	    		errors = TimeDetailValidationUtil.validateTimeEntryDetails(tdaf);
88  	    	}
89          }
90          errorMsgList.addAll(errors);
91  
92          tdaf.setOutputString(JSONValue.toJSONString(errorMsgList));
93          return mapping.findForward("ws");
94      }
95  
96  /*
97   * Moved to TimeDetailValidationUtil
98   * 
99   *     public List<String> validateLeaveEntry(TimeDetailActionFormBase tdaf) throws Exception {
100     	List<String> errorMsgList = new ArrayList<String>();
101     	CalendarEntry payCalendarEntry = tdaf.getCalendarEntry();
102     	if(ObjectUtils.isNotNull(payCalendarEntry)) {
103 			LeaveBlock lb = null;
104 			if(StringUtils.isNotEmpty(tdaf.getLmLeaveBlockId())) {
105 				lb = LmServiceLocator.getLeaveBlockService().getLeaveBlock(tdaf.getLmLeaveBlockId());
106 			}
107 			
108 			// Validate LeaveBlock timings and all that
109 			errorMsgList.addAll(LeaveCalendarValidationUtil.validateParametersForLeaveEntry(tdaf.getSelectedEarnCode(), tdaf.getCalendarEntry(),
110 					tdaf.getStartDate(), tdaf.getEndDate(), tdaf.getStartTime(), tdaf.getEndTime(), tdaf.getSelectedAssignment(), null, tdaf.getLmLeaveBlockId()));
111 			errorMsgList.addAll(LeaveCalendarValidationUtil.validateAvailableLeaveBalanceForUsage(tdaf.getSelectedEarnCode(), 
112 					tdaf.getStartDate(), tdaf.getEndDate(), tdaf.getLeaveAmount(), lb));
113 			//Validate leave block does not exceed max usage. Leave Calendar Validators at this point rely on a leave summary.
114 	        errorMsgList.addAll(LeaveCalendarValidationUtil.validateLeaveAccrualRuleMaxUsage(tdaf.getSelectedEarnCode(),
115                     tdaf.getStartDate(), tdaf.getEndDate(), tdaf.getLeaveAmount(), lb));
116 	        errorMsgList.addAll(LeaveCalendarValidationUtil.validateHoursUnderTwentyFour(tdaf.getSelectedEarnCode(),
117 	        		tdaf.getStartDate(), tdaf.getEndDate(), tdaf.getLeaveAmount()));
118 		}
119 		return errorMsgList;
120     }*/
121     
122     
123     //this is an ajax call for the assignment maintenance page
124     public ActionForward getDepartmentForJobNumber(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
125         KualiMaintenanceForm kualiForm = (KualiMaintenanceForm) form;
126 
127         String principalId = (String) request.getAttribute("principalId");
128         Long jobNumber = (Long) request.getAttribute("jobNumber");
129 
130         Job job = HrServiceLocator.getJobService().getJob(principalId, jobNumber, LocalDate.now());
131         kualiForm.setAnnotation(job.getDept());
132 
133         return mapping.findForward("ws");
134     }
135 
136     public ActionForward getEarnCodeJson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
137         TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
138         boolean containsRegEarnCode = false;
139         List<Map<String, Object>> earnCodeList = new LinkedList<Map<String, Object>>();
140 
141         if (StringUtils.isNotBlank(tdaf.getSelectedAssignment())) {
142             List<Assignment> assignments = tdaf.getTimesheetDocument().getAssignments();
143             AssignmentDescriptionKey key = AssignmentDescriptionKey.get(tdaf.getSelectedAssignment());
144             Map<String, EarnCode> regEarnCodes = getRegularEarnCodes(tdaf.getTimesheetDocument());
145             for (Assignment assignment : assignments) {
146             	if (assignment.getJobNumber().equals(key.getJobNumber()) &&
147             			assignment.getWorkArea().equals(key.getWorkArea()) &&
148             			assignment.getTask().equals(key.getTask())) {
149             		List<EarnCode> earnCodes = new ArrayList<EarnCode>();
150             		if (tdaf.getTimeBlockReadOnly()) {
151             			if (regEarnCodes.containsKey(assignment.getAssignmentKey())) {
152             				earnCodes.add(regEarnCodes.get(assignment.getAssignmentKey()));
153             			}
154             		} else {
155             			LocalDate endDate = tdaf.getTimesheetDocument().getDocEndDate();
156             			if(StringUtils.isNotBlank(tdaf.getEndDate())) {
157             				LocalDate tempDate = TKUtils.formatDateString(tdaf.getEndDate());
158             				if(tempDate != null) {
159             					endDate = tempDate;
160             				}
161             			}
162             			
163             			// use endDate to grab earn codes
164             			List<EarnCode> aList = TkServiceLocator.getTimesheetService()
165             					.getEarnCodesForTime(assignment, endDate, tdaf.getTimeBlockReadOnly());
166             			
167             			for(EarnCode anEarnCode : aList) {
168             				// kpme-2570, overtime earn codes should not show in adding/editing time block widget's earn code option list
169             				if(anEarnCode != null && !anEarnCode.getOvtEarnCode()) {
170             					earnCodes.add(anEarnCode);
171             				}
172             			}
173             		}
174                     for (EarnCode earnCode : earnCodes) {
175                         Map<String, Object> earnCodeMap = new HashMap<String, Object>();
176                         earnCodeMap.put("assignment", assignment.getAssignmentKey());
177                         earnCodeMap.put("earnCode", earnCode.getEarnCode());
178                         earnCodeMap.put("desc", earnCode.getDescription());
179                         earnCodeMap.put("type", earnCode.getEarnCodeType());
180                         // for leave blocks
181                         earnCodeMap.put("leavePlan", earnCode.getLeavePlan());
182                         if(StringUtils.isNotEmpty(earnCode.getLeavePlan())) {
183                             earnCodeMap.put("fractionalTimeAllowed", earnCode.getFractionalTimeAllowed());
184                             earnCodeMap.put("unitOfTime", ActionFormUtils.getUnitOfTimeForEarnCode(earnCode));
185                         }
186                         earnCodeMap.put("eligibleForAccrual", earnCode.getEligibleForAccrual());
187                         EarnCode regEarnCode = regEarnCodes.get(assignment.getAssignmentKey());
188                         if (regEarnCode != null
189                                 && StringUtils.equals(regEarnCode.getEarnCode(), earnCode.getEarnCode())) {
190                             containsRegEarnCode = true;
191                         }
192                         earnCodeList.add(earnCodeMap);
193                     }
194                 }
195             }
196         }
197 
198         if (!containsRegEarnCode) {
199             Map<String, Object> earnCodeMap = new HashMap<String, Object>();
200             earnCodeMap.put("assignment", "");
201             earnCodeMap.put("earnCode", "");
202             earnCodeMap.put("desc", "-- select an earn code --");
203             earnCodeMap.put("type", "");
204             // for leave blocks
205             earnCodeMap.put("leavePlan", "");
206             earnCodeMap.put("eligibleForAccrual", "");
207 
208             earnCodeList.add(0, earnCodeMap);
209         }
210         LOG.info(tdaf.toString());
211         tdaf.setOutputString(JSONValue.toJSONString(earnCodeList));
212         
213         return mapping.findForward("ws");
214     }
215     
216     private Map<String, EarnCode> getRegularEarnCodes(TimesheetDocument td) {
217     	Map<String, EarnCode> regEarnCodes = new HashMap<String, EarnCode>();
218     	if (td != null) {
219     		for (Assignment a : td.getAssignments()) {
220     			if (a.getJob() != null
221     					&& a.getJob().getPayTypeObj() != null) {
222     				PayType payType = a.getJob().getPayTypeObj();
223     				EarnCode ec = payType.getRegEarnCodeObj();
224     				if (ec == null
225     						&& StringUtils.isNotEmpty(payType.getRegEarnCode()))  {
226     					ec = HrServiceLocator.getEarnCodeService().getEarnCode(payType.getRegEarnCode(), payType.getEffectiveLocalDate());
227     				}
228     				regEarnCodes.put(a.getAssignmentKey(), ec);
229 	    			}
230     			}
231     		}
232     	return regEarnCodes;
233 	}
234 
235 	private List<Map<String, Object>> getAssignmentsForRegEarnCode(TimesheetDocument td, String earnCode) {
236 		List<Map<String, Object>> assignments = new ArrayList<Map<String, Object>>();
237 		if (td != null) {
238 			for (Assignment a : td.getAssignments()) {
239 				Map<String, Object> assignment = new HashMap<String, Object>();
240 				if (earnCode.equals(a.getJob().getPayTypeObj().getRegEarnCode())) {
241 					assignment.put("assignment", a.getAssignmentKey());
242 					assignments.add(assignment);
243 				}
244 			}
245 		}
246 		return assignments;
247 	}
248 
249 	public ActionForward getValidAssignments(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
250 		TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
251 
252 		String earnCode = tdaf.getSelectedEarnCode();
253 
254 		List<Map<String, Object>> assignments = new ArrayList<Map<String, Object>>();
255 		if (tdaf.getTimesheetDocument() != null && StringUtils.isNotEmpty(earnCode)) {
256 			assignments = getAssignmentsForRegEarnCode(tdaf.getTimesheetDocument(), earnCode);
257 		}
258 		tdaf.setOutputString(JSONValue.toJSONString(assignments));
259 		return mapping.findForward("ws");
260 	}
261 
262     public ActionForward getOvertimeEarnCodes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
263         TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
264         List<EarnCode> overtimeEarnCodes = HrServiceLocator.getEarnCodeService().getOvertimeEarnCodes(LocalDate.now());
265         List<Map<String, Object>> overtimeEarnCodeList = new LinkedList<Map<String, Object>>();
266         
267         if(StringUtils.isNotEmpty(tdaf.getTkTimeBlockId())) {
268         	TimeBlock tb = TkServiceLocator.getTimeBlockService().getTimeBlock(tdaf.getTkTimeBlockId());
269         	if(tb != null) {
270         		Job job = HrServiceLocator.getJobService().getJob(HrContext.getTargetPrincipalId(), tb.getJobNumber(), tb.getEndDateTime().toLocalDate());
271         		if(job != null) {
272         			for (EarnCode earnCode : overtimeEarnCodes) {
273         				String employee = HrContext.isActiveEmployee() ? "Y" : null;
274         				String approver = HrContext.isApprover() ? "Y" : null;
275         				String payrollProcessor = HrContext.isPayrollProcessor() ? "Y" : null; // KPME-2532
276         				
277         				List<EarnCodeSecurity> securityList = HrServiceLocator.getEarnCodeSecurityService().getEarnCodeSecurityList(job.getDept(), job.getHrSalGroup(), earnCode.getEarnCode(), employee, approver, payrollProcessor, job.getLocation(),
278         									"Y", tb.getEndDateTime().toLocalDate());
279         				if(CollectionUtils.isNotEmpty(securityList)) {
280         					Map<String, Object> earnCodeMap = new HashMap<String, Object>();
281 	        	            earnCodeMap.put("earnCode", earnCode.getEarnCode());
282 	        	            earnCodeMap.put("desc", earnCode.getDescription());
283 	        	            overtimeEarnCodeList.add(earnCodeMap);
284         				}
285         	        }
286         		}
287         	}
288         
289         }
290         LOG.info(tdaf.toString());
291         tdaf.setOutputString(JSONValue.toJSONString(overtimeEarnCodeList));
292         return mapping.findForward("ws");
293     }
294 
295 }