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.struts.action.ActionForm;
21  import org.apache.struts.action.ActionForward;
22  import org.apache.struts.action.ActionMapping;
23  import org.apache.struts.action.ActionRedirect;
24  import org.joda.time.Interval;
25  import org.kuali.kpme.core.api.accrualcategory.rule.AccrualCategoryRuleContract;
26  import org.kuali.kpme.core.api.principal.PrincipalHRAttributes;
27  import org.kuali.kpme.core.service.HrServiceLocator;
28  import org.kuali.kpme.core.util.HrConstants;
29  import org.kuali.kpme.core.util.HrContext;
30  import org.kuali.kpme.core.web.KPMEAction;
31  import org.kuali.kpme.tklm.api.leave.block.LeaveBlock;
32  import org.kuali.kpme.tklm.api.leave.block.LeaveBlockContract;
33  import org.kuali.kpme.tklm.leave.calendar.LeaveCalendarDocument;
34  import org.kuali.kpme.tklm.leave.service.LmServiceLocator;
35  import org.kuali.kpme.tklm.time.service.TkServiceLocator;
36  import org.kuali.rice.kew.api.document.DocumentStatus;
37  import org.kuali.rice.krad.exception.AuthorizationException;
38  import org.kuali.rice.krad.util.GlobalVariables;
39  import org.kuali.rice.krad.util.ObjectUtils;
40  
41  import javax.servlet.http.HttpServletRequest;
42  import javax.servlet.http.HttpServletResponse;
43  import java.util.ArrayList;
44  import java.util.List;
45  import java.util.Map;
46  import java.util.Map.Entry;
47  import java.util.Set;
48  
49  
50  public class LeaveCalendarSubmitAction extends KPMEAction {
51      @Override
52      protected void checkTKAuthorization(ActionForm form, String methodToCall) throws AuthorizationException {
53          LeaveCalendarSubmitForm lcf = (LeaveCalendarSubmitForm) form;
54  
55          String principalId = GlobalVariables.getUserSession().getPrincipalId();
56          String documentId = lcf.getDocumentId();
57          LeaveCalendarDocument lcd = LmServiceLocator.getLeaveCalendarService().getLeaveCalendarDocument(documentId);
58          if (!HrServiceLocator.getHRPermissionService().canEditCalendarDocument(principalId, lcd)) {
59              throw new AuthorizationException(principalId, "LeaveCalendarSubmitAction", "");
60          }
61      }
62      
63      public ActionForward approveLeaveCalendar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
64      	String documentId = request.getParameter("documentId");
65      	String action = request.getParameter("action");
66          LeaveCalendarDocument document = LmServiceLocator.getLeaveCalendarService().getLeaveCalendarDocument(documentId);
67  
68          // Switched to grab the target (chain, resolution: target -> backdoor -> actual) user.
69          // Approvals still using backdoor > actual
70          if (StringUtils.equals(action, HrConstants.DOCUMENT_ACTIONS.ROUTE)) {
71              if (DocumentStatus.INITIATED.getCode().equals(document.getDocumentHeader().getDocumentStatus())
72                      || DocumentStatus.SAVED.getCode().equals(document.getDocumentHeader().getDocumentStatus())) {
73              	
74          		Map<String,Set<LeaveBlock>> eligibilities = LmServiceLocator.getAccrualCategoryMaxBalanceService().getMaxBalanceViolations(document.getCalendarEntry(), document.getPrincipalId());
75          		
76          		ActionRedirect transferRedirect = new ActionRedirect();
77          		ActionRedirect payoutRedirect = new ActionRedirect();
78  				
79  				List<LeaveBlock> eligibleTransfers = new ArrayList<LeaveBlock>();
80  				List<LeaveBlock> eligiblePayouts = new ArrayList<LeaveBlock>();
81          		Interval interval = new Interval(document.getCalendarEntry().getBeginPeriodFullDateTime(), document.getCalendarEntry().getEndPeriodFullDateTime());
82          		for(Entry<String,Set<LeaveBlock>> entry : eligibilities.entrySet()) {
83          			
84              		for(LeaveBlock lb : entry.getValue()) {
85              			if(interval.contains(lb.getLeaveDateTime())) {
86  	            			//maxBalanceViolations should, if a violation exists, return a leave block with leave date either current date, or the end period date - 1 days.
87                      		PrincipalHRAttributes pha = HrServiceLocator.getPrincipalHRAttributeService().getPrincipalCalendar(document.getPrincipalId(), lb.getLeaveLocalDate());
88  	        				AccrualCategoryRuleContract aRule = lb.getAccrualCategoryRule();
89  	
90  	            			if(ObjectUtils.isNotNull(aRule)
91  	            					&& !StringUtils.equals(aRule.getMaxBalanceActionFrequency(),HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND)) {
92  	            				if(StringUtils.equals(aRule.getMaxBalanceActionFrequency(),HrConstants.MAX_BAL_ACTION_FREQ.LEAVE_APPROVE)
93  	            						|| (StringUtils.equals(aRule.getMaxBalanceActionFrequency(),HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
94  	            								&& HrServiceLocator.getLeavePlanService().isLastCalendarPeriodOfLeavePlan(document.getCalendarEntry(),pha.getLeavePlan(),lb.getLeaveLocalDate())))
95  			            			if(StringUtils.equals(aRule.getActionAtMaxBalance(),HrConstants.ACTION_AT_MAX_BALANCE.PAYOUT)) {
96  			            				eligiblePayouts.add(lb);
97  			            			}
98  			            			else if(StringUtils.equals(aRule.getActionAtMaxBalance(), HrConstants.ACTION_AT_MAX_BALANCE.TRANSFER)
99  			            					|| StringUtils.equals(aRule.getActionAtMaxBalance(), HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
100 			            				eligibleTransfers.add(lb);
101 			            			}
102 	            			}
103             			}
104             		}
105         		}
106         		if(CollectionUtils.isNotEmpty(eligibleTransfers)) {
107         			//LOSE actions get lumped into this set, and are redirected back to this page to handle submission via dialog.
108             		transferRedirect.setPath("/BalanceTransfer.do?"+request.getQueryString());
109             		request.getSession().setAttribute("eligibilities", eligibleTransfers);
110             		return transferRedirect;
111         		}
112         		if(CollectionUtils.isNotEmpty(eligiblePayouts)) {
113             		payoutRedirect.setPath("/LeavePayout.do?"+request.getQueryString());
114             		request.getSession().setAttribute("eligibilities", eligiblePayouts);
115             		return payoutRedirect;           			
116         		}
117                 LmServiceLocator.getLeaveCalendarService().routeLeaveCalendar(HrContext.getTargetPrincipalId(), document);
118             }
119         } else if (StringUtils.equals(action, HrConstants.DOCUMENT_ACTIONS.APPROVE)) {
120             if (LmServiceLocator.getLeaveCalendarService().isReadyToApprove(document)) {
121                 if (document.getDocumentHeader().getDocumentStatus().equals(DocumentStatus.ENROUTE.getCode())) {
122                     LmServiceLocator.getLeaveCalendarService().approveLeaveCalendar(HrContext.getPrincipalId(), document);
123                 }
124             } else {
125                 //ERROR!!!!
126             }
127         } else if (StringUtils.equals(action, HrConstants.DOCUMENT_ACTIONS.DISAPPROVE)) {
128             if (document.getDocumentHeader().getDocumentStatus().equals(DocumentStatus.ENROUTE.getCode())) {
129                 LmServiceLocator.getLeaveCalendarService().disapproveLeaveCalendar(HrContext.getPrincipalId(), document);
130             }
131         }
132         ActionRedirect rd = new ActionRedirect(mapping.findForward("leaveCalendarRedirect"));
133         TkServiceLocator.getTkSearchableAttributeService().updateSearchableAttribute(document, document.getAsOfDate());
134         rd.addParameter("documentId", documentId);
135 
136         return rd;
137     }
138 
139     public ActionForward approveApprovalTab(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
140         LeaveCalendarSubmitForm lcf = (LeaveCalendarSubmitForm)form;
141         LeaveCalendarDocument document = LmServiceLocator.getLeaveCalendarService().getLeaveCalendarDocument(lcf.getDocumentId());
142 
143         // Switched to grab the target (chain, resolution: target -> backdoor -> actual) user.
144         // Approvals still using backdoor > actual
145         if (StringUtils.equals(lcf.getAction(), HrConstants.DOCUMENT_ACTIONS.ROUTE)) {
146             if (document.getDocumentHeader().getDocumentStatus().equals(DocumentStatus.INITIATED.getCode())) {
147                 LmServiceLocator.getLeaveCalendarService().routeLeaveCalendar(HrContext.getTargetPrincipalId(), document);
148             }
149         } else if (StringUtils.equals(lcf.getAction(), HrConstants.DOCUMENT_ACTIONS.APPROVE)) {
150             //Todo:  check for unfinalized BalanceTransfer on current leave calendar.
151             if (LmServiceLocator.getLeaveCalendarService().isReadyToApprove(document)) {
152                 if (document.getDocumentHeader().getDocumentStatus().equals(DocumentStatus.ENROUTE.getCode())) {
153                     LmServiceLocator.getLeaveCalendarService().approveLeaveCalendar(HrContext.getPrincipalId(), document);
154                 }
155             } else {
156                 //ERROR!!!!
157             }
158 
159         } else if (StringUtils.equals(lcf.getAction(), HrConstants.DOCUMENT_ACTIONS.DISAPPROVE)) {
160             if (document.getDocumentHeader().getDocumentStatus().equals(DocumentStatus.ENROUTE.getCode())) {
161                 LmServiceLocator.getLeaveCalendarService().disapproveLeaveCalendar(HrContext.getPrincipalId(), document);
162             }
163         }
164 
165         HrContext.clearTargetUser();
166         return new ActionRedirect(mapping.findForward("approverRedirect"));
167 
168     }
169 
170 }