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.base.web;
017    
018    import java.sql.Date;
019    import java.text.SimpleDateFormat;
020    import java.util.ArrayList;
021    import java.util.Collections;
022    import java.util.List;
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.commons.lang.time.DateUtils;
029    import org.apache.struts.action.ActionForm;
030    import org.apache.struts.action.ActionForward;
031    import org.apache.struts.action.ActionMapping;
032    import org.displaytag.tags.TableTagParameters;
033    import org.displaytag.util.ParamEncoder;
034    import org.kuali.hr.core.document.calendar.CalendarDocumentContract;
035    import org.kuali.hr.time.assignment.Assignment;
036    import org.kuali.hr.time.calendar.Calendar;
037    import org.kuali.hr.time.calendar.CalendarEntries;
038    import org.kuali.hr.time.roles.UserRoles;
039    import org.kuali.hr.time.service.base.TkServiceLocator;
040    import org.kuali.hr.time.util.TKContext;
041    import org.kuali.hr.time.util.TKUser;
042    import org.kuali.hr.time.util.TKUtils;
043    import org.kuali.hr.time.util.TkConstants;
044    import org.kuali.hr.time.workarea.WorkArea;
045    import org.kuali.rice.krad.exception.AuthorizationException;
046    import org.kuali.rice.krad.util.GlobalVariables;
047    
048    public class ApprovalAction extends TkAction{
049    
050            @Override
051        public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
052            if (form instanceof TkForm) {
053               String methodToCall = ((TkForm)form).getMethodToCall();
054               if(StringUtils.isEmpty(methodToCall)) {
055                       super.execute(mapping, form, request, response);
056                       return loadApprovalTab(mapping, form, request, response); 
057               }
058            }
059            return super.execute(mapping, form, request, response);
060        }
061            
062            public ActionForward loadApprovalTab(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
063                    return mapping.findForward("basic");
064            }
065            
066            protected List<String> getSubListPrincipalIds(HttpServletRequest request, List<String> assignmentPrincipalIds) {
067                String page = request.getParameter((new ParamEncoder(TkConstants.APPROVAL_TABLE_ID).encodeParameterName(TableTagParameters.PARAMETER_PAGE)));
068                // The paging index begins from 1, but the sublist index begins from 0.
069                // So the logic below sets the sublist begin index to 0 if the page number is null or equals 1
070                Integer beginIndex = StringUtils.isBlank(page) || StringUtils.equals(page, "1") ? 0 : (Integer.parseInt(page) - 1)*TkConstants.PAGE_SIZE;
071                Integer endIndex = beginIndex + TkConstants.PAGE_SIZE > assignmentPrincipalIds.size() ? assignmentPrincipalIds.size() : beginIndex + TkConstants.PAGE_SIZE;
072    
073                return assignmentPrincipalIds.subList(beginIndex, endIndex);
074            }
075    
076    
077    
078    
079    
080            protected Boolean isAscending(HttpServletRequest request, ApprovalForm form) {
081    
082                // returned value 1 = ascending; 2 = descending
083                String ascending = request.getParameter((new ParamEncoder(TkConstants.APPROVAL_TABLE_ID).encodeParameterName(TableTagParameters.PARAMETER_ORDER)));
084                if (StringUtils.isEmpty(ascending)) {
085                ascending = form.isAscending() ? "1" : "2";
086            } else {
087                form.setAscending(StringUtils.equals(ascending, "1"));
088            }
089            return StringUtils.isEmpty(ascending) || StringUtils.equals(ascending, "1") ? true : false;
090            }
091    
092            protected String getSortField(HttpServletRequest request, ApprovalForm form) {
093                String sortField = request.getParameter((new ParamEncoder(TkConstants.APPROVAL_TABLE_ID).encodeParameterName(TableTagParameters.PARAMETER_SORT)));
094            if (StringUtils.isEmpty(sortField)) {
095                sortField = form.getSortField();
096            } else {
097                form.setSortField(sortField);
098            }
099            return sortField;
100            }
101    
102        protected String getPage(HttpServletRequest request, ApprovalForm form) {
103            String page = new ParamEncoder(TkConstants.APPROVAL_TABLE_ID).encodeParameterName(TableTagParameters.PARAMETER_PAGE);
104            String pageVal = request.getParameter(page);
105            if (StringUtils.isNotEmpty(pageVal)) {
106                form.setPageId(page + "=" + pageVal);
107            } else {
108                form.setPageId(StringUtils.EMPTY);
109            }
110            return pageVal;
111        }
112            
113            protected void checkTKAuthorization(ActionForm form, String methodToCall)
114                            throws AuthorizationException {
115                                if (!TKUser.isTimesheetReviewer() && !TKUser.isAnyApproverActive() && !TKUser.isSystemAdmin()
116                                            && !TKUser.isLocationAdmin() && !TKUser.isGlobalViewOnly() && !TKUser.isDeptViewOnly()
117                                            && !TKUser.isDepartmentAdmin()) {
118                                    throw new AuthorizationException(GlobalVariables.getUserSession().getPrincipalId(), "ApprovalAction", "");
119                                }
120                            }
121            
122            protected void resetMainFields(ActionForm form) {
123                    ApprovalForm taf = (ApprovalForm) form;
124                    taf.setSearchField(null);
125                    taf.setSearchTerm(null);
126                    taf.setSelectedWorkArea(null);
127                    taf.setSelectedDept(null);
128                    taf.setPayBeginDate(null);
129                    taf.setPayEndDate(null);
130                    taf.setHrPyCalendarEntriesId(null);
131            }
132            
133            protected void setupDocumentOnFormContext(HttpServletRequest request,
134                            ApprovalForm taf, CalendarEntries payCalendarEntries, String page, CalendarDocumentContract calDoc) {
135                    if(payCalendarEntries == null) {
136                            return;
137                    }
138                    taf.setHrPyCalendarId(payCalendarEntries.getHrCalendarId());
139                    taf.setHrPyCalendarEntriesId(payCalendarEntries.getHrCalendarEntriesId());
140                    taf.setPayBeginDate(payCalendarEntries.getBeginPeriodDateTime());
141            taf.setPayEndDate(payCalendarEntries.getEndPeriodDateTime());
142                    //taf.setPayEndDate(DateUtils.addMilliseconds(payCalendarEntries.getEndPeriodDateTime(),-1));
143                    
144                    CalendarEntries prevPayCalendarEntries = TkServiceLocator.getCalendarEntriesService().getPreviousCalendarEntriesByCalendarId(taf.getHrPyCalendarId(), payCalendarEntries);
145                    if (prevPayCalendarEntries != null) {
146                        taf.setPrevPayCalendarId(prevPayCalendarEntries.getHrCalendarEntriesId());
147                    } else {
148                        taf.setPrevPayCalendarId(null);
149                    }
150                    
151                    CalendarEntries nextPayCalendarEntries = TkServiceLocator.getCalendarEntriesService().getNextCalendarEntriesByCalendarId(taf.getHrPyCalendarId(), payCalendarEntries);
152                    if (nextPayCalendarEntries != null) {
153                        taf.setNextPayCalendarId(nextPayCalendarEntries.getHrCalendarEntriesId());
154                    } else {
155                        taf.setNextPayCalendarId(null);
156                    }       
157                    if (StringUtils.isBlank(page)) {
158                        List<String> depts = new ArrayList<String>(TKUser.getReportingApprovalDepartments().keySet());
159                        if ( depts.isEmpty() ) {
160                            return;
161                        }
162                        Collections.sort(depts);
163                        taf.setDepartments(depts);
164    
165                if (calDoc != null) {
166                    for (Assignment a : calDoc.getAssignments()) {
167                        WorkArea wa = TkServiceLocator.getWorkAreaService().getWorkArea(a.getWorkArea(), a.getEffectiveDate());
168                        if (taf.getDepartments().contains(wa.getDept())) {
169                            taf.setSelectedDept(wa.getDept());
170                            break;
171                        }
172                    }
173                }
174    
175                        if (taf.getDepartments().size() == 1 || taf.getSelectedDept() != null) {
176                            if (StringUtils.isEmpty(taf.getSelectedDept())) {
177                                    taf.setSelectedDept(taf.getDepartments().get(0));
178                    }
179                            
180                            List<WorkArea> workAreas = TkServiceLocator.getWorkAreaService().getWorkAreas(taf.getSelectedDept(), new java.sql.Date(taf.getPayBeginDate().getTime()));
181                    UserRoles ur = TKUser.getCurrentTargetRoles();
182                    for(WorkArea wa : workAreas){
183                                    if (ur.getApproverWorkAreas().contains(wa.getWorkArea())
184                                                    || ur.getReviewerWorkAreas().contains(wa.getWorkArea())) {
185                                            taf.getWorkAreaDescr().put(wa.getWorkArea(),wa.getDescription()+"("+wa.getWorkArea()+")");
186                                    }
187                            }
188                        }
189                    }
190    
191            }
192            
193        public ActionForward gotoCurrentPayPeriod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
194            
195    
196            ApprovalForm taf = (ApprovalForm) form;
197            String page = getPage(request, taf);
198            Date currentDate = TKUtils.getTimelessDate(null);
199            Calendar currentPayCalendar = TkServiceLocator.getCalendarService().getCalendarByGroup(taf.getSelectedPayCalendarGroup());
200            CalendarEntries payCalendarEntries = TkServiceLocator.getCalendarEntriesService().getCurrentCalendarEntriesByCalendarId(currentPayCalendar.getHrCalendarId(), currentDate);
201            taf.setPayCalendarEntries(payCalendarEntries);
202            taf.setSelectedCalendarYear(new SimpleDateFormat("yyyy").format(payCalendarEntries.getBeginPeriodDate()));
203            taf.setSelectedPayPeriod(payCalendarEntries.getHrCalendarEntriesId());
204            populateCalendarAndPayPeriodLists(request, taf);
205            setupDocumentOnFormContext(request, taf, payCalendarEntries, page, null);
206            return mapping.findForward("basic");
207        }
208        
209       
210        
211        // Triggered by changes of calendar year drop down list, reloads the pay period list
212        public ActionForward changeCalendarYear(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
213            ApprovalForm taf = (ApprovalForm) form;
214            if(!StringUtils.isEmpty(request.getParameter("selectedCY"))) {
215                    taf.setSelectedCalendarYear(request.getParameter("selectedCY").toString());
216                    populateCalendarAndPayPeriodLists(request, taf);
217            }
218            return mapping.findForward("basic");
219        }
220    
221        // Triggered by changes of pay period drop down list, reloads the whole page based on the selected pay period
222        public ActionForward changePayPeriod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
223          ApprovalForm taf = (ApprovalForm) form;
224          String page = getPage(request, taf);
225              if(!StringUtils.isEmpty(request.getParameter("selectedPP"))) {
226                      taf.setSelectedPayPeriod(request.getParameter("selectedPP").toString());
227                      CalendarEntries pce = TkServiceLocator.getCalendarEntriesService()
228                            .getCalendarEntries(request.getParameter("selectedPP").toString());
229                      if(pce != null) {
230                              taf.setPayCalendarEntries(pce);
231                              setupDocumentOnFormContext(request, taf, pce, page, null);
232                      }
233              }
234              return mapping.findForward("basic");
235            }
236        // sets the CalendarYear and Pay Period lists. Should be overridden by subclasses
237        protected void populateCalendarAndPayPeriodLists(HttpServletRequest request, ApprovalForm taf) {
238            
239        }
240    
241    
242    }