Example usage for org.joda.time DateTime minusDays

List of usage examples for org.joda.time DateTime minusDays

Introduction

In this page you can find the example usage for org.joda.time DateTime minusDays.

Prototype

public DateTime minusDays(int days) 

Source Link

Document

Returns a copy of this datetime minus the specified number of days.

Usage

From source file:org.kuali.kpme.core.calendar.entry.dao.CalendarEntryDaoOjbImpl.java

License:Educational Community License

public List<CalendarEntry> getCurrentCalendarEntryNeedsScheduled(int thresholdDays, DateTime asOfDate) {
    DateTime windowStart = asOfDate.minusDays(thresholdDays);
    DateTime windowEnd = asOfDate.plusDays(thresholdDays);

    Criteria root = new Criteria();

    root.addGreaterOrEqualThan("beginPeriodDateTime", windowStart.toDate());
    root.addLessOrEqualThan("beginPeriodDateTime", windowEnd.toDate());

    Query query = QueryFactory.newQuery(CalendarEntry.class, root);
    Collection c = this.getPersistenceBrokerTemplate().getCollectionByQuery(query);

    List<CalendarEntry> pce = new ArrayList<CalendarEntry>(c.size());
    pce.addAll(c);/*from   ww  w .j  av  a2 s  .c  om*/

    return pce;
}

From source file:org.kuali.kpme.tklm.leave.accrual.bucket.KPMEAccrualCategoryBucket.java

License:Educational Community License

private void adjustBalances(CalendarEntry calendarEntry, DateTime rolloverDate, Set<String> assignmentKeys)
        throws KPMEBalanceException {

    //fetch calendar entries in this sequence belonging to the current leave year.
    String dateString = TKUtils.formatDate(LocalDate.now());
    List<CalendarEntry> calendarEntries = HrServiceLocator.getCalendarEntryService()
            .getAllCalendarEntriesForCalendarIdAndYear(calendarEntry.getHrCalendarId(),
                    dateString.substring(6, 10));

    //calendar change into a different leave calendar year
    if (rolloverDate != null) {

        //clear all balances.
        clearLeaveBalances();/*from ww w.j  a va  2 s .  c  o  m*/

        //reset the asOfDate this bucket will go off of, as well as those of the leave balances
        adjustAsOfDates(calendarEntry, calendarEntries);

        //TODO: if in current calendar year, use current date + planning months for extent of fetch.
        List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksSinceCarryOver(
                principalCalendar.getPrincipalId(),
                LmServiceLocator.getLeaveBlockService().getLastCarryOverBlocks(
                        principalCalendar.getPrincipalId(), rolloverDate.minusDays(1).toLocalDate()),
                rolloverDate.plusDays(365).toLocalDate(), true);

        //retrieve (if any) last carryover blocks given the new asOfDate
        Map<String, LeaveBlock> carryOverBlocks = LmServiceLocator.getLeaveBlockService()
                .getLastCarryOverBlocks(principalCalendar.getPrincipalId(), asOfDate);

        //method taken from leave summary service - map general leave block fetch by accrual category
        Map<String, List<LeaveBlock>> accrualCategoryMappedLeaveBlocks = mapLeaveBlocksByAccrualCategory(
                leaveBlocks);

        //merge carryOverBlock map with accrualCategoryMappedLeaveBlocks.
        for (Entry<String, LeaveBlock> entry : carryOverBlocks.entrySet()) {
            //TODO: modify CarryOverLeaveBalance to identify and make use of CARRY_OVER type leave block
            if (accrualCategoryMappedLeaveBlocks.containsKey(entry.getKey()))
                accrualCategoryMappedLeaveBlocks.get(entry.getKey()).add(entry.getValue());
            else {
                List<LeaveBlock> carryOverList = new ArrayList<LeaveBlock>();
                carryOverList.add(entry.getValue());
                accrualCategoryMappedLeaveBlocks.put(entry.getKey(), carryOverList);
            }

        }
        //add leave blocks, accrual category by accrual category, to this bucket.
        for (Entry<String, List<LeaveBlock>> entry : accrualCategoryMappedLeaveBlocks.entrySet()) {
            for (LeaveBlock leaveBlock : entry.getValue()) {
                try {
                    addLeaveBlock(leaveBlock);
                } catch (KPMEBalanceException e) {
                    InstantiationException ie = new InstantiationException();
                    ie.setStackTrace(e.getStackTrace());
                    ie.printStackTrace();
                }
            }
        }
    } else {
        //Calendar change within the same leave year.

        List<String> assignmentKeyList = new ArrayList<String>();
        assignmentKeyList.addAll(assignmentKeys);

        List<LeaveBlock> leaveBlocks = new ArrayList<LeaveBlock>();

        //determine which leave blocks are affected by the calendar change, remove them, and re-add them under the new asOfDate
        if (calendarEntry.getEndPeriodFullDateTime()
                .isBefore(viewingCalendarEntry.getEndPeriodFullDateTime().getMillis())) {
            //need to remove leave blocks from otherLeaveCalendarDocument begin date to thisLeaveCalendarDocument end date
            leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocks(
                    principalCalendar.getPrincipalId(),
                    LocalDate.fromDateFields(calendarEntry.getBeginPeriodDateTime()),
                    LocalDate.fromDateFields(viewingCalendarEntry.getEndPeriodDateTime()));
            //leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForLeaveCalendar(principalCalendar.getPrincipalId(), LocalDate.fromDateFields(calendarEntry.getBeginPeriodDateTime()), LocalDate.fromDateFields(viewingCalendarEntry.getEndPeriodDateTime()), assignmentKeyList);
        } else {
            //need to remove leave blocks from thisLeaveCalendarDocument begin date to otherLeaveCalendarDocument end date
            leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocks(
                    principalCalendar.getPrincipalId(),
                    LocalDate.fromDateFields(viewingCalendarEntry.getBeginPeriodDateTime()),
                    LocalDate.fromDateFields(calendarEntry.getEndPeriodDateTime()));
            //leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForLeaveCalendar(principalCalendar.getPrincipalId(), LocalDate.fromDateFields(viewingCalendarEntry.getBeginPeriodDateTime()), LocalDate.fromDateFields(calendarEntry.getEndPeriodDateTime()), assignmentKeyList);
        }
        //remove affected leave blocks
        for (LeaveBlock block : leaveBlocks) {
            removeLeaveBlock(block);
        }

        //update this bucket and its leave balances with new relative date information
        LocalDate newAsOfDate = null;
        DateTime currentLeavePlanStartDate = HrServiceLocator.getLeavePlanService()
                .getFirstDayOfLeavePlan(principalCalendar.getLeavePlan(), LocalDate.now());
        if (calendarEntry.getEndPeriodDate().before(currentLeavePlanStartDate.toDate())) {
            //require balances as of the final day of the leave calendar year.
            DateTime calendarEntryLeavePlanRolloverDate = HrServiceLocator.getLeavePlanService()
                    .getRolloverDayOfLeavePlan(principalCalendar.getLeavePlan(),
                            LocalDate.fromDateFields(calendarEntry.getEndPeriodDate()));
            newAsOfDate = LocalDate.fromDateFields(calendarEntryLeavePlanRolloverDate.toDate()).minusDays(1);
        } else {
            Interval interval = new Interval(calendarEntry.getBeginPeriodDateTime().getTime(),
                    calendarEntry.getEndPeriodDateTime().getTime());
            if (interval.contains(LocalDate.now().toDate().getTime())) {
                newAsOfDate = LocalDate.now();
            } else if (calendarEntry.getBeginPeriodDate().before(LocalDate.now().toDate()))
                newAsOfDate = LocalDate.fromDateFields(calendarEntry.getEndPeriodDate()).minusDays(1);
            else // if it's in the calendar interval above, the equals case is taken care of, begin date must be after today
                newAsOfDate = LocalDate.fromDateFields(calendarEntry.getBeginPeriodDate()).minusDays(1);
        }

        asOfDate = newAsOfDate;

        for (Entry<String, List<LeaveBalance>> leaveBalance : leaveBalances.entrySet()) {
            for (LeaveBalance balance : leaveBalance.getValue()) {
                balance.calendarPeriodBeginDate = LocalDate
                        .fromDateFields(calendarEntry.getBeginPeriodDateTime());
                balance.calendarPeriodEndDate = LocalDate.fromDateFields(calendarEntry.getEndPeriodDateTime());
                balance.asOfDate = newAsOfDate;
            }
        }
        //re-add the affected leave blocks under the new date / calendar information
        for (LeaveBlock block : leaveBlocks) {
            addLeaveBlock(block);
        }
    }
}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualServiceImpl.java

