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(DateUtils.addMilliseconds(payCalendarEntries.getEndPeriodDateTime(),-1));
142                    
143                    CalendarEntries prevPayCalendarEntries = TkServiceLocator.getCalendarEntriesService().getPreviousCalendarEntriesByCalendarId(taf.getHrPyCalendarId(), payCalendarEntries);
144                    if (prevPayCalendarEntries != null) {
145                        taf.setPrevPayCalendarId(prevPayCalendarEntries.getHrCalendarEntriesId());
146                    } else {
147                        taf.setPrevPayCalendarId(null);
148                    }
149                    
150                    CalendarEntries nextPayCalendarEntries = TkServiceLocator.getCalendarEntriesService().getNextCalendarEntriesByCalendarId(taf.getHrPyCalendarId(), payCalendarEntries);
151                    if (nextPayCalendarEntries != null) {
152                        taf.setNextPayCalendarId(nextPayCalendarEntries.getHrCalendarEntriesId());
153                    } else {
154                        taf.setNextPayCalendarId(null);
155                    }       
156                    if (StringUtils.isBlank(page)) {
157                        List<String> depts = new ArrayList<String>(TKUser.getReportingApprovalDepartments().keySet());
158                        if ( depts.isEmpty() ) {
159                            return;
160                        }
161                        Collections.sort(depts);
162                        taf.setDepartments(depts);
163    
164                if (calDoc != null) {
165                    for (Assignment a : calDoc.getAssignments()) {
166                        WorkArea wa = TkServiceLocator.getWorkAreaService().getWorkArea(a.getWorkArea(), a.getEffectiveDate());
167                        if (taf.getDepartments().contains(wa.getDept())) {
168                            taf.setSelectedDept(wa.getDept());
169                            break;
170                        }
171                    }
172                }
173    
174                        if (taf.getDepartments().size() == 1 || taf.getSelectedDept() != null) {
175                            if (StringUtils.isEmpty(taf.getSelectedDept())) {
176                                    taf.setSelectedDept(taf.getDepartments().get(0));
177                    }
178                            
179                            List<WorkArea> workAreas = TkServiceLocator.getWorkAreaService().getWorkAreas(taf.getSelectedDept(), new java.sql.Date(taf.getPayBeginDate().getTime()));
180                    UserRoles ur = TKUser.getCurrentTargetRoles();
181                    for(WorkArea wa : workAreas){
182                                    if (ur.getApproverWorkAreas().contains(wa.getWorkArea())
183                                                    || ur.getReviewerWorkAreas().contains(wa.getWorkArea())) {
184                                            taf.getWorkAreaDescr().put(wa.getWorkArea(),wa.getDescription()+"("+wa.getWorkArea()+")");
185                                    }
186                            }
187                        }
188                    }
189    
190            }
191            
192        public ActionForward gotoCurrentPayPeriod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
193            
194    
195            ApprovalForm taf = (ApprovalForm) form;
196            String page = getPage(request, taf);
197            Date currentDate = TKUtils.getTimelessDate(null);
198            Calendar currentPayCalendar = TkServiceLocator.getCalendarService().getCalendarByGroup(taf.getSelectedPayCalendarGroup());
199            CalendarEntries payCalendarEntries = TkServiceLocator.getCalendarEntriesService().getCurrentCalendarEntriesByCalendarId(currentPayCalendar.getHrCalendarId(), currentDate);
200            taf.setPayCalendarEntries(payCalendarEntries);
201            taf.setSelectedCalendarYear(new SimpleDateFormat("yyyy").format(payCalendarEntries.getBeginPeriodDate()));
202            taf.setSelectedPayPeriod(payCalendarEntries.getHrCalendarEntriesId());
203            populateCalendarAndPayPeriodLists(request, taf);
204            setupDocumentOnFormContext(request, taf, payCalendarEntries, page, null);
205            return mapping.findForward("basic");
206        }
207        
208       
209        
210        // Triggered by changes of calendar year drop down list, reloads the pay period list
211        public ActionForward changeCalendarYear(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
212            ApprovalForm taf = (ApprovalForm) form;
213            if(!StringUtils.isEmpty(request.getParameter("selectedCY"))) {
214                    taf.setSelectedCalendarYear(request.getParameter("selectedCY").toString());
215                    populateCalendarAndPayPeriodLists(request, taf);
216            }
217            return mapping.findForward("basic");
218        }
219    
220        // Triggered by changes of pay period drop down list, reloads the whole page based on the selected pay period
221        public ActionForward changePayPeriod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
222          ApprovalForm taf = (ApprovalForm) form;
223          String page = getPage(request, taf);
224              if(!StringUtils.isEmpty(request.getParameter("selectedPP"))) {
225                      taf.setSelectedPayPeriod(request.getParameter("selectedPP").toString());
226                      CalendarEntries pce = TkServiceLocator.getCalendarEntriesService()
227                            .getCalendarEntries(request.getParameter("selectedPP").toString());
228                      if(pce != null) {
229                              taf.setPayCalendarEntries(pce);
230                              setupDocumentOnFormContext(request, taf, pce, page, null);
231                      }
232              }
233              return mapping.findForward("basic");
234            }
235        // sets the CalendarYear and Pay Period lists. Should be overridden by subclasses
236        protected void populateCalendarAndPayPeriodLists(HttpServletRequest request, ApprovalForm taf) {
237            
238        }
239    
240    
241    }