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.assignment.service;
017    
018    import org.apache.commons.collections.CollectionUtils;
019    import org.apache.commons.lang.StringUtils;
020    import org.apache.log4j.Logger;
021    import org.joda.time.DateTime;
022    import org.kuali.hr.job.Job;
023    import org.kuali.hr.lm.leavecalendar.LeaveCalendarDocument;
024    import org.kuali.hr.time.assignment.Assignment;
025    import org.kuali.hr.time.assignment.AssignmentDescriptionKey;
026    import org.kuali.hr.time.assignment.dao.AssignmentDao;
027    import org.kuali.hr.time.calendar.CalendarEntries;
028    import org.kuali.hr.time.service.base.TkServiceLocator;
029    import org.kuali.hr.time.timesheet.TimesheetDocument;
030    import org.kuali.hr.time.util.TKContext;
031    import org.kuali.hr.time.util.TKUser;
032    import org.kuali.hr.time.util.TKUtils;
033    import org.kuali.hr.time.util.TkConstants;
034    
035    import java.sql.Date;
036    import java.util.*;
037    
038    public class AssignmentServiceImpl implements AssignmentService {
039    
040        private static final Logger LOG = Logger.getLogger(AssignmentServiceImpl.class);
041        private AssignmentDao assignmentDao;
042    
043        public AssignmentDao getAssignmentDao() {
044            return assignmentDao;
045        }
046    
047        public void setAssignmentDao(AssignmentDao assignmentDao) {
048            this.assignmentDao = assignmentDao;
049        }
050    
051    
052        @Override
053        public List<Assignment> getAssignments(String principalId, Date asOfDate) {
054            List<Assignment> assignments;
055    
056            if (asOfDate == null) {
057                asOfDate = TKUtils.getCurrentDate();
058            }
059    
060            assignments = assignmentDao.findAssignments(principalId, asOfDate);
061    
062            for (Assignment assignment : assignments) {
063                populateAssignment(assignment, asOfDate);
064            }
065    
066            return assignments;
067        }
068    
069        public List<Assignment> getAssignments(String principalId, Date beginDate, Date endDate) {
070            List<Assignment> assignments;
071    
072            assignments = assignmentDao.findAssignmentsWithinPeriod(principalId, beginDate, endDate);
073    
074            for (Assignment assignment : assignments) {
075                populateAssignment(assignment, assignment.getEffectiveDate());
076            }
077    
078            return assignments;
079        }
080    
081    
082        @Override
083        public List<Assignment> searchAssignments(Date fromEffdt, Date toEffdt, String principalId, String jobNumber,
084                                               String dept, String workArea, String active, String showHistory) {
085            return assignmentDao.searchAssignments(fromEffdt, toEffdt, principalId, jobNumber, dept, workArea, active, showHistory);
086        }
087    
088        public List<Assignment> getAssignmentsByPayEntry(String principalId, CalendarEntries payCalendarEntry) {
089            DateTime entryEndDate = payCalendarEntry.getEndLocalDateTime().toDateTime();
090            if (entryEndDate.getHourOfDay() == 0) {
091                entryEndDate = entryEndDate.minusDays(1);
092            }
093            Date endDate = new java.sql.Date(entryEndDate.getMillis());
094            List<Assignment> beginPeriodAssign = getAssignments(principalId, payCalendarEntry.getBeginPeriodDate());
095            List<Assignment> endPeriodAssign = getAssignments(principalId, endDate);
096            List<Assignment> assignsWithPeriod = getAssignments(principalId, payCalendarEntry.getBeginPeriodDate(), endDate);
097    
098            List<Assignment> finalAssignments = new ArrayList<Assignment>();
099            Map<String, Assignment> assignKeyToAssignmentMap = new HashMap<String, Assignment>();
100            for (Assignment assign : endPeriodAssign) {
101                assignKeyToAssignmentMap.put(TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(), assign.getTask()), assign);
102                finalAssignments.add(assign);
103            }
104    
105            //Compare the begin and end and add any assignments to the end thats are not there
106            for (Assignment assign : beginPeriodAssign) {
107                String assignKey = TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(), assign.getTask());
108                if (!assignKeyToAssignmentMap.containsKey(assignKey)) {
109                    finalAssignments.add(assign);
110                }
111            }
112    
113            // Add the assignments within the pay period
114            for (Assignment assign : assignsWithPeriod) {
115                String assignKey = TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(), assign.getTask());
116                if (!assignKeyToAssignmentMap.containsKey(assignKey)) {
117                    finalAssignments.add(assign);
118                }
119            }
120    
121            return finalAssignments;
122    
123        }
124        
125        public List<Assignment> getAssignmentsByCalEntryForTimeCalendar(String principalId, CalendarEntries payCalendarEntry){
126            if (StringUtils.isEmpty(principalId)
127                    || payCalendarEntry == null) {
128                return Collections.emptyList();
129            }
130            List<Assignment> assignments = TkServiceLocator.getAssignmentService().getAssignmentsByPayEntry(principalId, payCalendarEntry);
131            List<Assignment> results = TkServiceLocator.getAssignmentService().filterAssignments(assignments, TkConstants.FLSA_STATUS_NON_EXEMPT, false);
132            return results;
133        }
134        
135        public List<Assignment> getAssignmentsByCalEntryForLeaveCalendar(String principalId, CalendarEntries payCalendarEntry){
136            if (StringUtils.isEmpty(principalId)
137                    || payCalendarEntry == null) {
138                return Collections.emptyList();
139            }
140            List<Assignment> assignments = TkServiceLocator.getAssignmentService().getAssignmentsByPayEntry(principalId, payCalendarEntry);
141            List<Assignment> results = TkServiceLocator.getAssignmentService().filterAssignments(assignments, null, true);
142            return results;
143        }
144    
145        public List<Assignment> filterAssignments(List<Assignment> assignments, String flsaStatus, boolean chkForLeaveEligible) {
146            List<Assignment> results = new ArrayList<Assignment>();
147            for(Assignment assignment : assignments) {
148                    boolean flag = false;
149                    if(StringUtils.isNotEmpty(flsaStatus)) {
150                            if(assignment != null 
151                                            && assignment.getJob() != null 
152                                            && assignment.getJob().getFlsaStatus() != null 
153                                            && assignment.getJob().getFlsaStatus().equalsIgnoreCase(flsaStatus)) {                          
154                                            if(chkForLeaveEligible) {
155                                                    if(assignment.getJob().isEligibleForLeave()) {
156                                                            flag = true;
157                                                    }
158                                            }else {
159                                                    flag = true;
160                                            }
161                            } 
162                    }else {
163                            if(chkForLeaveEligible) {
164                                    if(assignment != null && assignment.getJob() != null && assignment.getJob().isEligibleForLeave()) {
165                                            flag = true;
166                                    }
167                            } else {
168                                    flag = true;
169                            }
170                    }
171                    
172                            if(flag) {
173                                    results.add(assignment);
174                            }
175            }
176            
177            return results;
178            
179        }
180        
181        @Override
182        public AssignmentDescriptionKey getAssignmentDescriptionKey(String assignmentKey) {
183            return new AssignmentDescriptionKey(assignmentKey);
184        }
185    
186        @Override
187        public Map<String, String> getAssignmentDescriptions(TimesheetDocument td, boolean clockOnlyAssignments) {
188            if (td == null) {
189                //throw new RuntimeException("timesheet document is null.");
190                return Collections.emptyMap();
191            }
192            List<Assignment> assignments = td.getAssignments();
193    //              if(assignments.size() < 1) {
194    //                      throw new RuntimeException("No assignment on the timesheet document.");
195    //              }
196    
197            Map<String, String> assignmentDescriptions = new LinkedHashMap<String, String>();
198            for (Assignment assignment : assignments) {
199                //if the user is not the same as the timesheet and does not have approver access for the assignment
200                //do not add to the display
201                if (!StringUtils.equals(TKContext.getTargetPrincipalId(), TKContext.getPrincipalId())) {
202                    if (!TKUser.isSystemAdmin() && !TKUser.getReportingWorkAreas().contains(assignment.getWorkArea())) {
203                        continue;
204                    }
205                }
206    
207                //only add to the assignment list if they are synchronous assignments
208                //or clock only assignments is false
209                if (!clockOnlyAssignments || assignment.isSynchronous()) {
210                    assignmentDescriptions.putAll(TKUtils.formatAssignmentDescription(assignment));
211                }
212            }
213    
214            return assignmentDescriptions;
215        }
216    
217        @Override
218        public Map<String, String> getAssignmentDescriptions(Assignment assignment) {
219            if (assignment == null) {
220                throw new RuntimeException("Assignment is null");
221            }
222    
223            Map<String, String> assignmentDescriptions = new LinkedHashMap<String, String>();
224            assignmentDescriptions.putAll(TKUtils.formatAssignmentDescription(assignment));
225    
226            return assignmentDescriptions;
227    
228        }
229    
230        @Override
231        public Assignment getAssignment(TimesheetDocument timesheetDocument, String assignmentKey) {
232            List<Assignment> assignments = timesheetDocument.getAssignments();
233            AssignmentDescriptionKey desc = getAssignmentDescriptionKey(assignmentKey);
234    
235            for (Assignment assignment : assignments) {
236                if (assignment.getJobNumber().compareTo(desc.getJobNumber()) == 0 &&
237                        assignment.getWorkArea().compareTo(desc.getWorkArea()) == 0 &&
238                        assignment.getTask().compareTo(desc.getTask()) == 0) {
239                    return assignment;
240                }
241            }
242    
243            //No assignment found so fetch the inactive ones for this payBeginDate
244            Assignment assign = TkServiceLocator.getAssignmentService().getAssignment(desc, timesheetDocument.getCalendarEntry().getBeginPeriodDate());
245            if (assign != null) {
246                return assign;
247            }
248    
249    
250            LOG.warn("no matched assignment found");
251            return new Assignment();
252        }
253    
254        @Override
255        public Assignment getAssignment(String tkAssignmentId) {
256            return getAssignmentDao().getAssignment(tkAssignmentId);
257        }
258    
259    
260        @Override
261        public List<Assignment> getActiveAssignmentsForWorkArea(Long workArea, Date asOfDate) {
262            List<Assignment> assignments = assignmentDao.getActiveAssignmentsInWorkArea(workArea, asOfDate);
263            for (Assignment assignment : assignments) {
264                populateAssignment(assignment, asOfDate);
265            }
266            return assignments;
267        }
268    
269        @Override
270        public List<Assignment> getActiveAssignments(Date asOfDate) {
271            return assignmentDao.getActiveAssignments(asOfDate);
272        }
273    
274        private void populateAssignment(Assignment assignment, Date asOfDate) {
275            assignment.setJob(TkServiceLocator.getJobService().getJob(assignment.getPrincipalId(), assignment.getJobNumber(), asOfDate));
276            assignment.setTimeCollectionRule(TkServiceLocator.getTimeCollectionRuleService().getTimeCollectionRule(assignment.getJob().getDept(), assignment.getWorkArea(), assignment.getJob().getHrPayType(),asOfDate));
277            assignment.setWorkAreaObj(TkServiceLocator.getWorkAreaService().getWorkArea(assignment.getWorkArea(), asOfDate));
278            assignment.setDeptLunchRule(TkServiceLocator.getDepartmentLunchRuleService().getDepartmentLunchRule(assignment.getJob().getDept(),
279                    assignment.getWorkArea(), assignment.getPrincipalId(), assignment.getJobNumber(), asOfDate));
280        }
281    
282        public Assignment getAssignment(String principalId, AssignmentDescriptionKey key, Date asOfDate) {
283            Assignment a = null;
284    
285            if (key != null) {
286                a = assignmentDao.getAssignment(principalId, key.getJobNumber(), key.getWorkArea(), key.getTask(), asOfDate);
287            }
288    
289            return a;
290        }
291    
292        @Override
293        public Assignment getAssignment(AssignmentDescriptionKey key, Date asOfDate) {
294            Assignment a = null;
295    
296            if (key != null) {
297                a = assignmentDao.getAssignment(key.getJobNumber(), key.getWorkArea(), key.getTask(), asOfDate);
298            }
299    
300            return a;
301        }
302    
303        /**
304         * KPME-1129 Kagata
305         * Get a list of active assignments based on principalId and jobNumber as of a particular date
306         */
307        @Override
308        public List<Assignment> getActiveAssignmentsForJob(String principalId, Long jobNumber, Date asOfDate) {
309            List<Assignment> assignments = assignmentDao.getActiveAssignmentsForJob(principalId, jobNumber, asOfDate);
310    
311            return assignments;
312        }
313        
314        @Override
315        public Map<String, String> getAssignmentDescriptions(LeaveCalendarDocument lcd) {
316            if (lcd == null) {
317                throw new RuntimeException("leave document is null.");
318            }
319            List<Assignment> assignments = lcd.getAssignments();
320            return TkServiceLocator.getAssignmentService().getAssignmentDescriptionsForAssignments(assignments);
321        }
322        
323        public Map<String, String> getAssignmentDescriptionsForAssignments(List<Assignment>  assignments) {
324             Map<String, String> assignmentDescriptions = new LinkedHashMap<String, String>();
325             for (Assignment assignment : assignments) {
326                     assignmentDescriptions.putAll(TKUtils.formatAssignmentDescription(assignment));
327             }
328             return assignmentDescriptions;
329        }
330    
331        @Override
332        public Assignment getAssignment(LeaveCalendarDocument leaveCalendarDocument, String assignmentKey) {
333            List<Assignment> assignments = leaveCalendarDocument.getAssignments();
334            return TkServiceLocator.getAssignmentService().getAssignment(assignments, assignmentKey, leaveCalendarDocument.getCalendarEntry().getBeginPeriodDate());
335        }
336        
337        public Assignment getAssignment(List<Assignment> assignments, String assignmentKey, Date beginDate) {
338            AssignmentDescriptionKey desc = getAssignmentDescriptionKey(assignmentKey);
339            if (CollectionUtils.isNotEmpty(assignments)) {
340                for (Assignment assignment : assignments) {
341                    if (assignment.getJobNumber().compareTo(desc.getJobNumber()) == 0 &&
342                            assignment.getWorkArea().compareTo(desc.getWorkArea()) == 0 &&
343                            assignment.getTask().compareTo(desc.getTask()) == 0) {
344                        return assignment;
345                    }
346                }
347            }
348    
349            //No assignment found so fetch the inactive ones for this payBeginDate
350            Assignment assign = TkServiceLocator.getAssignmentService().getAssignment(desc, beginDate);
351            if (assign != null) {
352                return assign;
353            }
354    
355            LOG.warn("no matched assignment found");
356            return new Assignment();
357        }
358        
359        @Override
360        public Assignment getMaxTimestampAssignment(String principalId) {
361            return assignmentDao.getMaxTimestampAssignment(principalId);
362        }
363        
364            public Assignment getAssignmentToApplyScheduledTimeOff(TimesheetDocument timesheetDocument, java.sql.Date payEndDate) {
365                    Job primaryJob = TkServiceLocator.getJobService().getPrimaryJob(timesheetDocument.getPrincipalId(), payEndDate);
366                    for(Assignment assign : timesheetDocument.getAssignments()){
367                            if(assign.getJobNumber().equals(primaryJob.getJobNumber())){
368                                    return assign;
369                            }
370                    }
371                    return null;
372            }
373            
374            public List<String> getPrincipalIds(List<String> workAreaList, Date effdt, Date startDate, Date endDate) {
375                    if (CollectionUtils.isEmpty(workAreaList)) {
376                            return new ArrayList<String>();
377                    }       
378                    return assignmentDao.getPrincipalIds(workAreaList, effdt, startDate, endDate);
379            }
380            
381             public List<Assignment> getAssignments(List<String> workAreaList, Date effdt, Date startDate, Date endDate) {
382                    if (CollectionUtils.isEmpty(workAreaList)) {
383                            return new ArrayList<Assignment>();
384                    }       
385                    return assignmentDao.getAssignments(workAreaList, effdt, startDate, endDate);
386            }
387    }