License:Educational Community License

@Override
public DateTime getPreviousAccrualIntervalDate(String earnInterval, DateTime aDate) {
    DateTime previousAccrualIntervalDate = null;

    if (earnInterval.equals(HrConstants.ACCRUAL_EARN_INTERVAL_CODE.DAILY)) {
        previousAccrualIntervalDate = aDate.minusDays(1);
    } else if (earnInterval.equals(HrConstants.ACCRUAL_EARN_INTERVAL_CODE.WEEKLY)) {
        previousAccrualIntervalDate = aDate.minusWeeks(1).withDayOfWeek(DateTimeConstants.SATURDAY);
    } else if (earnInterval.equals(HrConstants.ACCRUAL_EARN_INTERVAL_CODE.SEMI_MONTHLY)) {
        previousAccrualIntervalDate = aDate.minusDays(15);
        if (previousAccrualIntervalDate.getDayOfMonth() <= 15) {
            previousAccrualIntervalDate = previousAccrualIntervalDate.withDayOfMonth(15);
        } else {/*from   w w w.jav  a 2s  .c om*/
            previousAccrualIntervalDate = previousAccrualIntervalDate
                    .withDayOfMonth(previousAccrualIntervalDate.dayOfMonth().getMaximumValue());
        }
    } else if (earnInterval.equals(HrConstants.ACCRUAL_EARN_INTERVAL_CODE.MONTHLY)) {
        previousAccrualIntervalDate = aDate.minusMonths(1);
        previousAccrualIntervalDate = previousAccrualIntervalDate
                .withDayOfMonth(previousAccrualIntervalDate.dayOfMonth().getMaximumValue());
    } else if (earnInterval.equals(HrConstants.ACCRUAL_EARN_INTERVAL_CODE.YEARLY)) {
        previousAccrualIntervalDate = aDate.minusYears(1);
        previousAccrualIntervalDate = previousAccrualIntervalDate
                .withDayOfYear(previousAccrualIntervalDate.dayOfYear().getMaximumValue());
    } else if (earnInterval.equals(HrConstants.ACCRUAL_EARN_INTERVAL_CODE.NO_ACCRUAL)) {
        previousAccrualIntervalDate = aDate;
    }

    return previousAccrualIntervalDate;
}

From source file:org.kuali.kpme.tklm.leave.batch.CarryOverSchedulerJob.java

License:Educational Community License

@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    LocalDate asOfDate = LocalDate.now();
    List<LeavePlan> leavePlans = HrServiceLocator.getLeavePlanService()
            .getLeavePlansNeedsCarryOverScheduled(getLeavePlanPollingWindow(), asOfDate);
    try {/*from w w  w.  j  a v a  2s .  c o  m*/
        if (leavePlans != null && !leavePlans.isEmpty()) {
            DateTime current = asOfDate.toDateTimeAtStartOfDay();
            DateTime windowStart = current.minusDays(getLeavePlanPollingWindow());
            DateTime windowEnd = current.plusDays(getLeavePlanPollingWindow());

            // schedule batch job for all LeavePlans who fall in leave polling window.
            for (LeavePlan leavePlan : leavePlans) {
                if (leavePlan.getBatchPriorYearCarryOverStartDate() != null
                        && leavePlan.getBatchPriorYearCarryOverStartTime() != null) {
                    DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd");
                    DateTime batchPriorYearCarryOverStartDateTime = formatter
                            .parseDateTime(leavePlan.getBatchPriorYearCarryOverStartDate())
                            .plus(leavePlan.getBatchPriorYearCarryOverStartTime().getTime());
                    if (batchPriorYearCarryOverStartDateTime.compareTo(windowStart) >= 0
                            && batchPriorYearCarryOverStartDateTime.compareTo(windowEnd) <= 0) {
                        getBatchJobService().scheduleLeaveCarryOverJobs(leavePlan);
                    }
                }
            }
        }
    } catch (SchedulerException se) {
        LOG.warn("Exception thrown during job scheduling of Carry over for Leave", se);
        //           throw new JobExecutionException("Exception thrown during job scheduling of Carry over for Leave", se);
    }
}

From source file:org.kuali.kpme.tklm.leave.calendar.LeaveCalendar.java

License:Educational Community License

