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.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         
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                         earnCodeList.add(earnCodeMap);
188                     }
189                 }
190             }
191         }
192         
193         LOG.info(tdaf.toString());
194         tdaf.setOutputString(JSONValue.toJSONString(earnCodeList));
195         
196         return mapping.findForward("ws");
197     }
198     
199     private Map<String, EarnCode> getRegularEarnCodes(TimesheetDocument td) {
200     	Map<String, EarnCode> regEarnCodes = new HashMap<String, EarnCode>();
201     	if (td != null) {
202     		for (Assignment a : td.getAssignments()) {
203     			if (a.getJob() != null
204     					&& a.getJob().getPayTypeObj() != null) {
205     				PayType payType = a.getJob().getPayTypeObj();
206     				EarnCode ec = payType.getRegEarnCodeObj();
207     				if (ec == null
208     						&& StringUtils.isNotEmpty(payType.getRegEarnCode()))  {
209     					ec = HrServiceLocator.getEarnCodeService().getEarnCode(payType.getRegEarnCode(), payType.getEffectiveLocalDate());
210     				}
211     				regEarnCodes.put(a.getAssignmentKey(), ec);
212 	    			}
213     			}
214     		}
215     	return regEarnCodes;
216 	}
217 
218 	private List<Map<String, Object>> getAssignmentsForRegEarnCode(TimesheetDocument td, String earnCode) {
219 		List<Map<String, Object>> assignments = new ArrayList<Map<String, Object>>();
220 		if (td != null) {
221 			for (Assignment a : td.getAssignments()) {
222 				Map<String, Object> assignment = new HashMap<String, Object>();
223 				if (earnCode.equals(a.getJob().getPayTypeObj().getRegEarnCode())) {
224 					assignment.put("assignment", a.getAssignmentKey());
225 					assignments.add(assignment);
226 				}
227 			}
228 		}
229 		return assignments;
230 	}
231 
232 	public ActionForward getValidAssignments(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
233 		TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
234 
235 		String earnCode = tdaf.getSelectedEarnCode();
236 
237 		List<Map<String, Object>> assignments = new ArrayList<Map<String, Object>>();
238 		if (tdaf.getTimesheetDocument() != null && StringUtils.isNotEmpty(earnCode)) {
239 			assignments = getAssignmentsForRegEarnCode(tdaf.getTimesheetDocument(), earnCode);
240 		}
241 		tdaf.setOutputString(JSONValue.toJSONString(assignments));
242 		return mapping.findForward("ws");
243 	}
244 
245     public ActionForward getOvertimeEarnCodes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
246         TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
247         List<EarnCode> overtimeEarnCodes = HrServiceLocator.getEarnCodeService().getOvertimeEarnCodes(LocalDate.now());
248         List<Map<String, Object>> overtimeEarnCodeList = new LinkedList<Map<String, Object>>();
249         
250         if(StringUtils.isNotEmpty(tdaf.getTkTimeBlockId())) {
251         	TimeBlock tb = TkServiceLocator.getTimeBlockService().getTimeBlock(tdaf.getTkTimeBlockId());
252         	if(tb != null) {
253         		Job job = HrServiceLocator.getJobService().getJob(HrContext.getTargetPrincipalId(), tb.getJobNumber(), tb.getEndDateTime().toLocalDate());
254         		if(job != null) {
255         			for (EarnCode earnCode : overtimeEarnCodes) {
256         				String employee = HrContext.isActiveEmployee() ? "Y" : null;
257         				String approver = HrContext.isApprover() ? "Y" : null;
258         				String payrollProcessor = HrContext.isPayrollProcessor() ? "Y" : null; // KPME-2532
259         				
260         				List<EarnCodeSecurity> securityList = HrServiceLocator.getEarnCodeSecurityService().getEarnCodeSecurityList(job.getDept(), job.getHrSalGroup(), earnCode.getEarnCode(), employee, approver, payrollProcessor, job.getLocation(),
261         									"Y", tb.getEndDateTime().toLocalDate());
262         				if(CollectionUtils.isNotEmpty(securityList)) {
263         					Map<String, Object> earnCodeMap = new HashMap<String, Object>();
264 	        	            earnCodeMap.put("earnCode", earnCode.getEarnCode());
265 	        	            earnCodeMap.put("desc", earnCode.getDescription());
266 	        	            overtimeEarnCodeList.add(earnCodeMap);
267         				}
268         	        }
269         		}
270         	}
271         
272         }
273         LOG.info(tdaf.toString());
274         tdaf.setOutputString(JSONValue.toJSONString(overtimeEarnCodeList));
275         return mapping.findForward("ws");
276     }
277 
278 }