View Javadoc

1   /**
2    * Copyright 2004-2012 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.hr.time.detail.web;
17  
18  import java.sql.Date;
19  import java.text.SimpleDateFormat;
20  import java.util.ArrayList;
21  import java.util.Collections;
22  import java.util.HashMap;
23  import java.util.HashSet;
24  import java.util.LinkedHashMap;
25  import java.util.LinkedList;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.Set;
29  
30  import org.apache.commons.collections.CollectionUtils;
31  import org.apache.commons.lang.StringUtils;
32  import org.joda.time.DateTime;
33  import org.joda.time.format.ISODateTimeFormat;
34  import org.json.simple.JSONValue;
35  import org.kuali.hr.time.accrual.AccrualCategory;
36  import org.kuali.hr.time.assignment.AssignmentDescriptionKey;
37  import org.kuali.hr.time.calendar.CalendarEntries;
38  import org.kuali.hr.time.earncode.EarnCode;
39  import org.kuali.hr.time.roles.TkUserRoles;
40  import org.kuali.hr.time.service.base.TkServiceLocator;
41  import org.kuali.hr.time.timeblock.TimeBlock;
42  import org.kuali.hr.time.timeblock.TimeHourDetail;
43  import org.kuali.hr.time.util.TKUser;
44  import org.kuali.hr.time.util.TKUtils;
45  import org.kuali.hr.time.util.TkConstants;
46  import org.kuali.hr.time.workarea.WorkArea;
47  import org.kuali.rice.krad.util.GlobalVariables;
48  
49  public class ActionFormUtils {
50  
51      public static void validateHourLimit(TimeDetailActionFormBase tdaf) throws Exception {
52          List<String> warningMessages = TkServiceLocator.getTimeOffAccrualService().validateAccrualHoursLimit(tdaf.getTimesheetDocument());
53          addUniqueWarningsToForm(tdaf, warningMessages);
54      }
55  
56      public static void addWarningTextFromEarnGroup(TimeDetailActionFormBase tdaf) throws Exception {
57          List<String> warningMessages = TkServiceLocator.getEarnGroupService().warningTextFromEarnGroupsOfDocument(tdaf.getTimesheetDocument());
58          addUniqueWarningsToForm(tdaf, warningMessages);
59      }
60  
61      public static void addUniqueWarningsToForm(TimeDetailActionFormBase tdaf, List<String> warningMessages) {
62          if (!warningMessages.isEmpty()) {
63              Set<String> aSet = new HashSet<String>();
64              aSet.addAll(warningMessages);
65              aSet.addAll(tdaf.getWarnings());
66              List<String> aList = new ArrayList<String>();
67              aList.addAll(aSet);
68              tdaf.setWarnings(aList);
69          }
70      }
71  
72  //    public static String getTimeBlockJSONMap(List<TimeBlock> blocks) {
73  //        List<Map<String, Object>> jsonList = getTimeBlocksJson(blocks, null);
74  //        Map<String, Map<String, Object>> jsonMappedList = new HashMap<String, Map<String, Object>>();
75  //        for (Map<String, Object> tbm : jsonList) {
76  //            String id = (String) tbm.get("id");
77  //            jsonMappedList.put(id, tbm);
78  //        }
79  //        return JSONValue.toJSONString(jsonMappedList);
80  //    }
81  
82      public static Map<String, String> buildAssignmentStyleClassMap(List<TimeBlock> timeBlocks) {
83          Map<String, String> aMap = new HashMap<String, String>();
84          List<String> assignmentKeys = new ArrayList<String>();
85  
86          for (TimeBlock tb : timeBlocks) {
87              if (!assignmentKeys.contains(tb.getAssignmentKey())) {
88                  assignmentKeys.add(tb.getAssignmentKey());
89              }
90          }
91  
92          Collections.sort(assignmentKeys);
93  
94          for (int i = 0; i < assignmentKeys.size(); i++) {
95              // pick a color from a five color palette
96              aMap.put(assignmentKeys.get(i), "assignment" + Integer.toString(i % 5));
97          }
98  
99          return aMap;
100     }
101 
102     /**
103      * This method will build the JSON data structure needed for calendar
104      * manipulation and processing on the client side. Start and End times here
105      * are based on the pre-timezone adjusted times startDisplayTime, and
106      * endDisplayTime.
107      *
108      * @param timeBlocks
109      * @return
110      */
111     public static String getTimeBlocksJson(List<TimeBlock> timeBlocks) {
112 
113         if (timeBlocks == null || timeBlocks.size() == 0) {
114             return "";
115         }
116 
117         List<Map<String, Object>> timeBlockList = new LinkedList<Map<String, Object>>();
118         String timezone = TkServiceLocator.getTimezoneService().getUserTimezone();
119 
120         for (TimeBlock timeBlock : timeBlocks) {
121             Map<String, Object> timeBlockMap = new LinkedHashMap<String, Object>();
122 
123             WorkArea workArea = TkServiceLocator.getWorkAreaService().getWorkArea(timeBlock.getWorkArea(), new java.sql.Date(timeBlock.getEndTimestamp().getTime()));
124             String workAreaDesc = workArea.getDescription();
125 
126             // Roles
127             Boolean isAnyApprover = TkUserRoles.getUserRoles(GlobalVariables.getUserSession().getPrincipalId()).isAnyApproverActive();
128             timeBlockMap.put("isApprover", isAnyApprover);
129             timeBlockMap.put("isSynchronousUser", timeBlock.getClockLogCreated());
130 
131             // Permissions
132             timeBlockMap.put("canEditTb", TkServiceLocator.getPermissionsService().canEditTimeBlock(timeBlock));
133             timeBlockMap.put("canEditTBOvt", TkServiceLocator.getPermissionsService().canEditOvertimeEarnCode(timeBlock));
134             timeBlockMap.put("canAddTB", TkServiceLocator.getPermissionsService().canAddTimeBlock());
135 
136             if (TkServiceLocator.getPermissionsService().canEditTimeBlockAllFields(timeBlock)) {
137                 timeBlockMap.put("canEditTBAll", true);
138                 timeBlockMap.put("canEditTBAssgOnly", false);
139             } else {
140                 timeBlockMap.put("canEditTBAll", false);
141                 timeBlockMap.put("canEditTBAssgOnly", true);
142             }
143 
144             //    tracking any kind of 'mutating' state with this object, it's just a one off modification under a specific circumstance.
145             DateTime start = timeBlock.getBeginTimeDisplay();
146             DateTime end = timeBlock.getEndTimeDisplay();
147 
148             /**
149              * This is the timeblock backward pushing logic.
150              * the purpose of this is to accommodate the virtual day mode where the start/end period time is not from 12a to 12a.
151              * A timeblock will be pushed back if the timeblock is still within the previous interval
152              */
153             if (timeBlock.isPushBackward()) {
154                 start = start.minusDays(1);
155                 end = end.minusDays(1);
156             }
157 
158             timeBlockMap.put("documentId", timeBlock.getDocumentId());
159             timeBlockMap.put("title", workAreaDesc);
160             timeBlockMap.put("earnCode", timeBlock.getEarnCode());
161             timeBlockMap.put("earnCodeDesc", TkServiceLocator.getEarnCodeService().getEarnCode(timeBlock.getEarnCode(), TKUtils.getCurrentDate()).getDescription());
162             //TODO: need to cache this or pre-load it when the app boots up
163             // EarnCode earnCode = TkServiceLocator.getEarnCodeService().getEarnCode(timeBlock.getEarnCode(), new java.sql.Date(timeBlock.getBeginTimestamp().getTime()));
164             timeBlockMap.put("earnCodeType", timeBlock.getEarnCodeType());
165 
166             // TODO: Cleanup the start / end time related properties. We certainly don't need all of them.
167             // The ones which are used by the javascript are startDate, endDate, startTime, endTime, startTimeHourMinute, and endTimeHourMinute
168             timeBlockMap.put("start", start.toString(ISODateTimeFormat.dateTimeNoMillis()));
169             timeBlockMap.put("end", end.toString(ISODateTimeFormat.dateTimeNoMillis()));
170             timeBlockMap.put("startDate", start.toString(TkConstants.DT_BASIC_DATE_FORMAT));
171             timeBlockMap.put("endDate", end.toString(TkConstants.DT_BASIC_DATE_FORMAT));
172             timeBlockMap.put("startNoTz", start.toString(ISODateTimeFormat.dateHourMinuteSecond()));
173             timeBlockMap.put("endNoTz", end.toString(ISODateTimeFormat.dateHourMinuteSecond()));
174             // start / endTimeHourMinute fields are for only for the display purpose
175             timeBlockMap.put("startTimeHourMinute", start.toString(TkConstants.DT_BASIC_TIME_FORMAT));
176             timeBlockMap.put("endTimeHourMinute", end.toString(TkConstants.DT_BASIC_TIME_FORMAT));
177             // start / endTime are the actual fields used by the adding / editing timeblocks
178             timeBlockMap.put("startTime", start.toString(TkConstants.DT_MILITARY_TIME_FORMAT));
179             timeBlockMap.put("endTime", end.toString(TkConstants.DT_MILITARY_TIME_FORMAT));
180             timeBlockMap.put("id", timeBlock.getTkTimeBlockId() == null ? null : timeBlock.getTkTimeBlockId().toString());
181             timeBlockMap.put("hours", timeBlock.getHours());
182             timeBlockMap.put("amount", timeBlock.getAmount());
183             timeBlockMap.put("timezone", timezone);
184             timeBlockMap.put("assignment", new AssignmentDescriptionKey(timeBlock.getJobNumber(), timeBlock.getWorkArea(), timeBlock.getTask()).toAssignmentKeyString());
185             timeBlockMap.put("tkTimeBlockId", timeBlock.getTkTimeBlockId() != null ? timeBlock.getTkTimeBlockId() : "");
186             timeBlockMap.put("lunchDeleted", timeBlock.isLunchDeleted());
187 
188             List<Map<String, Object>> timeHourDetailList = new LinkedList<Map<String, Object>>();
189             for (TimeHourDetail timeHourDetail : timeBlock.getTimeHourDetails()) {
190                 Map<String, Object> timeHourDetailMap = new LinkedHashMap<String, Object>();
191                 timeHourDetailMap.put("earnCode", timeHourDetail.getEarnCode());
192                 timeHourDetailMap.put("hours", timeHourDetail.getHours());
193                 timeHourDetailMap.put("amount", timeHourDetail.getAmount());
194 
195                 // if there is a lunch hour deduction, add a flag to the timeBlockMap
196                 if (StringUtils.equals(timeHourDetail.getEarnCode(), "LUN")) {
197                     timeBlockMap.put("lunchDeduction", true);
198                 }
199 
200                 timeHourDetailList.add(timeHourDetailMap);
201             }
202             timeBlockMap.put("timeHourDetails", JSONValue.toJSONString(timeHourDetailList));
203 
204             timeBlockList.add(timeBlockMap);
205         }
206 
207 //        Map<String, Map<String, Object>> jsonMappedList = new HashMap<String, Map<String, Object>>();
208 //        for (Map<String, Object> tbm : timeBlockList) {
209 //            String id = (String) tbm.get("id");
210 //            jsonMappedList.put(id, tbm);
211 //        }
212         return JSONValue.toJSONString(timeBlockList);
213     }
214 
215     public static Map<String, String> getPayPeriodsMap(List<CalendarEntries> payPeriods) {
216     	// use linked map to keep the order of the pay periods
217     	Map<String, String> pMap = Collections.synchronizedMap(new LinkedHashMap<String, String>());
218     	if (payPeriods == null || payPeriods.isEmpty()) {
219             return pMap;
220         }
221     	payPeriods.removeAll(Collections.singletonList(null));
222     	Collections.sort(payPeriods);  // sort the pay period list by getBeginPeriodDate
223     	Collections.reverse(payPeriods); 	// newest on top
224     	SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
225         for (CalendarEntries pce : payPeriods) {
226         	if(pce != null && pce.getHrCalendarEntriesId()!= null && pce.getBeginPeriodDate() != null && pce.getEndPeriodDate() != null) {
227         		pMap.put(pce.getHrCalendarEntriesId(), sdf.format(pce.getBeginPeriodDate()) + " - " + sdf.format(pce.getEndPeriodDate()));
228         	}
229         }
230         
231     	return pMap;
232     }
233     
234     // detect if the passed-in calendar entry is the current one
235     public static boolean getOnCurrentPeriodFlag(CalendarEntries pce) {
236     	Date currentDate = TKUtils.getTimelessDate(null);
237     	String viewPrincipal = TKUser.getCurrentTargetPerson().getPrincipalId();
238         CalendarEntries calendarEntry = TkServiceLocator.getCalendarService().getCurrentCalendarDates(viewPrincipal,  currentDate);
239 
240         if(pce != null && calendarEntry != null && calendarEntry.equals(pce)) {
241     		return true;
242     	}
243     	return false;
244     }
245     
246     public static String getUnitOfTimeForEarnCode(EarnCode earnCode) {
247     	AccrualCategory acObj = null;
248     	if(earnCode.getAccrualCategory() != null) {
249     		acObj = TkServiceLocator.getAccrualCategoryService().getAccrualCategory(earnCode.getAccrualCategory(), TKUtils.getCurrentDate());
250     	}
251     	String unitTime = (acObj!= null ? acObj.getUnitOfTime() : earnCode.getRecordMethod()) ;
252     	return unitTime;
253     }
254     
255 }
256