public LeaveCalendar(String principalId, CalendarEntry calendarEntry, List<String> assignmentKeys) {
    super(calendarEntry);

    DateTime currentDisplayDateTime = getBeginDateTime();
    DateTime endDisplayDateTime = getEndDateTime();

    // Fill in the days if the first day or end day is in the middle of the week
    if (currentDisplayDateTime.getDayOfWeek() != DateTimeConstants.SUNDAY) {
        currentDisplayDateTime = currentDisplayDateTime.minusDays(currentDisplayDateTime.getDayOfWeek());
    }//  ww  w. j a v a  2 s  .  c  o m
    if (endDisplayDateTime.getDayOfWeek() != DateTimeConstants.SATURDAY) {
        endDisplayDateTime = endDisplayDateTime
                .plusDays(DateTimeConstants.SATURDAY - endDisplayDateTime.getDayOfWeek());
    }

    LeaveCalendarWeek leaveCalendarWeek = new LeaveCalendarWeek();
    Integer dayNumber = 0;
    List<LeaveBlock> blocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocks(principalId,
            calendarEntry.getBeginPeriodFullDateTime().toLocalDate(),
            calendarEntry.getEndPeriodFullDateTime().toLocalDate());
    Map<String, List<LeaveBlock>> leaveBlockMap = new HashMap<String, List<LeaveBlock>>();
    for (LeaveBlock lb : blocks) {
        String key = lb.getLeaveLocalDate().toString();
        if (leaveBlockMap.containsKey(key)) {
            leaveBlockMap.get(key).add(lb);
        } else {
            leaveBlockMap.put(key, createNewLeaveBlockList(lb));
        }
    }

    //KPME-2560 If leave calendar document is final status, then User wont be able to add leave blocks to the calendar. 
    Boolean dayEditableFlag = true;
    LeaveCalendarDocumentHeader header = LmServiceLocator.getLeaveCalendarDocumentHeaderService()
            .getDocumentHeader(principalId, calendarEntry.getBeginPeriodFullDateTime(),
                    calendarEntry.getEndPeriodFullDateTime());
    if (header != null && header.getDocumentStatus().equals(HrConstants.ROUTE_STATUS.FINAL))
        dayEditableFlag = false;

    while (currentDisplayDateTime.isBefore(endDisplayDateTime)
            || currentDisplayDateTime.isEqual(endDisplayDateTime)) {
        LeaveCalendarDay leaveCalendarDay = new LeaveCalendarDay();

        // If the day is not within the current pay period, mark them as read only (gray)
        if (currentDisplayDateTime.isBefore(getBeginDateTime())
                || currentDisplayDateTime.isEqual(getEndDateTime())
                || currentDisplayDateTime.isAfter(getEndDateTime())) {
            leaveCalendarDay.setGray(true);
        } else {
            // This is for the div id of the days on the calendar.
            // It creates a day id like day_11/01/2011 which will make day parsing easier in the javascript.
            //                leaveCalendarDay.setDayNumberDelta(currDateTime.toString(HrConstants.DT_BASIC_DATE_FORMAT));
            //                leaveCalendarDay.setDayNumberDelta(currDateTime.getDayOfMonth());
            leaveCalendarDay.setDayNumberDelta(dayNumber);

            LocalDate leaveDate = currentDisplayDateTime.toLocalDate();
            List<LeaveBlock> lbs = leaveBlockMap.get(currentDisplayDateTime.toLocalDate().toString());
            if (lbs == null) {
                lbs = Collections.emptyList();
            }
            // use given assignmentKeys to control leave blocks displayed on the calendar
            if (CollectionUtils.isNotEmpty(lbs) && CollectionUtils.isNotEmpty(assignmentKeys)) {
                List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService()
                        .filterLeaveBlocksForLeaveCalendar(lbs, assignmentKeys);
                leaveCalendarDay.setLeaveBlocks(leaveBlocks);
            } else {
                leaveCalendarDay.setLeaveBlocks(lbs);
            }

            if (HrServiceLocator.getHRPermissionService().canViewLeaveTabsWithNEStatus()) {
                TimesheetDocumentHeader tdh = TkServiceLocator.getTimesheetDocumentHeaderService()
                        .getDocumentHeaderForDate(principalId, leaveDate.toDateTimeAtStartOfDay());
                if (tdh != null) {
                    if (DateUtils.isSameDay(leaveDate.toDate(), tdh.getEndDate())
                            || leaveDate.isAfter(LocalDate.fromDateFields(tdh.getEndDate()))) {
                        leaveCalendarDay.setDayEditable(true);
                    }
                } else {
                    leaveCalendarDay.setDayEditable(true);
                }
            } else {
                leaveCalendarDay.setDayEditable(true);
            }
            //KPME-2560 If leave calendar document is final status, then User wont be able to add leave blocks to the calendar. 
            if (!dayEditableFlag)
                leaveCalendarDay.setDayEditable(false);

            dayNumber++;
        }
        leaveCalendarDay.setDayNumberString(currentDisplayDateTime.dayOfMonth().getAsShortText());
        leaveCalendarDay.setDateString(currentDisplayDateTime.toString(HrConstants.DT_BASIC_DATE_FORMAT));

        leaveCalendarWeek.getDays().add(leaveCalendarDay);

        if (leaveCalendarWeek.getDays().size() == DateTimeConstants.DAYS_PER_WEEK) {
            getWeeks().add(leaveCalendarWeek);
            leaveCalendarWeek = new LeaveCalendarWeek();
        }

        currentDisplayDateTime = currentDisplayDateTime.plusDays(1);
    }

    if (!leaveCalendarWeek.getDays().isEmpty()) {
        getWeeks().add(leaveCalendarWeek);
    }

    boolean isPlanningCal = LmServiceLocator.getLeaveCalendarService().isLeavePlanningCalendar(principalId,
            calendarEntry.getBeginPeriodFullDateTime().toLocalDate(),
            calendarEntry.getEndPeriodFullDateTime().toLocalDate());
    Map<String, String> earnCodes = HrServiceLocator.getEarnCodeService().getEarnCodesForDisplay(principalId,
            isPlanningCal);
    setEarnCodeList(earnCodes);
}

From source file:org.kuali.kpme.tklm.leave.calendar.LeaveRequestCalendar.java

License:Educational Community License

