001    /**
002     * Copyright 2004-2013 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.hr.time.detail.web;
017    
018    import java.util.ArrayList;
019    import java.util.HashMap;
020    import java.util.LinkedList;
021    import java.util.List;
022    import java.util.Map;
023    
024    import javax.servlet.http.HttpServletRequest;
025    import javax.servlet.http.HttpServletResponse;
026    
027    import org.apache.commons.lang.StringUtils;
028    import org.apache.log4j.Logger;
029    import org.apache.struts.action.ActionForm;
030    import org.apache.struts.action.ActionForward;
031    import org.apache.struts.action.ActionMapping;
032    import org.json.simple.JSONArray;
033    import org.json.simple.JSONValue;
034    import org.kuali.hr.job.Job;
035    import org.kuali.hr.lm.leaveSummary.LeaveSummary;
036    import org.kuali.hr.lm.leaveblock.LeaveBlock;
037    import org.kuali.hr.lm.leavecalendar.validation.LeaveCalendarValidationUtil;
038    import org.kuali.hr.time.assignment.Assignment;
039    import org.kuali.hr.time.assignment.AssignmentDescriptionKey;
040    import org.kuali.hr.time.calendar.CalendarEntries;
041    import org.kuali.hr.time.detail.validation.TimeDetailValidationUtil;
042    import org.kuali.hr.time.earncode.EarnCode;
043    import org.kuali.hr.time.service.base.TkServiceLocator;
044    import org.kuali.hr.time.timesheet.web.TimesheetAction;
045    import org.kuali.hr.time.util.TKContext;
046    import org.kuali.hr.time.util.TKUtils;
047    import org.kuali.hr.time.util.TkConstants;
048    import org.kuali.rice.kns.web.struts.form.KualiMaintenanceForm;
049    import org.kuali.rice.krad.util.ObjectUtils;
050    
051    public class TimeDetailWSAction extends TimesheetAction {
052    
053        private static final Logger LOG = Logger.getLogger(TimeDetailWSAction.class);
054    
055        @Override
056        public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
057            return super.execute(mapping, form, request, response);
058        }
059    
060        /**
061         * This is an ajax call triggered after a user submits the time entry form.
062         * If there is any error, it will return error messages as a json object.
063         *
064         * @param mapping
065         * @param form
066         * @param request
067         * @param response
068         * @return jsonObj
069         * @throws Exception
070         */
071        @SuppressWarnings("unchecked")
072        public ActionForward validateTimeEntry(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
073            TimeDetailActionFormBase tdaf = (TimeDetailActionFormBase) form;
074            JSONArray errorMsgList = new JSONArray();
075            List<String> errors = new ArrayList<String>();
076            
077            EarnCode ec = TkServiceLocator.getEarnCodeService().getEarnCode(tdaf.getSelectedEarnCode(), tdaf.getTimesheetDocument().getAsOfDate());
078            if(ec != null 
079                            && (ec.getLeavePlan() != null || ec.getEligibleForAccrual().equals("N"))) {     // leave blocks changes
080                    errors = this.validateLeaveEntry(tdaf);
081            } else {        // time blocks changes
082                    errors = TimeDetailValidationUtil.validateTimeEntryDetails(tdaf);
083            }
084            
085    //        List<String> errors = TimeDetailValidationService.validateTimeEntryDetails(tdaf);
086            errorMsgList.addAll(errors);
087    
088            tdaf.setOutputString(JSONValue.toJSONString(errorMsgList));
089            return mapping.findForward("ws");
090        }
091    
092        public List<String> validateLeaveEntry(TimeDetailActionFormBase tdaf) throws Exception {
093            List<String> errorMsgList = new ArrayList<String>();
094            CalendarEntries payCalendarEntry = tdaf.getPayCalendarDates();
095            if(ObjectUtils.isNotNull(payCalendarEntry)) {
096                    String leaveStart = tdaf.getStartDate();
097                            LeaveSummary ls = TkServiceLocator.getLeaveSummaryService().getLeaveSummary(TKContext.getTargetPrincipalId(), tdaf.getPayCalendarDates());
098                            LeaveBlock lb = null;
099                            if(StringUtils.isNotEmpty(tdaf.getLmLeaveBlockId())) {
100                                    lb = TkServiceLocator.getLeaveBlockService().getLeaveBlock(tdaf.getLmLeaveBlockId());
101                            }
102                            errorMsgList.addAll(LeaveCalendarValidationUtil.validateAvailableLeaveBalanceForUsage(tdaf.getSelectedEarnCode(), 
103                                            tdaf.getStartDate(), tdaf.getEndDate(), tdaf.getLeaveAmount(), lb));
104                            //Validate leave block does not exceed max usage. Leave Calendar Validators at this point rely on a leave summary.
105                    errorMsgList.addAll(LeaveCalendarValidationUtil.validateLeaveAccrualRuleMaxUsage(ls, tdaf.getSelectedEarnCode(),
106                        tdaf.getStartDate(), tdaf.getEndDate(), tdaf.getLeaveAmount(), lb));
107                    }
108                    return errorMsgList;
109        }
110        
111        
112        //this is an ajax call for the assignment maintenance page
113        public ActionForward getDepartmentForJobNumber(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
114            KualiMaintenanceForm kualiForm = (KualiMaintenanceForm) form;
115    
116            String principalId = (String) request.getAttribute("principalId");
117            Long jobNumber = (Long) request.getAttribute("jobNumber");
118    
119            Job job = TkServiceLocator.getJobService().getJob(principalId, jobNumber, TKUtils.getCurrentDate());
120            kualiForm.setAnnotation(job.getDept());
121    
122            return mapping.findForward("ws");
123        }
124    
125        public ActionForward getEarnCodeJson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
126            TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
127            List<Map<String, Object>> earnCodeList = new LinkedList<Map<String, Object>>();
128    
129            if (StringUtils.isNotBlank(tdaf.getSelectedAssignment())) {
130                List<Assignment> assignments = tdaf.getTimesheetDocument().getAssignments();
131                AssignmentDescriptionKey key = new AssignmentDescriptionKey(tdaf.getSelectedAssignment());
132                for (Assignment assignment : assignments) {
133                    if (assignment.getJobNumber().compareTo(key.getJobNumber()) == 0 &&
134                            assignment.getWorkArea().compareTo(key.getWorkArea()) == 0 &&
135                            assignment.getTask().compareTo(key.getTask()) == 0) {
136                        List<EarnCode> earnCodes = TkServiceLocator.getEarnCodeService().getEarnCodesForTime(assignment, tdaf.getTimesheetDocument().getAsOfDate());
137                        for (EarnCode earnCode : earnCodes) {
138                            Map<String, Object> earnCodeMap = new HashMap<String, Object>();
139                            earnCodeMap.put("assignment", assignment.getAssignmentKey());
140                            earnCodeMap.put("earnCode", earnCode.getEarnCode());
141                            earnCodeMap.put("desc", earnCode.getDescription());
142                            earnCodeMap.put("type", earnCode.getEarnCodeType());
143                            // for leave blocks
144                            earnCodeMap.put("leavePlan", earnCode.getLeavePlan());
145                            if(StringUtils.isNotEmpty(earnCode.getLeavePlan())) {
146                                earnCodeMap.put("fractionalTimeAllowed", earnCode.getFractionalTimeAllowed());
147                                earnCodeMap.put("unitOfTime", ActionFormUtils.getUnitOfTimeForEarnCode(earnCode));
148                            }
149                            earnCodeMap.put("eligibleForAccrual", earnCode.getEligibleForAccrual());
150                            earnCodeList.add(earnCodeMap);
151                        }
152                    }
153                }
154            }
155            LOG.info(tdaf.toString());
156            tdaf.setOutputString(JSONValue.toJSONString(earnCodeList));
157            return mapping.findForward("ws");
158        }
159    
160        public ActionForward getOvertimeEarnCodes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
161            TimeDetailWSActionForm tdaf = (TimeDetailWSActionForm) form;
162            List<EarnCode> overtimeEarnCodes = TkServiceLocator.getEarnCodeService().getOvertimeEarnCodes(TKUtils.getCurrentDate());
163            List<Map<String, Object>> overtimeEarnCodeList = new LinkedList<Map<String, Object>>();
164    
165            for (EarnCode earnCode : overtimeEarnCodes) {
166                Map<String, Object> earnCodeMap = new HashMap<String, Object>();
167                earnCodeMap.put("earnCode", earnCode.getEarnCode());
168                earnCodeMap.put("desc", earnCode.getDescription());
169    
170                overtimeEarnCodeList.add(earnCodeMap);
171            }
172    
173            LOG.info(tdaf.toString());
174            tdaf.setOutputString(JSONValue.toJSONString(overtimeEarnCodeList));
175            return mapping.findForward("ws");
176        }
177    
178    }