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.core.assignment.service;
17  
18  import org.apache.commons.collections.CollectionUtils;
19  import org.apache.commons.collections.MapUtils;
20  import org.apache.commons.lang.StringUtils;
21  import org.apache.log4j.Logger;
22  import org.joda.time.DateTime;
23  import org.joda.time.Days;
24  import org.joda.time.DurationFieldType;
25  import org.joda.time.LocalDate;
26  import org.kuali.kpme.core.api.assignment.Assignment;
27  import org.kuali.kpme.core.api.assignment.AssignmentDescriptionKey;
28  import org.kuali.kpme.core.api.assignment.service.AssignmentService;
29  import org.kuali.kpme.core.api.calendar.entry.CalendarEntry;
30  import org.kuali.kpme.core.api.job.JobContract;
31  import org.kuali.kpme.core.api.namespace.KPMENamespace;
32  import org.kuali.kpme.core.api.task.TaskContract;
33  import org.kuali.kpme.core.api.util.KpmeUtils;
34  import org.kuali.kpme.core.api.workarea.WorkArea;
35  import org.kuali.kpme.core.assignment.AssignmentBo;
36  import org.kuali.kpme.core.assignment.dao.AssignmentDao;
37  import org.kuali.kpme.core.job.JobBo;
38  import org.kuali.kpme.core.role.KPMERole;
39  import org.kuali.kpme.core.service.HrServiceLocator;
40  import org.kuali.kpme.core.task.TaskBo;
41  import org.kuali.kpme.core.util.HrConstants;
42  import org.kuali.kpme.core.util.TKUtils;
43  import org.kuali.kpme.core.workarea.WorkAreaBo;
44  import org.kuali.rice.core.api.config.property.ConfigContext;
45  import org.kuali.rice.core.api.mo.ModelObjectUtils;
46  import org.kuali.rice.core.api.util.type.KualiDecimal;
47  import org.kuali.rice.kim.api.role.RoleService;
48  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
49  
50  import java.util.*;
51  
52  public class AssignmentServiceImpl implements AssignmentService {
53  
54      private static final Logger LOG = Logger.getLogger(AssignmentServiceImpl.class);
55      private AssignmentDao assignmentDao;
56  
57      public void setAssignmentDao(AssignmentDao assignmentDao) {
58          this.assignmentDao = assignmentDao;
59      }
60  
61      protected List<Assignment> convertToImmutable(List<AssignmentBo> bos) {
62          return ModelObjectUtils.transform(bos, AssignmentBo.toAssignment);
63      }
64  
65  
66      @Override
67      public List<Assignment> getAssignments(String principalId, LocalDate asOfDate) {
68          List<Assignment> assigns = new ArrayList<Assignment>();
69          if (asOfDate == null) {
70              asOfDate = LocalDate.now();
71          }
72  
73          List<AssignmentBo> assignments = assignmentDao.findAssignments(principalId, asOfDate);
74  
75          for (AssignmentBo assignment : assignments) {
76              assigns.add(AssignmentBo.to(populateAssignment(assignment, asOfDate)));
77          }
78  
79          return assigns;
80      }
81  
82      //@Override
83      public List<Assignment> getAssignments(String principalId, LocalDate beginDate, LocalDate endDate) {
84          List<AssignmentBo> assignments = assignmentDao.findAssignmentsWithinPeriod(principalId, beginDate, endDate);
85          List<Assignment> assigns = new ArrayList<Assignment>();
86          for (AssignmentBo assignment : assignments) {
87              assigns.add(AssignmentBo.to(populateAssignment(assignment, assignment.getEffectiveLocalDate())));
88          }
89  
90          return assigns;
91      }
92  /*
93      @Override
94      public List<Assignment> filterLookupAssignments(List<Assignment> rawResults, String userPrincipalId) {
95          List<Assignment> results = new ArrayList<Assignment>();
96          for (Assignment assignmentObj : rawResults) {
97  
98              String department = assignmentObj.getDept();
99              String groupKeyCode = assignmentObj.getGroupKeyCode();
100             Department departmentObj = HrServiceLocator.getDepartmentService().getDepartment(department, groupKeyCode, assignmentObj.getEffectiveLocalDate());
101             String location = departmentObj != null ? departmentObj.getGroupKey().getLocationId() : null;
102 
103             Map<String, String> roleQualification = new HashMap<String, String>();
104 
105             roleQualification.put(KimConstants.AttributeConstants.PRINCIPAL_ID, userPrincipalId);
106             roleQualification.put(KPMERoleMemberAttribute.DEPARTMENT.getRoleMemberAttributeName(), department);
107             roleQualification.put(KPMERoleMemberAttribute.LOCATION.getRoleMemberAttributeName(), location);
108 
109             if (!KimApiServiceLocator.getPermissionService().isPermissionDefinedByTemplate(KPMENamespace.KPME_WKFLW.getNamespaceCode(),
110                     KPMEPermissionTemplate.VIEW_KPME_RECORD.getPermissionTemplateName(), new HashMap<String, String>())
111                     || KimApiServiceLocator.getPermissionService().isAuthorizedByTemplate(userPrincipalId, KPMENamespace.KPME_WKFLW.getNamespaceCode(),
112                     KPMEPermissionTemplate.VIEW_KPME_RECORD.getPermissionTemplateName(), new HashMap<String, String>(), roleQualification)) {
113                 results.add(assignmentObj);
114             }
115         }
116 
117         return results;
118     }
119 */
120     public List<Assignment> getAssignmentsByPayEntry(String principalId, CalendarEntry payCalendarEntry) {
121     	DateTime entryEndDate = payCalendarEntry.getEndPeriodLocalDateTime().toDateTime();
122         if (entryEndDate.getHourOfDay() == 0) {
123             entryEndDate = entryEndDate.minusDays(1);
124         }
125         List<Assignment> beginPeriodAssign = getAssignments(principalId, payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate());
126         List<Assignment> endPeriodAssign = getAssignments(principalId, entryEndDate.toLocalDate());
127         List<Assignment> assignsWithPeriod = getAssignments(principalId, payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate(), entryEndDate.toLocalDate());
128 
129         List<Assignment> finalAssignments = new ArrayList<Assignment>();
130         Map<String, Assignment> assignKeyToAssignmentMap = new HashMap<String, Assignment>();
131         for (Assignment assign : endPeriodAssign) {
132             assignKeyToAssignmentMap.put(AssignmentDescriptionKey.getAssignmentKeyString(assign), assign);
133             finalAssignments.add(assign);
134         }
135 
136         //Compare the begin and end and add any assignments to the end thats are not there
137         for (Assignment assign : beginPeriodAssign) {
138             String assignKey = AssignmentDescriptionKey.getAssignmentKeyString(assign);
139             if (!assignKeyToAssignmentMap.containsKey(assignKey)) {
140                 finalAssignments.add(assign);
141             }
142         }
143 
144         // Add the assignments within the pay period
145         for (Assignment assign : assignsWithPeriod) {
146             String assignKey = AssignmentDescriptionKey.getAssignmentKeyString(assign);
147             if (!assignKeyToAssignmentMap.containsKey(assignKey)) {
148                 finalAssignments.add(assign);
149             }
150         }
151 
152         return finalAssignments;
153 
154     }
155 
156     public Map<LocalDate, List<Assignment>> getAssignmentsByCalEntryForTimeCalendar(String principalId, CalendarEntry payCalendarEntry){
157         if (StringUtils.isEmpty(principalId)
158                 || payCalendarEntry == null) {
159             return Collections.emptyMap();
160         }
161 
162         return getAssignmentHistoryBetweenDaysInternal(principalId, payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate(), payCalendarEntry.getEndPeriodFullDateTime().toLocalDate(), HrConstants.FLSA_STATUS_NON_EXEMPT, false);
163     }
164 
165     public List<Assignment> getAllAssignmentsByCalEntryForTimeCalendar(String principalId, CalendarEntry payCalendarEntry){
166         Map<LocalDate, List<Assignment>> history = getAssignmentsByCalEntryForTimeCalendar(principalId, payCalendarEntry);
167         return KpmeUtils.getUniqueAssignments(history);
168     }
169     
170     public Map<LocalDate, List<Assignment>> getAssignmentsByCalEntryForLeaveCalendar(String principalId, CalendarEntry payCalendarEntry){
171         if (StringUtils.isEmpty(principalId)
172                 || payCalendarEntry == null) {
173             return Collections.emptyMap();
174         }
175         return getAssignmentHistoryBetweenDaysInternal(principalId, payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate(), payCalendarEntry.getEndPeriodFullDateTime().toLocalDate(), null, true);
176     }
177 
178     public List<Assignment> getAllAssignmentsByCalEntryForLeaveCalendar(String principalId, CalendarEntry payCalendarEntry){
179         Map<LocalDate, List<Assignment>> history = getAssignmentsByCalEntryForLeaveCalendar(principalId, payCalendarEntry);
180         return KpmeUtils.getUniqueAssignments(history);
181     }
182 
183     public List<Assignment> filterAssignments(List<Assignment> assignments, String flsaStatus, boolean chkForLeaveEligible) {
184     	List<Assignment> results = new ArrayList<Assignment>();
185     	for(Assignment assignment : assignments) {
186     		boolean flag = false;
187     		if(StringUtils.isNotEmpty(flsaStatus)) {
188     			if(assignment != null 
189 		    			&& assignment.getJob() != null 
190 		    			&& assignment.getJob().getFlsaStatus() != null 
191 		    			&& assignment.getJob().getFlsaStatus().equalsIgnoreCase(flsaStatus)) {    			
192 					if(chkForLeaveEligible) {
193 						if(assignment.getJob().isEligibleForLeave()) {
194 							flag = true;
195 						}
196 					}else {
197 						flag = true;
198 					}
199 	    		} 
200     		}else {
201     			if(chkForLeaveEligible) {
202     				if(assignment != null && assignment.getJob() != null && assignment.getJob().isEligibleForLeave()) {
203     					flag = true;
204     				}
205     			} else {
206     				flag = true;
207     			}
208     		}
209     		
210 			if(flag) {
211 				results.add(assignment);
212 			}
213     	}
214     	
215     	return results;
216     	
217     }
218     
219     @Override
220     public AssignmentDescriptionKey getAssignmentDescriptionKey(String assignmentKey) {
221         return AssignmentDescriptionKey.get(assignmentKey);
222     }
223 
224     @Override
225     public Map<String, String> getAssignmentDescriptions(Assignment assignment) {
226     	Map<String, String> assignmentDescriptions = new LinkedHashMap<String, String>();
227         if (assignment == null) {
228         	LOG.warn("Assignment is null");
229 //            throw new RuntimeException("Assignment is null");
230         } else { 
231 	        assignmentDescriptions.putAll(TKUtils.formatAssignmentDescription(assignment));
232         }	
233         return assignmentDescriptions;
234 
235     }
236 
237     @Override
238     public Assignment getAssignment(String tkAssignmentId) {
239         return AssignmentBo.to(assignmentDao.getAssignment(tkAssignmentId));
240     }
241 
242     public List<Assignment> getActiveAssignmentsForWorkArea(Long workArea)
243     {
244         List<AssignmentBo> assignments = assignmentDao.getActiveAssignmentsInWorkArea(workArea);
245         List<Assignment> assigns = new ArrayList<Assignment>(assignments.size());
246         for (AssignmentBo assignment : assignments) {
247             assigns.add(AssignmentBo.to(populateAssignment(assignment, assignment.getEffectiveLocalDate())));
248         }
249         return assigns;
250     }
251 
252     @Override
253     public List<Assignment> getActiveAssignmentsForWorkArea(Long workArea, LocalDate asOfDate) {
254         List<AssignmentBo> assignments = assignmentDao.getActiveAssignmentsInWorkArea(workArea, asOfDate);
255         List<Assignment> assigns = new ArrayList<Assignment>(assignments.size());
256         for (AssignmentBo assignment : assignments) {
257             assigns.add(AssignmentBo.to(populateAssignment(assignment, asOfDate)));
258         }
259         return assigns;
260     }
261     
262     @Override
263     public List<Assignment> getActiveAssignmentsForWorkArea(Long workArea, LocalDate beginDate, LocalDate endDate) {
264         List<AssignmentBo> assignments = assignmentDao.getActiveAssignmentsInWorkArea(workArea, beginDate,endDate);
265         List<Assignment> assigns = new ArrayList<Assignment>(assignments.size());
266         for (AssignmentBo assignment : assignments) {
267             assigns.add(AssignmentBo.to(populateAssignment(assignment, beginDate)));
268         }
269         
270         return assigns;
271     }
272 
273     @Override
274     public List<String> getPrincipalIdsInActiveAssignmentsForWorkArea(Long workArea, LocalDate asOfDate) {
275         List<AssignmentBo> assignments = assignmentDao.getActiveAssignmentsInWorkArea(workArea, asOfDate);
276         Set<String> principalIds = new HashSet<String>();
277         for (AssignmentBo assignment : assignments) {
278             principalIds.add(assignment.getPrincipalId());
279         }
280         return new ArrayList<String>(principalIds);
281     }
282 
283     @Override
284     public List<String> getPrincipalIdsInActiveAssignmentsForWorkAreas(List<Long> workAreas, LocalDate asOfDate) {
285         if (org.springframework.util.CollectionUtils.isEmpty(workAreas)) {
286             return Collections.emptyList();
287         }
288         List<AssignmentBo> assignments = assignmentDao.getActiveAssignmentsInWorkAreas(workAreas, asOfDate);
289         Set<String> principalIds = new HashSet<String>();
290         for (AssignmentBo assignment : assignments) {
291             principalIds.add(assignment.getPrincipalId());
292         }
293         return new ArrayList<String>(principalIds);
294     }
295 
296     @Override
297     public List<Assignment> getActiveAssignments(LocalDate asOfDate) {
298         return convertToImmutable(assignmentDao.getActiveAssignments(asOfDate));
299     }
300 
301     protected AssignmentBo populateAssignment(AssignmentBo assignment, LocalDate asOfDate) {
302         assignment.setJob(JobBo.from(HrServiceLocator.getJobService().getJob(assignment.getPrincipalId(), assignment.getJobNumber(), asOfDate)));
303         assignment.setWorkAreaObj(WorkAreaBo.from(HrServiceLocator.getWorkAreaService().getWorkArea(assignment.getWorkArea(), asOfDate)));
304         assignment.setTaskObj(TaskBo.from(HrServiceLocator.getTaskService().getTask(assignment.getTask(), asOfDate)));
305         assignment.populateAssignmentDescription(asOfDate);
306         return assignment;
307     }
308 
309     public Assignment getAssignment(String principalId, AssignmentDescriptionKey key, LocalDate asOfDate) {
310         AssignmentBo a = null;
311 
312         if (key != null) {
313             a = assignmentDao.getAssignment(principalId, key.getGroupKeyCode(), key.getJobNumber(), key.getWorkArea(), key.getTask(), asOfDate);
314         }
315         if (a != null) {
316             a = populateAssignment(a, asOfDate);
317         }
318 
319         return AssignmentBo.to(a);
320     }
321 
322     @Override
323     public Assignment getAssignmentForTargetPrincipal(AssignmentDescriptionKey key, LocalDate asOfDate) {
324         AssignmentBo a = null;
325 
326         if (key != null) {
327             a = assignmentDao.getAssignmentForTargetPrincipal(key.getGroupKeyCode(), key.getJobNumber(), key.getWorkArea(), key.getTask(), asOfDate);
328         }
329 
330         return AssignmentBo.to(a);
331     }
332 
333     /**
334      * KPME-1129 Kagata
335      * Get a list of active assignments based on principalId and jobNumber as of a particular date
336      */
337     @Override
338     public List<Assignment> getActiveAssignmentsForJob(String principalId, Long jobNumber, LocalDate asOfDate) {
339         List<AssignmentBo> assignments = assignmentDao.getActiveAssignmentsForJob(principalId, jobNumber, asOfDate);
340 
341         return convertToImmutable(assignments);
342     }
343     
344     @Override
345     public Map<String, String> getAssignmentDescriptionsForAssignments(List<Assignment> assignments) {
346     	 Map<String, String> assignmentDescriptions = new LinkedHashMap<String, String>();
347          for (Assignment assignment : assignments) {
348                  assignmentDescriptions.putAll(TKUtils.formatAssignmentDescription(assignment));
349          }
350          return assignmentDescriptions;
351     }
352 
353     @Override
354     public Assignment getAssignment(List<Assignment> assignments, String assignmentKey, LocalDate beginDate) {
355         AssignmentDescriptionKey desc = getAssignmentDescriptionKey(assignmentKey);
356     	if (CollectionUtils.isNotEmpty(assignments)) {
357             for (Assignment assignment : assignments) {
358                 if (assignment.getJobNumber().compareTo(desc.getJobNumber()) == 0 &&
359                         assignment.getWorkArea().compareTo(desc.getWorkArea()) == 0 &&
360                         assignment.getTask().compareTo(desc.getTask()) == 0) {
361                     return assignment;
362                 }
363             }
364         }
365 
366         //No assignment found so fetch the inactive ones for this payBeginDate
367         Assignment assign = getAssignmentForTargetPrincipal(desc, beginDate);
368         if (assign != null) {
369             return assign;
370         }
371 
372         LOG.warn("no matched assignment found");
373         return null;
374     }
375     
376     @Override
377     public Assignment getMaxTimestampAssignment(String principalId) {
378     	return AssignmentBo.to(assignmentDao.getMaxTimestampAssignment(principalId));
379     }
380 	
381 	public List<String> getPrincipalIds(List<String> workAreaList, LocalDate effdt, LocalDate startDate, LocalDate endDate) {
382 		if (CollectionUtils.isEmpty(workAreaList)) {
383 			return new ArrayList<String>();
384 		}	
385 		return assignmentDao.getPrincipalIds(workAreaList, effdt, startDate, endDate);
386 	}
387 	
388 	 public List<Assignment> getAssignments(List<String> workAreaList, LocalDate effdt, LocalDate startDate, LocalDate endDate) {
389 		if (CollectionUtils.isEmpty(workAreaList)) {
390 			return Collections.emptyList();
391 		}	
392 		return convertToImmutable(assignmentDao.getAssignments(workAreaList, effdt, startDate, endDate));
393 	}
394 
395     @Override
396     public String getAssignmentDescription(String principalId, String groupKeyCode, Long jobNumber, Long workArea, Long task, LocalDate asOfDate) {
397         StringBuilder builder = new StringBuilder();
398 
399         if (jobNumber != null && workArea != null && task != null) {
400             JobContract jobObj = HrServiceLocator.getJobService().getJob(principalId, jobNumber, asOfDate);
401             WorkArea workAreaObj = HrServiceLocator.getWorkAreaService().getWorkArea(workArea, asOfDate);
402             TaskContract taskObj = HrServiceLocator.getTaskService().getTask(task, asOfDate);
403 
404             String workAreaDescription = workAreaObj != null ? workAreaObj.getDescription() : StringUtils.EMPTY;
405             KualiDecimal compensationRate = jobObj != null ? jobObj.getCompRate() : KualiDecimal.ZERO;
406             String department = jobObj != null ? jobObj.getDept() : StringUtils.EMPTY;
407             String taskDescription = taskObj != null && !HrConstants.TASK_DEFAULT_DESP.equals(taskObj.getDescription()) ? taskObj.getDescription() : StringUtils.EMPTY;
408 
409             builder.append(workAreaDescription).append(" : $").append(compensationRate).append(" Rcd ").append(jobNumber).append(" ").append(department);
410             if (StringUtils.isNotBlank(taskDescription)) {
411                 builder.append(" ").append(taskDescription);
412             }
413         }
414 
415         return builder.toString();
416     }
417 
418 
419     @Override
420     public List<Assignment> getRecentAssignments(String principalId) {
421         //if no dates are specified uses date range of now and now minus limit set in config
422     	Integer limit = 0;
423     	String limitString = ConfigContext.getCurrentContextConfig().getProperty("kpme.tklm.target.employee.time.limit");
424     	if(StringUtils.isNotBlank(limitString)) {
425     		limit = Integer.parseInt(limitString);
426     	}
427         LocalDate startDate = LocalDate.now().minusDays(limit);
428         LocalDate endDate = LocalDate.now();
429 
430         return getRecentAssignmentsBetweenDays(principalId, startDate, endDate);
431     }
432 
433     @Override
434     public List<Assignment> getRecentAssignmentsBetweenDays(String principalId, LocalDate startDate, LocalDate endDate) {
435         Set<Assignment> assignmentSet = new HashSet<Assignment>();
436         List<Assignment> assignmentList = new ArrayList<Assignment>();
437 
438         Map<LocalDate, List<Assignment>> assignmentMap = getAssignmentHistoryBetweenDaysInternal(principalId, startDate, endDate, StringUtils.EMPTY, false);
439         //getAssignmentHistoryBetweenDays(principalId, startDate, endDate);
440 
441         //loop through every entry in the map, and add unique assignments to the set of recent active assignments
442         for (Map.Entry<LocalDate, List<Assignment>> entry : assignmentMap.entrySet()) {
443             for (Assignment assignment : entry.getValue()) {
444                 assignmentSet.add(assignment);
445             }
446         }
447 
448         //convert set to a list
449         assignmentList.addAll(assignmentSet);
450 
451         return assignmentList;
452     }
453 
454     @Override
455     public String getAssignmentDescriptionForAssignment(Assignment assignment, LocalDate asOfDate) {
456         return getAssignmentDescription(assignment.getPrincipalId(), assignment.getGroupKeyCode(), assignment.getJobNumber(), assignment.getWorkArea(), assignment.getTask(), asOfDate);
457     }
458 
459 
460 
461     /*@Override
462     public Map<String, String> getAssignmentDescriptionsForDay(String principalId, boolean clockOnlyAssignments, LocalDate asOfDate ) {
463         Map<LocalDate, List<Assignment>> history = getAssignmentHistoryBetweenDays(principalId, asOfDate, asOfDate);
464         List<Assignment> assignments = history.get(asOfDate);
465         if (CollectionUtils.isEmpty(assignments)) {
466             return Collections.emptyMap();
467         }
468         return filterAssignmentKeys(assignments, clockOnlyAssignments, asOfDate);
469     }*/
470 
471     @Override
472     public Map<LocalDate, List<Assignment>> getAssignmentHistoryBetweenDays(String principalId, LocalDate beginDate, LocalDate endDate) {
473         return getAssignmentHistoryBetweenDaysInternal(principalId, beginDate, endDate, HrConstants.FLSA_STATUS_NON_EXEMPT, false);
474     }
475 
476     @Override
477     public List<Assignment> filterAssignmentListForUser(String userPrincipalId, List<Assignment> assignments) {
478         if (CollectionUtils.isEmpty(assignments)) {
479             return Collections.emptyList();
480         }
481         List<Assignment> filteredAssignments = new ArrayList<Assignment>();
482         //TkUserRoles roles = TkUserRoles.getUserRoles(TKContext.getPrincipalId());
483         //boolean systemAdmin = HrContext.isSystemAdmin();
484         boolean systemAdmin = HrServiceLocator.getKPMEGroupService().isMemberOfSystemAdministratorGroup(userPrincipalId, LocalDate.now().toDateTimeAtStartOfDay());
485 
486         List<String> roleIds = new ArrayList<String>();
487         RoleService roleService = KimApiServiceLocator.getRoleService();
488         roleIds.add(roleService.getRoleIdByNamespaceCodeAndName(KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.REVIEWER.getRoleName()));
489         roleIds.add(roleService.getRoleIdByNamespaceCodeAndName(KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.APPROVER_DELEGATE.getRoleName()));
490         roleIds.add(roleService.getRoleIdByNamespaceCodeAndName(KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.APPROVER.getRoleName()));
491         roleIds.add(roleService.getRoleIdByNamespaceCodeAndName(KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.PAYROLL_PROCESSOR.getRoleName()));
492         roleIds.add(roleService.getRoleIdByNamespaceCodeAndName(KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.PAYROLL_PROCESSOR_DELEGATE.getRoleName()));
493         List<Long> reportingWorkAreas = HrServiceLocator.getKPMERoleService().getWorkAreasForPrincipalInRoles(userPrincipalId, roleIds, LocalDate.now().toDateTimeAtStartOfDay(), true);
494         for (Assignment assignment : assignments) {
495             //if the user is not the same as the timesheet and does not have approver access for the assignment
496             //do not add to the display
497             if (!StringUtils.equals(userPrincipalId, assignment.getPrincipalId())) {
498                 if (!systemAdmin && !reportingWorkAreas.contains(assignment.getWorkArea())) {
499                     continue;
500                 }
501             }
502 
503             filteredAssignments.add(assignment);
504         }
505 
506         return filteredAssignments;
507     }
508 
509 
510     @Override
511     public Map<LocalDate, List<Assignment>> getAssignmentHistoryForCalendarEntry(String principalId, CalendarEntry calendarEntry) {
512         return getAssignmentHistoryBetweenDaysInternal(principalId, calendarEntry.getBeginPeriodFullDateTime().toLocalDate(), calendarEntry.getEndPeriodFullDateTime().toLocalDate(), HrConstants.FLSA_STATUS_NON_EXEMPT, false);
513     }
514 
515     protected Map<LocalDate, List<Assignment>> getAssignmentHistoryBetweenDaysInternal(String principalId, LocalDate beginDate, LocalDate endDate, String flsaStatus, boolean checkLeaveEligible) {
516         Map<LocalDate, List<Assignment>> history = new HashMap<LocalDate, List<Assignment>>();
517 
518         //get active assignments for period begin date
519         List<Assignment> beginAssignments = getAssignments(principalId, beginDate);
520 
521         //might as well set the first day, since we have it already
522         history.put(beginDate, filterAssignments(new ArrayList<Assignment>(beginAssignments), flsaStatus, checkLeaveEligible));
523 
524         if(beginDate.equals(endDate)) {
525             return history;
526         }
527         //get all assignment activity between start and end dates
528         List<AssignmentBo> assignmentChanges = assignmentDao.findAssignmentsHistoryForPeriod(principalId, beginDate, endDate);
529 
530         //let's put this in a map for easier access!!!
531         Map<LocalDate, List<Assignment>> assignmentChangeMap = new HashMap<LocalDate, List<Assignment>>();
532         for (AssignmentBo change : assignmentChanges) {
533             LocalDate key = change.getEffectiveLocalDate();
534             if (assignmentChangeMap.containsKey(key)) {
535                 assignmentChangeMap.get(key).add(AssignmentBo.to(change));
536             } else {
537                 List<Assignment> changeList = new ArrayList<Assignment>();
538                 changeList.add(AssignmentBo.to(change));
539                 assignmentChangeMap.put(key, changeList);
540             }
541         }
542 
543         //we now have a list, in order of the active at the start, and all changes between... now lets try to map it out per day....
544         List<LocalDate> localDates = new ArrayList<LocalDate>();
545         int days = Days.daysBetween(beginDate, endDate).getDays()+1;
546         for (int i=0; i < days; i++) {
547             LocalDate d = beginDate.withFieldAdded(DurationFieldType.days(), i);
548             localDates.add(d);
549         }
550 
551         LocalDate previousDay = beginDate;
552         for (LocalDate ldate : localDates) {
553             if (!ldate.equals(beginDate)) {
554                 List<Assignment> previousAssignments = history.get(previousDay);
555                 List<Assignment> todaysAssignments = new ArrayList<Assignment>(previousAssignments);
556 
557                 if (assignmentChangeMap.containsKey(ldate)) {
558                     //what changed??? Figure it out and filter
559                     for (Assignment a : assignmentChangeMap.get(ldate)) {
560                         if (!a.isActive()) {
561                             // try to remove from list
562                             Iterator<Assignment> iter = todaysAssignments.iterator();
563                             while (iter.hasNext()) {
564                                 Assignment iterAssign = iter.next();
565                                 if (iterAssign.getAssignmentKey().equals(a.getAssignmentKey())) {
566                                     iter.remove();
567                                 }
568                             }
569                         } else {
570                             //if it already exists, remove before adding new
571                             ListIterator<Assignment> iter = todaysAssignments.listIterator();
572                             boolean replaced = false;
573                             while (iter.hasNext()) {
574                                 Assignment iterAssign = iter.next();
575                                 if (iterAssign.getAssignmentKey().equals(a.getAssignmentKey())) {
576                                     iter.set(a);
577                                     replaced = true;
578                                 }
579                             }
580 
581                             //add to list if not already replaced
582                             if (!replaced) {
583                                 todaysAssignments.add(a);
584                             }
585                         }
586                     }
587                     todaysAssignments = filterAssignments(todaysAssignments, flsaStatus, checkLeaveEligible);
588                 }
589 
590                 history.put(ldate, todaysAssignments);
591                 previousDay = ldate;
592             }
593         }
594 
595         return history;
596     }
597 
598 /*    protected Map<String, String> filterAssignmentKeys(List<Assignment> assignments, boolean clockOnlyAssignments, LocalDate asOfDate) {
599         String principalId = "";
600         if (CollectionUtils.isEmpty(assignments)) {
601             return Collections.emptyMap();
602         } else {
603             principalId = assignments.get(0).getPrincipalId();
604         }
605         //sorting the assignment list
606         Collections.sort(assignments, new Comparator<Assignment>() {
607             @Override
608             public int compare(Assignment a1, Assignment a2) {
609                 int sComp = a1.getJobNumber().compareTo(a2.getJobNumber());
610 
611                 if (sComp != 0 ) {
612                     return sComp;
613                 } else {                 //comparing workarea descriptions   TK-1945
614                     String w1 = a1.getWorkAreaObj() == null ? "" : a1.getWorkAreaObj().getDescription();
615                     String w2 = a2.getWorkAreaObj() == null ? "" : a2.getWorkAreaObj().getDescription();
616                     return w1.compareTo(w2);
617                 }
618             }
619         });
620 
621         Map<String, String> assignmentDescriptions = new LinkedHashMap<String, String>();
622         //TkUserRoles roles = TkUserRoles.getUserRoles(TKContext.getPrincipalId());
623         boolean systemAdmin = HrContext.isSystemAdmin();
624         Set<Long> reportingWorkAreas = new HashSet<Long>();
625         reportingWorkAreas.addAll(HrServiceLocator.getKPMERoleService().getWorkAreasForPrincipalInRole(principalId, KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.APPROVER_DELEGATE.getRoleName(), asOfDate.toDateTimeAtStartOfDay(), true));
626         reportingWorkAreas.addAll(HrServiceLocator.getKPMERoleService().getWorkAreasForPrincipalInRole(principalId, KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.APPROVER.getRoleName(), asOfDate.toDateTimeAtStartOfDay(), true));
627         reportingWorkAreas.addAll(HrServiceLocator.getKPMERoleService().getWorkAreasForPrincipalInRole(principalId, KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.REVIEWER.getRoleName(), asOfDate.toDateTimeAtStartOfDay(), true));
628 
629         for (Assignment assignment : assignments) {
630             //if the user is not the same as the timesheet and does not have approver access for the assignment
631             //do not add to the display
632             if (!StringUtils.equals(HrContext.getTargetPrincipalId(), HrContext.getPrincipalId())) {
633                 if (!systemAdmin && !reportingWorkAreas.contains(assignment.getWorkArea())) {
634                     continue;
635                 }
636             }
637 
638             //only add to the assignment list if they are synchronous assignments
639             //or clock only assignments is false
640             if (!clockOnlyAssignments || assignment.isSynchronous()) {
641                 assignmentDescriptions.putAll(getAssignmentDescriptions(assignment));
642             }
643         }
644 
645         return assignmentDescriptions;
646     }*/
647 }