public LeaveRequestCalendar(DateTime beginDateTime, DateTime endDateTime,
        Map<String, List<LeaveRequestDocument>> leaveReqDocsMap, Map<String, List<LeaveBlock>> leaveBlocksMap,
        Map<String, List<LeaveBlockHistory>> disapprovedLBMap, String calendarType) {
    this.calendarType = calendarType;
    setBeginDateTime(beginDateTime);// w  w w.  jav  a 2 s  . c  o m
    setEndDateTime(endDateTime);

    DateTime currentDisplayDateTime = new DateTime(beginDateTime.getMillis());
    DateTime endDisplayDateTime = new DateTime(endDateTime.getMillis());

    // Fill in the days if the first day or end day is in the middle of the week
    if (currentDisplayDateTime.getDayOfWeek() != DateTimeConstants.SUNDAY) {
        currentDisplayDateTime = currentDisplayDateTime.minusDays(currentDisplayDateTime.getDayOfWeek());
    }
    if (endDisplayDateTime.getDayOfWeek() != DateTimeConstants.SATURDAY) {
        endDisplayDateTime = endDisplayDateTime
                .plusDays(DateTimeConstants.SATURDAY - endDisplayDateTime.getDayOfWeek());
    }

    LeaveRequestCalendarWeek leaveReqCalendarWeek = new LeaveRequestCalendarWeek();
    Integer dayNumber = 0;

    while (currentDisplayDateTime.isBefore(endDisplayDateTime)
            || currentDisplayDateTime.isEqual(endDisplayDateTime)) {
        LeaveRequestCalendarDay leaveReqCalendarDay = new LeaveRequestCalendarDay();

        // If the day is not within the current pay period, mark them as read only (gray)
        if (StringUtils.equalsIgnoreCase("M", calendarType)
                && (currentDisplayDateTime.isBefore(getBeginDateTime())
                        || currentDisplayDateTime.isEqual(getEndDateTime())
                        || currentDisplayDateTime.isAfter(getEndDateTime()))) {
            leaveReqCalendarDay.setGray(true);
        } else {
            // This is for the div id of the days on the calendar.
            // It creates a day id like day_11/01/2011 which will make day parsing easier in the javascript.
            leaveReqCalendarDay.setDayNumberDelta(dayNumber);

            List<LeaveRequestDocument> reqDocs = leaveReqDocsMap
                    .get(currentDisplayDateTime.toLocalDate().toString());
            List<LeaveBlock> leaveBlocks = leaveBlocksMap.get(currentDisplayDateTime.toLocalDate().toString());
            List<LeaveBlockHistory> disapprovedBlocks = disapprovedLBMap
                    .get(currentDisplayDateTime.toLocalDate().toString());
            List<LeaveRequestApprovalRow> rowList = new ArrayList<LeaveRequestApprovalRow>();
            if (reqDocs == null) {
                reqDocs = Collections.emptyList();
            }
            if (leaveBlocks == null) {
                leaveBlocks = Collections.emptyList();
            }
            List<String> leaveBlockIds = new ArrayList<String>();
            if (!reqDocs.isEmpty()) {
                for (LeaveRequestDocument lrd : reqDocs) {
                    LeaveBlock lb = lrd.getLeaveBlock();
                    leaveBlockIds.add(lb.getLmLeaveBlockId());
                    String principalId = lb.getPrincipalId();
                    LeaveRequestApprovalRow aRow = new LeaveRequestApprovalRow();
                    // Set Employee Name 
                    EntityNamePrincipalName entityNamePrincipalName = KimApiServiceLocator.getIdentityService()
                            .getDefaultNamesForPrincipalId(principalId);
                    if (entityNamePrincipalName != null) {
                        aRow.setPrincipalId(principalId);
                        aRow.setEmployeeName(
                                entityNamePrincipalName.getDefaultName() == null ? StringUtils.EMPTY
                                        : entityNamePrincipalName.getDefaultName().getCompositeName());
                    }
                    aRow.setLeaveRequestDocId(lrd.getDocumentNumber());
                    aRow.setLeaveCode(lb.getEarnCode());
                    aRow.setRequestedDate(TKUtils.formatDate(lb.getLeaveLocalDate()));
                    aRow.setRequestedHours(lb.getLeaveAmount().toString());
                    aRow.setDescription(
                            lrd.getDescription() == null ? lb.getDescription() : lrd.getDescription());
                    aRow.setAssignmentTitle(lb.getAssignmentTitle());
                    aRow.setRequestStatus(lb.getRequestStatusString().toLowerCase());
                    rowList.add(aRow);
                }
            }

            if (!leaveBlocks.isEmpty()) {
                for (LeaveBlock lb : leaveBlocks) {
                    if (!leaveBlockIds.contains(lb.getLmLeaveBlockId())) {
                        String principalId = lb.getPrincipalId();
                        LeaveRequestApprovalRow aRow = new LeaveRequestApprovalRow();
                        // Set Employee Name 
                        EntityNamePrincipalName entityNamePrincipalName = KimApiServiceLocator
                                .getIdentityService().getDefaultNamesForPrincipalId(principalId);
                        if (entityNamePrincipalName != null) {
                            aRow.setPrincipalId(principalId);
                            aRow.setEmployeeName(
                                    entityNamePrincipalName.getDefaultName() == null ? StringUtils.EMPTY
                                            : entityNamePrincipalName.getDefaultName().getCompositeName());
                        }
                        aRow.setLeaveCode(lb.getEarnCode());
                        aRow.setRequestedDate(TKUtils.formatDate(lb.getLeaveLocalDate()));
                        aRow.setRequestedHours(lb.getLeaveAmount().toString());
                        aRow.setRequestStatus(lb.getRequestStatusString().toLowerCase());
                        aRow.setDescription(lb.getDescription());
                        aRow.setAssignmentTitle(lb.getAssignmentTitle());
                        rowList.add(aRow);
                    }
                }
            }
            // Adding disapproved blocks.
            if (disapprovedBlocks != null && !disapprovedBlocks.isEmpty()) {
                for (LeaveBlockHistory lb : disapprovedBlocks) {
                    String principalId = lb.getPrincipalId();
                    LeaveRequestApprovalRow aRow = new LeaveRequestApprovalRow();
                    // Set Employee Name 
                    EntityNamePrincipalName entityNamePrincipalName = KimApiServiceLocator.getIdentityService()
                            .getDefaultNamesForPrincipalId(principalId);
                    if (entityNamePrincipalName != null) {
                        aRow.setPrincipalId(principalId);
                        aRow.setEmployeeName(
                                entityNamePrincipalName.getDefaultName() == null ? StringUtils.EMPTY
                                        : entityNamePrincipalName.getDefaultName().getCompositeName());
                    }
                    aRow.setLeaveCode(lb.getEarnCode());
                    aRow.setRequestedDate(TKUtils.formatDate(lb.getLeaveLocalDate()));
                    aRow.setRequestedHours(lb.getLeaveAmount().toString());
                    aRow.setRequestStatus(lb.getRequestStatusString().toLowerCase());
                    aRow.setDescription(lb.getDescription());
                    aRow.setAssignmentTitle(lb.getAssignmentTitle());
                    rowList.add(aRow);
                }
            }

            leaveReqCalendarDay.setLeaveReqRows(rowList);
            if (!rowList.isEmpty() && rowList.size() > 0) {
                requestList.addAll(rowList);
            }
            dayNumber++;
        }

        leaveReqCalendarDay.setDayNumberString(currentDisplayDateTime.dayOfMonth().getAsShortText());
        leaveReqCalendarDay
                .setDateString(currentDisplayDateTime.toString(HrConstants.DateTimeFormats.BASIC_DATE_FORMAT));

        leaveReqCalendarWeek.getDays().add(leaveReqCalendarDay);

        if (leaveReqCalendarWeek.getDays().size() == DateTimeConstants.DAYS_PER_WEEK) {
            getWeeks().add(leaveReqCalendarWeek);
            leaveReqCalendarWeek = new LeaveRequestCalendarWeek();
        }

        currentDisplayDateTime = currentDisplayDateTime.plusDays(1);
    }

    if (!leaveReqCalendarWeek.getDays().isEmpty()) {
        getWeeks().add(leaveReqCalendarWeek);
    }

}

From source file:org.kuali.kpme.tklm.leave.calendar.validation.LeaveCalendarValidationUtil.java

License:Educational Community License

