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