public static List<String> validateAvailableLeaveBalanceForUsage(String earnCode, String leaveStartDateString,
        String leaveEndDateString, BigDecimal leaveAmount, LeaveBlock updatedLeaveBlock) {
    List<String> errors = new ArrayList<String>();
    boolean earnCodeChanged = false;
    BigDecimal oldAmount = null;//  w w w. j  a v a  2 s.com

    if (leaveAmount == null) {
        leaveAmount = TKUtils.getHoursBetween(TKUtils.formatDateString(leaveStartDateString).toDate().getTime(),
                TKUtils.formatDateString(leaveEndDateString).toDate().getTime());
    }
    if (updatedLeaveBlock != null) {
        if (!updatedLeaveBlock.getEarnCode().equals(earnCode)) {
            earnCodeChanged = true;
        }
        if (!updatedLeaveBlock.getLeaveAmount().equals(leaveAmount)) {
            oldAmount = updatedLeaveBlock.getLeaveAmount();
        }
    }
    LocalDate startDate = TKUtils.formatDateString(leaveStartDateString);
    LocalDate endDate = TKUtils.formatDateString(leaveEndDateString);
    long daysSpan = TKUtils.getDaysBetween(startDate, endDate);
    EarnCode earnCodeObj = HrServiceLocator.getEarnCodeService().getEarnCode(earnCode, endDate);
    if (earnCodeObj != null && earnCodeObj.getAllowNegativeAccrualBalance().equals("N")) {
        AccrualCategory accrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(earnCodeObj.getAccrualCategory(), endDate);
        if (accrualCategory != null) {
            DateTime nextIntervalDate = LmServiceLocator.getAccrualService().getNextAccrualIntervalDate(
                    accrualCategory.getAccrualEarnInterval(), endDate.toDateTimeAtStartOfDay());
            // get the usage checking cut off Date, normally it's the day before the next interval date
            DateTime usageEndDate = nextIntervalDate;
            if (nextIntervalDate.compareTo(endDate.toDateTimeAtCurrentTime()) > 0) {
                usageEndDate = nextIntervalDate.minusDays(1);
            }
            // use the end of the year as the interval date for usage checking of no-accrual hours,
            // normally no-accrual hours are from banked/transferred system scheduled time offs
            if (accrualCategory.getAccrualEarnInterval()
                    .equals(HrConstants.ACCRUAL_EARN_INTERVAL_CODE.NO_ACCRUAL)) {
                usageEndDate = endDate.toDateTimeAtStartOfDay().withMonthOfYear(DateTimeConstants.DECEMBER)
                        .withDayOfMonth(31);
            }
            BigDecimal availableBalance = LmServiceLocator.getLeaveSummaryService()
                    .getLeaveBalanceForAccrCatUpToDate(HrContext.getTargetPrincipalId(), startDate, endDate,
                            accrualCategory.getAccrualCategory(), usageEndDate.toLocalDate());

            if (oldAmount != null) {
                if (!earnCodeChanged || updatedLeaveBlock.getAccrualCategory()
                        .equals(accrualCategory.getAccrualCategory())) {
                    availableBalance = availableBalance.add(oldAmount.abs());
                }
            }
            //multiply by days in span in case the user has also edited the start/end dates.
            BigDecimal desiredUsage = null;
            if (!HrConstants.EARN_CODE_TIME.equals(earnCodeObj.getRecordMethod())) {
                desiredUsage = leaveAmount.multiply(new BigDecimal(daysSpan + 1));
            } else {
                desiredUsage = leaveAmount.multiply(new BigDecimal(daysSpan));
            }

            if (desiredUsage.compareTo(availableBalance) > 0) {
                errors.add("Requested leave amount " + desiredUsage.toString()
                        + " is greater than available leave balance " + availableBalance.toString()); //errorMessages
            }
        }
    }

    return errors;
}

From source file:org.kuali.kpme.tklm.leave.calendar.web.LeaveCalendarAction.java

License:Educational Community License

protected void setLeaveSummary(LeaveCalendarForm leaveCalendarForm) throws Exception {
    String principalId = HrContext.getTargetPrincipalId();
    CalendarEntry calendarEntry = leaveCalendarForm.getCalendarEntry();
    PrincipalHRAttributes principalHRAttributes = HrServiceLocator.getPrincipalHRAttributeService()
            .getPrincipalCalendar(principalId, calendarEntry.getEndPeriodFullDateTime().toLocalDate());

    //check to see if we are on a previous leave plan
    if (principalHRAttributes != null) {
        DateTime currentYearBeginDate = HrServiceLocator.getLeavePlanService()
                .getFirstDayOfLeavePlan(principalHRAttributes.getLeavePlan(), LocalDate.now());
        DateTime calEntryEndDate = calendarEntry.getEndPeriodFullDateTime();
        if (calEntryEndDate.getMillis() > currentYearBeginDate.getMillis()) {
            //current or future year
            LeaveSummary ls = LmServiceLocator.getLeaveSummaryService().getLeaveSummary(principalId,
                    calendarEntry);/*from   w w w .  j  a v  a2s  .  c o m*/
            leaveCalendarForm.setLeaveSummary(ls);
        } else {
            //current year roll over date has been passed, all previous calendars belong to the previous leave plan calendar year.
            DateTime effDate = HrServiceLocator.getLeavePlanService().getRolloverDayOfLeavePlan(
                    principalHRAttributes.getLeavePlan(), calEntryEndDate.minusDays(1).toLocalDate());
            LeaveSummary ls = LmServiceLocator.getLeaveSummaryService()
                    .getLeaveSummaryAsOfDateWithoutFuture(principalId, effDate.toLocalDate());
            //override title element (based on date passed in)
            DateFormat formatter = new SimpleDateFormat("MMMM d");
            DateFormat formatter2 = new SimpleDateFormat("MMMM d yyyy");
            DateTime entryEndDate = new LocalDateTime(calendarEntry.getEndPeriodDate()).toDateTime();
            if (entryEndDate.getHourOfDay() == 0) {
                entryEndDate = entryEndDate.minusDays(1);
            }
            String aString = formatter.format(calendarEntry.getBeginPeriodDate()) + " - "
                    + formatter2.format(entryEndDate.toDate());
            ls.setPendingDatesString(aString);
            DateTimeFormatter fmt = DateTimeFormat.forPattern("MMM d, yyyy");
            ls.setNote("Values as of: " + fmt.print(effDate));
            leaveCalendarForm.setLeaveSummary(ls);
        }
    }
}

From source file:org.kuali.kpme.tklm.leave.calendar.web.LeaveCalendarAction.java

License:Educational Community License

protected void setMessages(LeaveCalendarForm leaveCalendarForm, List<LeaveBlock> leaveBlocks) {
    String principalId = HrContext.getTargetPrincipalId();
    CalendarEntry calendarEntry = leaveCalendarForm.getCalendarEntry();
    PrincipalHRAttributes principalHRAttributes = HrServiceLocator.getPrincipalHRAttributeService()
            .getPrincipalCalendar(principalId, calendarEntry.getEndPeriodFullDateTime().toLocalDate());

    Map<String, Set<String>> allMessages = LeaveCalendarValidationUtil
            .getWarningMessagesForLeaveBlocks(leaveBlocks);

    // add warning message for accrual categories that have exceeded max balance.
    // Could set a flag on the transferable rows here so that LeaveCalendarSubmit.do knows
    // which row(s) to transfer when user submits the calendar for approval.
    List<BalanceTransfer> losses = new ArrayList<BalanceTransfer>();

    Interval calendarInterval = new Interval(calendarEntry.getBeginPeriodDate().getTime(),
            calendarEntry.getEndPeriodDate().getTime());
    Map<String, Set<LeaveBlock>> maxBalInfractions = new HashMap<String, Set<LeaveBlock>>();

    Date effectiveDate = LocalDate.now().toDate();
    if (!calendarInterval.contains(effectiveDate.getTime())) {
        effectiveDate = calendarEntry.getEndPeriodDate();
    }/*from  w  ww  . j av a2 s .c o  m*/

    if (principalHRAttributes != null) {
        maxBalInfractions = LmServiceLocator.getAccrualCategoryMaxBalanceService()
                .getMaxBalanceViolations(calendarEntry, principalId);

        LeaveSummary summary = leaveCalendarForm.getLeaveSummary();
        for (Entry<String, Set<LeaveBlock>> entry : maxBalInfractions.entrySet()) {
            for (LeaveBlock lb : entry.getValue()) {
                AccrualCategory accrualCat = HrServiceLocator.getAccrualCategoryService()
                        .getAccrualCategory(lb.getAccrualCategory(), lb.getLeaveLocalDate());
                AccrualCategoryRule aRule = HrServiceLocator.getAccrualCategoryRuleService()
                        .getAccrualCategoryRule(lb.getAccrualCategoryRuleId());
                if (StringUtils.equals(aRule.getActionAtMaxBalance(), HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
                    DateTime aDate = null;
                    if (StringUtils.equals(aRule.getMaxBalanceActionFrequency(),
                            HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)) {
                        aDate = HrServiceLocator.getLeavePlanService().getRolloverDayOfLeavePlan(
                                principalHRAttributes.getLeavePlan(), lb.getLeaveLocalDate());
                    } else {
                        Calendar cal = HrServiceLocator.getCalendarService().getCalendarByPrincipalIdAndDate(
                                principalId, new LocalDate(lb.getLeaveDate()), true);
                        CalendarEntry leaveEntry = HrServiceLocator.getCalendarEntryService()
                                .getCurrentCalendarEntryByCalendarId(cal.getHrCalendarId(),
                                        new DateTime(lb.getLeaveDate()));
                        aDate = new DateTime(leaveEntry.getEndPeriodDate());
                    }
                    aDate = aDate.minusDays(1);
                    if (calendarInterval.contains(aDate.getMillis())
                            && aDate.toDate().compareTo(calendarEntry.getEndPeriodDate()) <= 0) {
                        //may want to calculate summary for all rows, displayable or not, and determine displayability via tags.
                        AccrualCategory accrualCategory = HrServiceLocator.getAccrualCategoryService()
                                .getAccrualCategory(aRule.getLmAccrualCategoryId());
                        BigDecimal accruedBalance = LmServiceLocator.getAccrualService()
                                .getAccruedBalanceForPrincipal(principalId, accrualCategory,
                                        lb.getLeaveLocalDate());

                        BalanceTransfer loseTransfer = LmServiceLocator.getBalanceTransferService()
                                .initializeTransfer(principalId, lb.getAccrualCategoryRuleId(), accruedBalance,
                                        lb.getLeaveLocalDate());
                        boolean valid = BalanceTransferValidationUtils.validateTransfer(loseTransfer);
                        if (valid) {
                            losses.add(loseTransfer);
                        }
                    }
                } else if (StringUtils.equals(HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND,
                        aRule.getMaxBalanceActionFrequency())) {
                    if (calendarInterval.contains(lb.getLeaveDate().getTime())) {
                        // accrual categories within the leave plan that are hidden from the leave summary will not appear.
                        List<LeaveSummaryRow> summaryRows = summary.getLeaveSummaryRows();
                        List<LeaveSummaryRow> updatedSummaryRows = new ArrayList<LeaveSummaryRow>(
                                summaryRows.size());
                        //AccrualCategoryRule currentRule = HrServiceLocator.getAccrualCategoryRuleService().getAccrualCategoryRuleForDate(accrualCat, effectiveDate, principalCalendar.getServiceDate());
                        for (LeaveSummaryRow summaryRow : summaryRows) {
                            if (StringUtils.equals(summaryRow.getAccrualCategory(),
                                    accrualCat.getAccrualCategory())) {
                                if (StringUtils.equals(aRule.getActionAtMaxBalance(),
                                        HrConstants.ACTION_AT_MAX_BALANCE.PAYOUT)) {
                                    summaryRow.setPayoutable(true);
                                } else {
                                    if (StringUtils.equals(aRule.getActionAtMaxBalance(),
                                            HrConstants.ACTION_AT_MAX_BALANCE.TRANSFER)) {
                                        summaryRow.setTransferable(true);
                                    }
                                }

                                summaryRow.setInfractingLeaveBlockId(lb.getLmLeaveBlockId());
                            }
                            updatedSummaryRows.add(summaryRow);
                        }
                        summary.setLeaveSummaryRows(updatedSummaryRows);
                    }
                }

                if (calendarInterval.contains(lb.getLeaveDate().getTime())) {
                    // accrual categories within the leave plan that are hidden from the leave summary WILL appear.
                    String message = "You have exceeded the maximum balance limit for '"
                            + accrualCat.getAccrualCategory() + "' as of " + lb.getLeaveDate() + ". "
                            + "Depending upon the accrual category rules, leave over this limit may be forfeited.";
                    //  leave blocks are sorted in getMaxBalanceViolations() method, so we just take the one with the earliest leave date for an accrual category.
                    if (!StringUtils.contains(allMessages.get("warningMessages").toString(),
                            "You have exceeded the maximum balance limit for '"
                                    + accrualCat.getAccrualCategory())) {
                        allMessages.get("warningMessages").add(message);
                    }
                }
            }
        }
        leaveCalendarForm.setLeaveSummary(summary);
    }
    leaveCalendarForm.setForfeitures(losses);

    Map<String, Set<String>> transactionalMessages = LeaveCalendarValidationUtil.validatePendingTransactions(
            principalId, calendarEntry.getBeginPeriodFullDateTime().toLocalDate(),
            calendarEntry.getEndPeriodFullDateTime().toLocalDate());
    allMessages.get("infoMessages").addAll(transactionalMessages.get("infoMessages"));
    allMessages.get("warningMessages").addAll(transactionalMessages.get("warningMessages"));
    allMessages.get("actionMessages").addAll(transactionalMessages.get("actionMessages"));

    // add warning messages based on max carry over balances for each accrual category
    if (principalHRAttributes != null) {
        List<AccrualCategory> accrualCategories = HrServiceLocator.getAccrualCategoryService()
                .getActiveLeaveAccrualCategoriesForLeavePlan(principalHRAttributes.getLeavePlan(),
                        calendarEntry.getEndPeriodFullDateTime().toLocalDate());
        for (AccrualCategory accrualCategory : accrualCategories) {
            if (LmServiceLocator.getAccrualCategoryMaxCarryOverService().exceedsAccrualCategoryMaxCarryOver(
                    accrualCategory.getAccrualCategory(), principalId, calendarEntry,
                    calendarEntry.getEndPeriodFullDateTime().toLocalDate())) {
                String message = "Your pending leave balance is greater than the annual max carry over for accrual category '"
                        + accrualCategory.getAccrualCategory()
                        + "' and upon approval, the excess balance will be lost.";
                if (!allMessages.get("warningMessages").contains(message)) {
                    allMessages.get("warningMessages").add(message);
                }
            }
        }

        // KPME-1279 check for Absent Earn code to add warning.
        List<EarnCode> earnCodes = HrServiceLocator.getEarnCodeService().getEarnCodesForPrincipal(principalId,
                calendarEntry.getEndPeriodFullDateTime().toLocalDate(), true);
        if (earnCodes != null && !earnCodes.isEmpty()) {
            for (EarnCode earnCodeObj : earnCodes) {
                if (earnCodeObj != null) {
                    if ("Y".equalsIgnoreCase(earnCodeObj.getAffectPay())
                            && "N".equalsIgnoreCase(earnCodeObj.getEligibleForAccrual())) {
                        String message = "Absent time cannot be used until other accrual balances are zero or below a specified accrual balance.";
                        if (!allMessages.get("warningMessages").contains(message)) {
                            allMessages.get("warningMessages").add(message);
                            break;
                        }
                    }
                }
            }
        }
    }

    leaveCalendarForm.setWarningMessages(new ArrayList<String>(allMessages.get("warningMessages")));
    leaveCalendarForm.setInfoMessages(new ArrayList<String>(allMessages.get("infoMessages")));
    leaveCalendarForm.setActionMessages(new ArrayList<String>(allMessages.get("actionMessages")));
}

From source file:org.kuali.kpme.tklm.leave.summary.service.LeaveSummaryServiceImpl.java

License:Educational Community License

protected LeaveSummary getLeaveSummary(String principalId, LocalDate startDate, LocalDate endDate,
        String accrualCategory, boolean includeFuture) {
    LeaveSummary ls = new LeaveSummary();
    List<LeaveSummaryRow> rows = new ArrayList<LeaveSummaryRow>();

    if (StringUtils.isEmpty(principalId) || startDate == null || endDate == null) {
        return ls;
    }/*from   ww w. j  a va2s .  c  o  m*/

    Set<String> leavePlans = getLeavePlans(principalId, startDate, endDate);
    PrincipalHRAttributes pha = getPrincipalHrAttributes(principalId, startDate, endDate);
    if (CollectionUtils.isNotEmpty(leavePlans)) {
        for (String aLpString : leavePlans) {
            LeavePlan lp = HrServiceLocator.getLeavePlanService().getLeavePlan(aLpString, startDate);
            if (lp == null) {
                continue;
            }
            DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM d");
            DateTimeFormatter formatter2 = DateTimeFormat.forPattern("MMMM d yyyy");
            DateTime entryEndDate = endDate.toDateTimeAtStartOfDay();
            if (entryEndDate.getHourOfDay() == 0) {
                entryEndDate = entryEndDate.minusDays(1);
            }
            String aString = formatter.print(startDate) + " - " + formatter2.print(entryEndDate);
            ls.setPendingDatesString(aString);

            LeaveCalendarDocumentHeader approvedLcdh = LmServiceLocator.getLeaveCalendarDocumentHeaderService()
                    .getMaxEndDateApprovedLeaveCalendar(principalId);
            if (approvedLcdh != null) {
                DateTime endApprovedDate = approvedLcdh.getEndDateTime();
                LocalDateTime aLocalTime = approvedLcdh.getEndDateTime().toLocalDateTime();
                DateTime endApprovedTime = aLocalTime
                        .toDateTime(HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback());
                if (endApprovedTime.getHourOfDay() == 0) {
                    endApprovedDate = endApprovedDate.minusDays(1);
                }
                String datesString = formatter.print(approvedLcdh.getBeginDateTime()) + " - "
                        + formatter2.print(endApprovedDate);
                ls.setYtdDatesString(datesString);
            }

            //until we have something that creates carry over, we need to grab everything.
            // Calculating leave bLocks from Calendar Year start instead of Service Date
            Map<String, LeaveBlock> carryOverBlocks = getLeaveBlockService().getLastCarryOverBlocks(principalId,
                    startDate);

            boolean filterByAccrualCategory = false;
            if (StringUtils.isNotEmpty(accrualCategory)) {
                filterByAccrualCategory = true;
                //remove unwanted carry over blocks from map
                LeaveBlock carryOverBlock = carryOverBlocks.get(accrualCategory);
                carryOverBlocks = new HashMap<String, LeaveBlock>(1);
                if (ObjectUtils.isNotNull(carryOverBlock))
                    carryOverBlocks.put(carryOverBlock.getAccrualCategory(), carryOverBlock);
            }
            List<LeaveBlock> leaveBlocks = getLeaveBlockService().getLeaveBlocksSinceCarryOver(principalId,
                    carryOverBlocks, endDate, filterByAccrualCategory);

            List<LeaveBlock> futureLeaveBlocks = new ArrayList<LeaveBlock>();
            if (includeFuture) {
                if (!filterByAccrualCategory) {
                    futureLeaveBlocks = getLeaveBlockService().getLeaveBlocks(principalId, endDate,
                            endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())));
                } else {
                    futureLeaveBlocks = getLeaveBlockService().getLeaveBlocksWithAccrualCategory(principalId,
                            endDate, endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())),
                            accrualCategory);
                }
            }
            Map<String, List<LeaveBlock>> leaveBlockMap = mapLeaveBlocksByAccrualCategory(leaveBlocks);
            Map<String, List<LeaveBlock>> futureLeaveBlockMap = mapLeaveBlocksByAccrualCategory(
                    futureLeaveBlocks);
            List<AccrualCategory> acList = HrServiceLocator.getAccrualCategoryService()
                    .getActiveAccrualCategoriesForLeavePlan(lp.getLeavePlan(), endDate);
            if (CollectionUtils.isNotEmpty(acList)) {
                for (AccrualCategory ac : acList) {
                    if (ac.getShowOnGrid().equals("Y")) {

                        LeaveSummaryRow lsr = new LeaveSummaryRow();
                        lsr.setAccrualCategory(ac.getAccrualCategory());
                        lsr.setAccrualCategoryId(ac.getLmAccrualCategoryId());
                        //get max balances
                        AccrualCategoryRule acRule = HrServiceLocator.getAccrualCategoryRuleService()
                                .getAccrualCategoryRuleForDate(ac, endDate, pha.getServiceLocalDate());
                        //accrual category rule id set on a leave summary row will be useful in generating a relevant balance transfer
                        //document from the leave calendar display. Could put this id in the request for balance transfer document.
                        EmployeeOverride maxUsageOverride = LmServiceLocator.getEmployeeOverrideService()
                                .getEmployeeOverride(principalId, lp.getLeavePlan(), ac.getAccrualCategory(),
                                        "MU", endDate);

                        lsr.setAccrualCategoryRuleId(
                                acRule == null ? null : acRule.getLmAccrualCategoryRuleId());
                        if (acRule != null
                                && (acRule.getMaxBalance() != null || acRule.getMaxUsage() != null)) {
                            if (acRule.getMaxUsage() != null) {
                                lsr.setUsageLimit(new BigDecimal(acRule.getMaxUsage()).setScale(2));
                            } else {
                                lsr.setUsageLimit(null);
                            }

                        } else {
                            lsr.setUsageLimit(null);
                        }

                        if (maxUsageOverride != null)
                            lsr.setUsageLimit(new BigDecimal(maxUsageOverride.getOverrideValue()));

                        //Fetching leaveblocks for accCat with type CarryOver -- This is logic according to the CO blocks created from scheduler job.
                        BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                        lsr.setCarryOver(carryOver);

                        //handle up to current leave blocks
                        //CalendarEntry.getEndPeriodDate passed to fetch leave block amounts on last day of Calendar period
                        assignApprovedValuesToRow(lsr, ac.getAccrualCategory(),
                                leaveBlockMap.get(ac.getAccrualCategory()), lp, startDate, endDate);

                        //how about the leave blocks on the calendar entry being currently handled??
                        /*                            if(carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                                                       LeaveBlock carryOverBlock = carryOverBlocks.get(lsr.getAccrualCategory());
                                                       DateTime carryOverBlockLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), carryOverBlock.getLeaveDate());
                                                       DateTime currentLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), TKUtils.getCurrentDate());
                                                       if(carryOverBlockLPStart.equals(currentLPStart))
                          carryOver = carryOverBlock.getLeaveAmount();
                                                    }*/
                        //figure out past carry over values!!!
                        //We now have list of past years accrual and use (with ordered keys!!!)

                        //merge key sets
                        if (carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                            carryOver = carryOverBlocks.get(lsr.getAccrualCategory()).getLeaveAmount();
                            carryOver = carryOver.setScale(2);
                        }
                        Set<String> keyset = new HashSet<String>();
                        keyset.addAll(lsr.getPriorYearsUsage().keySet());
                        keyset.addAll(lsr.getPriorYearsTotalAccrued().keySet());
                        for (String key : keyset) {
                            BigDecimal value = lsr.getPriorYearsTotalAccrued().get(key);
                            if (value == null) {
                                value = BigDecimal.ZERO;
                            }
                            carryOver = carryOver.add(value);
                            BigDecimal use = lsr.getPriorYearsUsage().containsKey(key)
                                    ? lsr.getPriorYearsUsage().get(key)
                                    : BigDecimal.ZERO;
                            carryOver = carryOver.add(use);
                            EmployeeOverride carryOverOverride = LmServiceLocator.getEmployeeOverrideService()
                                    .getEmployeeOverride(principalId, lp.getLeavePlan(),
                                            ac.getAccrualCategory(), "MAC", endDate);
                            if (acRule != null && acRule.getMaxCarryOver() != null) {
                                BigDecimal carryOverDisplay = BigDecimal.ZERO;
                                if (carryOverOverride != null)
                                    carryOverDisplay = new BigDecimal(
                                            carryOverOverride.getOverrideValue() < carryOver.longValue()
                                                    ? carryOverOverride.getOverrideValue()
                                                    : carryOver.longValue());
                                else
                                    carryOverDisplay = new BigDecimal(
                                            acRule.getMaxCarryOver() < carryOver.longValue()
                                                    ? acRule.getMaxCarryOver()
                                                    : carryOver.longValue());
                                carryOver = carryOverDisplay;
                            }
                        }

                        lsr.setCarryOver(carryOver);
                        if (acRule != null && acRule.getMaxCarryOver() != null) {
                            EmployeeOverride carryOverOverride = LmServiceLocator.getEmployeeOverrideService()
                                    .getEmployeeOverride(principalId, lp.getLeavePlan(),
                                            ac.getAccrualCategory(), "MAC", endDate);
                            if (carryOverOverride != null)
                                lsr.setMaxCarryOver(new BigDecimal(carryOverOverride.getOverrideValue()));
                            else
                                lsr.setMaxCarryOver(
                                        new BigDecimal(acRule.getMaxCarryOver() < carryOver.longValue()
                                                ? acRule.getMaxCarryOver()
                                                : carryOver.longValue()));
                        }

                        //handle future leave blocks
                        assignPendingValuesToRow(lsr, ac.getAccrualCategory(),
                                futureLeaveBlockMap.get(ac.getAccrualCategory()));

                        //compute Leave Balance
                        BigDecimal leaveBalance = lsr.getAccruedBalance()
                                .subtract(lsr.getPendingLeaveRequests());
                        //if leave balance is set
                        //Employee overrides have already been taken into consideration and the appropriate values
                        //for usage have been set by this point.
                        //                            if (acRule != null && StringUtils.equals(acRule.getMaxBalFlag(), "Y")) {
                        //there exists an accrual category rule with max balance limit imposed.
                        //max bal flag = 'Y' has no precedence here with max-bal / balance transfers implemented.
                        //unless institutions are not required to define a max balance limit for action_at_max_bal = LOSE.
                        //Possibly preferable to procure forfeiture blocks through balance transfer
                        if (lsr.getUsageLimit() != null) { //should not set leave balance to usage limit simply because it's not null.
                            BigDecimal availableUsage = lsr.getUsageLimit()
                                    .subtract(lsr.getYtdApprovedUsage().add(lsr.getPendingLeaveRequests()));
                            if (leaveBalance.compareTo(availableUsage) > 0)
                                lsr.setLeaveBalance(availableUsage);
                            else
                                lsr.setLeaveBalance(leaveBalance);
                        } else { //no usage limit
                            lsr.setLeaveBalance(leaveBalance);
                        }

                        rows.add(lsr);
                    }
                }
                // let's check for 'empty' accrual categories
                if (leaveBlockMap.containsKey(null) || futureLeaveBlockMap.containsKey(null)) {
                    LeaveSummaryRow otherLeaveSummary = new LeaveSummaryRow();
                    //otherLeaveSummary.setAccrualCategory("Other");

                    assignApprovedValuesToRow(otherLeaveSummary, null, leaveBlockMap.get(null), lp, startDate,
                            endDate);
                    BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                    for (Map.Entry<String, BigDecimal> entry : otherLeaveSummary.getPriorYearsTotalAccrued()
                            .entrySet()) {
                        carryOver = carryOver.add(entry.getValue());
                        BigDecimal use = otherLeaveSummary.getPriorYearsUsage().containsKey(entry.getKey())
                                ? otherLeaveSummary.getPriorYearsUsage().get(entry.getKey())
                                : BigDecimal.ZERO;
                        carryOver = carryOver.add(use);
                    }
                    otherLeaveSummary.setCarryOver(carryOver);
                    assignPendingValuesToRow(otherLeaveSummary, null, futureLeaveBlockMap.get(null));
                    otherLeaveSummary.setAccrualCategory("Other");

                    //compute Leave Balance
                    // blank the avail
                    otherLeaveSummary.setUsageLimit(null);
                    otherLeaveSummary.setLeaveBalance(null);

                    rows.add(otherLeaveSummary);
                }
            }
        }
    }
    ls.setLeaveSummaryRows(rows);
    return ls;
}