Example usage for org.joda.time LocalDate isEqual

List of usage examples for org.joda.time LocalDate isEqual

Introduction

In this page you can find the example usage for org.joda.time LocalDate isEqual.

Prototype

public boolean isEqual(ReadablePartial partial) 

Source Link

Document

Is this partial the same as the specified partial.

Usage

From source file:com.gst.portfolio.loanaccount.loanschedule.domain.AbstractLoanScheduleGenerator.java

License:Apache License

/**
 * calculates Interest stating date as per the settings
 * /*from   ww  w.j a  v a 2 s.c o m*/
 * @param firstRepaymentdate
 *            TODO
 * @param boolean1
 * @param localDate
 */
private LocalDate calculateInterestStartDateForPeriod(final LoanApplicationTerms loanApplicationTerms,
        LocalDate periodStartDate, final LocalDate idealDisbursementDate, final LocalDate firstRepaymentdate,
        final Boolean isInterestChargedFromDateSameAsDisbursalDateEnabled,
        final LocalDate expectedDisbursementDate) {
    LocalDate periodStartDateApplicableForInterest = periodStartDate;
    if (periodStartDate.isBefore(idealDisbursementDate) || firstRepaymentdate.isAfter(periodStartDate)) {
        if (loanApplicationTerms.getInterestChargedFromLocalDate() != null) {
            if (periodStartDate.isEqual(loanApplicationTerms.getExpectedDisbursementDate())
                    || loanApplicationTerms.getInterestChargedFromLocalDate().isAfter(periodStartDate)) {
                periodStartDateApplicableForInterest = loanApplicationTerms.getInterestChargedFromLocalDate();
            }
        } else if (loanApplicationTerms.getInterestChargedFromLocalDate() == null
                && isInterestChargedFromDateSameAsDisbursalDateEnabled) {
            periodStartDateApplicableForInterest = expectedDisbursementDate;
        } else if (periodStartDate.isEqual(loanApplicationTerms.getExpectedDisbursementDate())) {
            periodStartDateApplicableForInterest = idealDisbursementDate;
        }
    }
    return periodStartDateApplicableForInterest;
}

From source file:com.gst.portfolio.loanaccount.loanschedule.domain.AbstractLoanScheduleGenerator.java

License:Apache License

private LoanScheduleDTO rescheduleNextInstallments(final MathContext mc,
        final LoanApplicationTerms loanApplicationTerms, Loan loan, final HolidayDetailDTO holidayDetailDTO,
        final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor,
        final LocalDate rescheduleFrom, final LocalDate scheduleTillDate) {
    // Loan transactions to process and find the variation on payments
    Collection<RecalculationDetail> recalculationDetails = new ArrayList<>();
    List<LoanTransaction> transactions = loan.getLoanTransactions();
    for (LoanTransaction loanTransaction : transactions) {
        if (loanTransaction.isPaymentTransaction()) {
            recalculationDetails.add(new RecalculationDetail(loanTransaction.getTransactionDate(),
                    LoanTransaction.copyTransactionProperties(loanTransaction)));
        }/*from w w w .ja v  a  2  s  .  com*/
    }
    final boolean applyInterestRecalculation = loanApplicationTerms.isInterestRecalculationEnabled();

    LoanScheduleParams loanScheduleParams = null;
    Collection<LoanScheduleModelPeriod> periods = new ArrayList<>();
    final List<LoanRepaymentScheduleInstallment> retainedInstallments = new ArrayList<>();

    // this block is to retain the schedule installments prior to the
    // provided date and creates late and early payment details for further
    // calculations
    if (rescheduleFrom != null) {
        Money principalToBeScheduled = getPrincipalToBeScheduled(loanApplicationTerms);
        // actual outstanding balance for interest calculation
        Money outstandingBalance = principalToBeScheduled;
        // total outstanding balance as per rest for interest calculation.
        Money outstandingBalanceAsPerRest = outstandingBalance;

        // this is required to update total fee amounts in the
        // LoanScheduleModel
        final BigDecimal chargesDueAtTimeOfDisbursement = deriveTotalChargesDueAtTimeOfDisbursement(
                loan.charges());
        periods = createNewLoanScheduleListWithDisbursementDetails(
                loanApplicationTerms.fetchNumberOfRepaymentsAfterExceptions(), loanApplicationTerms,
                chargesDueAtTimeOfDisbursement);
        MonetaryCurrency currency = outstandingBalance.getCurrency();

        // early payments will be added here and as per the selected
        // strategy
        // action will be performed on this value
        Money reducePrincipal = outstandingBalanceAsPerRest.zero();

        Money uncompoundedAmount = outstandingBalanceAsPerRest.zero();
        // principal changes will be added along with date(after applying
        // rest)
        // from when these amounts will effect the outstanding balance for
        // interest calculation
        final Map<LocalDate, Money> principalPortionMap = new HashMap<>();
        // compounding(principal) amounts will be added along with
        // date(after applying compounding frequency)
        // from when these amounts will effect the outstanding balance for
        // interest calculation
        final Map<LocalDate, Money> latePaymentMap = new HashMap<>();

        // compounding(interest/Fee) amounts will be added along with
        // date(after applying compounding frequency)
        // from when these amounts will effect the outstanding balance for
        // interest calculation
        final TreeMap<LocalDate, Money> compoundingMap = new TreeMap<>();
        final Map<LocalDate, Map<LocalDate, Money>> compoundingDateVariations = new HashMap<>();
        LocalDate currentDate = DateUtils.getLocalDateOfTenant();
        LocalDate lastRestDate = currentDate;
        if (loanApplicationTerms.isInterestRecalculationEnabled()) {
            lastRestDate = getNextRestScheduleDate(currentDate.minusDays(1), loanApplicationTerms,
                    holidayDetailDTO);
        }
        LocalDate actualRepaymentDate = loanApplicationTerms.getExpectedDisbursementDate();
        boolean isFirstRepayment = true;

        // cumulative fields
        Money totalCumulativePrincipal = principalToBeScheduled.zero();
        Money totalCumulativeInterest = principalToBeScheduled.zero();
        Money totalFeeChargesCharged = principalToBeScheduled.zero().plus(chargesDueAtTimeOfDisbursement);
        Money totalPenaltyChargesCharged = principalToBeScheduled.zero();
        Money totalRepaymentExpected = principalToBeScheduled.zero();

        // Actual period Number as per the schedule
        int periodNumber = 1;
        // Actual period Number plus interest only repayments
        int instalmentNumber = 1;
        LocalDate lastInstallmentDate = actualRepaymentDate;
        LocalDate periodStartDate = loanApplicationTerms.getExpectedDisbursementDate();
        // Set fixed Amortization Amounts(either EMI or Principal )
        updateAmortization(mc, loanApplicationTerms, periodNumber, outstandingBalance);

        // count periods without interest grace to exclude for flat loan calculations

        final Map<LocalDate, Money> disburseDetailMap = new HashMap<>();
        if (loanApplicationTerms.isMultiDisburseLoan()) {
            // fetches the first tranche amount and also updates other
            // tranche
            // details to map
            BigDecimal disburseAmt = getDisbursementAmount(loanApplicationTerms,
                    loanApplicationTerms.getExpectedDisbursementDate(), periods, chargesDueAtTimeOfDisbursement,
                    disburseDetailMap, true);
            outstandingBalance = outstandingBalance.zero().plus(disburseAmt);
            outstandingBalanceAsPerRest = outstandingBalance;
            principalToBeScheduled = principalToBeScheduled.zero().plus(disburseAmt);
        }
        int loanTermInDays = 0;

        List<LoanTermVariationsData> exceptionDataList = loanApplicationTerms.getLoanTermVariations()
                .getExceptionData();
        final ListIterator<LoanTermVariationsData> exceptionDataListIterator = exceptionDataList.listIterator();
        LoanTermVariationParams loanTermVariationParams = null;

        // identify retain installments
        final List<LoanRepaymentScheduleInstallment> processInstallmentsInstallments = fetchRetainedInstallments(
                loan.getRepaymentScheduleInstallments(), rescheduleFrom, currency);
        final List<LoanRepaymentScheduleInstallment> newRepaymentScheduleInstallments = new ArrayList<>();

        // Block process the installment and creates the period if it falls
        // before reschedule from date
        // This will create the recalculation details by applying the
        // transactions
        for (LoanRepaymentScheduleInstallment installment : processInstallmentsInstallments) {
            // this will generate the next schedule due date and allows to
            // process the installment only if recalculate from date is
            // greater than due date
            if (installment.getDueDate().isAfter(lastInstallmentDate)) {
                if (totalCumulativePrincipal
                        .isGreaterThanOrEqualTo(loanApplicationTerms.getTotalDisbursedAmount())) {
                    break;
                }
                ArrayList<LoanTermVariationsData> dueDateVariationsDataList = new ArrayList<>();

                // check for date changes

                do {
                    actualRepaymentDate = this.scheduledDateGenerator.generateNextRepaymentDate(
                            actualRepaymentDate, loanApplicationTerms, isFirstRepayment, holidayDetailDTO);
                    isFirstRepayment = false;
                    lastInstallmentDate = this.scheduledDateGenerator.adjustRepaymentDate(actualRepaymentDate,
                            loanApplicationTerms, holidayDetailDTO);
                    while (loanApplicationTerms.getLoanTermVariations()
                            .hasDueDateVariation(lastInstallmentDate)) {
                        LoanTermVariationsData variation = loanApplicationTerms.getLoanTermVariations()
                                .nextDueDateVariation();
                        if (!variation.isSpecificToInstallment()) {
                            actualRepaymentDate = variation.getDateValue();
                            /*if (!isDueDateChangeApplied) {
                            previousRepaymentDate = actualRepaymentDate;
                            isDueDateChangeApplied = true;
                            }*/
                            lastInstallmentDate = actualRepaymentDate;
                        }
                        dueDateVariationsDataList.add(variation);
                    }
                    loanTermVariationParams = applyExceptionLoanTermVariations(loanApplicationTerms,
                            lastInstallmentDate, exceptionDataListIterator, instalmentNumber,
                            totalCumulativePrincipal, totalCumulativeInterest, mc);
                } while (loanTermVariationParams != null && loanTermVariationParams.isSkipPeriod());

                /*if (!lastInstallmentDate.isBefore(rescheduleFrom)) {
                actualRepaymentDate = previousRepaymentDate;
                if(isDueDateChangeApplied){
                    int numberOfDateChangesApplied = dueDateVariationsDataList.size();
                    while(numberOfDateChangesApplied >0 ){
                        loanApplicationTerms.getLoanTermVariations().previousDueDateVariation();
                        numberOfDateChangesApplied--;
                    }
                }
                break;
                }*/
                periodNumber++;

                for (LoanTermVariationsData dueDateVariation : dueDateVariationsDataList) {
                    dueDateVariation.setProcessed(true);
                }

                if (loanTermVariationParams != null && loanTermVariationParams.isSkipPeriod()) {
                    ArrayList<LoanTermVariationsData> variationsDataList = loanTermVariationParams
                            .getVariationsDataList();
                    for (LoanTermVariationsData variationsData : variationsDataList) {
                        variationsData.setProcessed(true);
                    }
                }
            }

            for (Map.Entry<LocalDate, Money> disburseDetail : disburseDetailMap.entrySet()) {
                if (disburseDetail.getKey().isAfter(installment.getFromDate())
                        && !disburseDetail.getKey().isAfter(installment.getDueDate())) {
                    // creates and add disbursement detail to the repayments
                    // period
                    final LoanScheduleModelDisbursementPeriod disbursementPeriod = LoanScheduleModelDisbursementPeriod
                            .disbursement(disburseDetail.getKey(), disburseDetail.getValue(),
                                    chargesDueAtTimeOfDisbursement);
                    periods.add(disbursementPeriod);
                    // updates actual outstanding balance with new
                    // disbursement detail
                    outstandingBalance = outstandingBalance.plus(disburseDetail.getValue());
                    principalToBeScheduled = principalToBeScheduled.plus(disburseDetail.getValue());
                }
            }

            // calculation of basic fields to start the schedule generation
            // from the middle
            periodStartDate = installment.getDueDate();
            installment.resetDerivedComponents();
            newRepaymentScheduleInstallments.add(installment);
            outstandingBalance = outstandingBalance.minus(installment.getPrincipal(currency));
            final LoanScheduleModelPeriod loanScheduleModelPeriod = createLoanScheduleModelPeriod(installment,
                    outstandingBalance);
            periods.add(loanScheduleModelPeriod);
            totalCumulativePrincipal = totalCumulativePrincipal.plus(installment.getPrincipal(currency));
            totalCumulativeInterest = totalCumulativeInterest.plus(installment.getInterestCharged(currency));
            totalFeeChargesCharged = totalFeeChargesCharged.plus(installment.getFeeChargesCharged(currency));
            totalPenaltyChargesCharged = totalPenaltyChargesCharged
                    .plus(installment.getPenaltyChargesCharged(currency));
            instalmentNumber++;
            loanTermInDays = Days.daysBetween(installment.getFromDate(), installment.getDueDate()).getDays();

            if (loanApplicationTerms.isInterestRecalculationEnabled()) {

                // populates the collection with transactions till the due
                // date
                // of
                // the period for interest recalculation enabled loans
                Collection<RecalculationDetail> applicableTransactions = getApplicableTransactionsForPeriod(
                        applyInterestRecalculation, installment.getDueDate(), recalculationDetails);

                // calculates the expected principal value for this
                // repayment
                // schedule
                Money principalPortionCalculated = principalToBeScheduled.zero();
                if (!installment.isRecalculatedInterestComponent()) {
                    principalPortionCalculated = calculateExpectedPrincipalPortion(
                            installment.getInterestCharged(currency), loanApplicationTerms);
                }

                // expected principal considering the previously paid excess
                // amount
                Money actualPrincipalPortion = principalPortionCalculated.minus(reducePrincipal);
                if (actualPrincipalPortion.isLessThanZero()) {
                    actualPrincipalPortion = principalPortionCalculated.zero();
                }

                Money unprocessed = updateEarlyPaidAmountsToMap(loanApplicationTerms, holidayDetailDTO,
                        loanRepaymentScheduleTransactionProcessor, newRepaymentScheduleInstallments, currency,
                        principalPortionMap, installment, applicableTransactions, actualPrincipalPortion);

                // this block is to adjust the period number based on the
                // actual
                // schedule due date and installment due date
                // recalculatedInterestComponent installment shouldn't be
                // considered while calculating fixed EMI amounts
                int period = periodNumber;
                if (!lastInstallmentDate.isEqual(installment.getDueDate())) {
                    period--;
                }
                reducePrincipal = fetchEarlyPaidAmount(installment.getPrincipal(currency),
                        principalPortionCalculated, reducePrincipal, loanApplicationTerms,
                        totalCumulativePrincipal, period, mc);
                // Updates principal paid map with efective date for
                // reducing
                // the amount from outstanding balance(interest calculation)
                LocalDate amountApplicableDate = null;
                if (loanApplicationTerms.getRestCalendarInstance() != null) {
                    amountApplicableDate = getNextRestScheduleDate(installment.getDueDate().minusDays(1),
                            loanApplicationTerms, holidayDetailDTO);
                }

                // updates map with the installment principal amount
                // excluding
                // unprocessed amount since this amount is already
                // accounted.
                updateMapWithAmount(principalPortionMap, installment.getPrincipal(currency).minus(unprocessed),
                        amountApplicableDate);
                uncompoundedAmount = updateCompoundingDetailsForPartialScheduleGeneration(installment,
                        loanApplicationTerms, principalPortionMap, compoundingDateVariations,
                        uncompoundedAmount, applicableTransactions, lastRestDate, holidayDetailDTO);

                // update outstanding balance for interest calculation
                outstandingBalanceAsPerRest = updateBalanceForInterestCalculation(principalPortionMap,
                        installment.getDueDate(), outstandingBalanceAsPerRest, false);
                outstandingBalanceAsPerRest = updateBalanceForInterestCalculation(disburseDetailMap,
                        installment.getDueDate(), outstandingBalanceAsPerRest, true);
                // updates the map with over due amounts
                updateLatePaymentsToMap(loanApplicationTerms, holidayDetailDTO, currency, latePaymentMap,
                        lastInstallmentDate, newRepaymentScheduleInstallments, true, lastRestDate);
            } else {
                outstandingBalanceAsPerRest = outstandingBalance;
            }
        }
        totalRepaymentExpected = totalCumulativePrincipal.plus(totalCumulativeInterest)
                .plus(totalFeeChargesCharged).plus(totalPenaltyChargesCharged);

        // for partial schedule generation
        if (!newRepaymentScheduleInstallments.isEmpty() && totalCumulativeInterest.isGreaterThanZero()) {
            Money totalOutstandingInterestPaymentDueToGrace = Money.zero(currency);
            loanScheduleParams = LoanScheduleParams.createLoanScheduleParamsForPartialUpdate(periodNumber,
                    instalmentNumber, loanTermInDays, periodStartDate, actualRepaymentDate,
                    totalCumulativePrincipal, totalCumulativeInterest, totalFeeChargesCharged,
                    totalPenaltyChargesCharged, totalRepaymentExpected,
                    totalOutstandingInterestPaymentDueToGrace, reducePrincipal, principalPortionMap,
                    latePaymentMap, compoundingMap, uncompoundedAmount, disburseDetailMap,
                    principalToBeScheduled, outstandingBalance, outstandingBalanceAsPerRest,
                    newRepaymentScheduleInstallments, recalculationDetails,
                    loanRepaymentScheduleTransactionProcessor, scheduleTillDate, currency,
                    applyInterestRecalculation);
            retainedInstallments.addAll(newRepaymentScheduleInstallments);
            loanScheduleParams.getCompoundingDateVariations().putAll(compoundingDateVariations);
            loanApplicationTerms.updateTotalInterestDue(
                    Money.of(currency, loan.getLoanSummary().getTotalInterestCharged()));
        } else {
            loanApplicationTerms.getLoanTermVariations().resetVariations();
        }

    }
    // for complete schedule generation
    if (loanScheduleParams == null) {
        loanScheduleParams = LoanScheduleParams.createLoanScheduleParamsForCompleteUpdate(recalculationDetails,
                loanRepaymentScheduleTransactionProcessor, scheduleTillDate, applyInterestRecalculation);
        periods.clear();
    }
    LoanScheduleModel loanScheduleModel = generate(mc, loanApplicationTerms, loan.charges(), holidayDetailDTO,
            loanScheduleParams);
    for (LoanScheduleModelPeriod loanScheduleModelPeriod : loanScheduleModel.getPeriods()) {
        if (loanScheduleModelPeriod.isRepaymentPeriod()) {
            // adding newly created repayment periods to installments
            addLoanRepaymentScheduleInstallment(retainedInstallments, loanScheduleModelPeriod);
        }
    }
    periods.addAll(loanScheduleModel.getPeriods());
    LoanScheduleModel loanScheduleModelwithPeriodChanges = LoanScheduleModel
            .withLoanScheduleModelPeriods(periods, loanScheduleModel);
    return LoanScheduleDTO.from(retainedInstallments, loanScheduleModelwithPeriodChanges);
}

From source file:com.gst.portfolio.loanaccount.loanschedule.domain.DefaultScheduledDateGenerator.java

License:Apache License

@Override
public Boolean isDateFallsInSchedule(final PeriodFrequencyType frequency, final int repaidEvery,
        final LocalDate startDate, final LocalDate date) {
    boolean isScheduledDate = false;
    switch (frequency) {
    case DAYS:/*  w ww .  ja va2s. com*/
        int diff = Days.daysBetween(startDate, date).getDays();
        isScheduledDate = (diff % repaidEvery) == 0;
        break;
    case WEEKS:
        int weekDiff = Weeks.weeksBetween(startDate, date).getWeeks();
        isScheduledDate = (weekDiff % repaidEvery) == 0;
        if (isScheduledDate) {
            LocalDate modifiedDate = startDate.plusWeeks(weekDiff);
            isScheduledDate = modifiedDate.isEqual(date);
        }
        break;
    case MONTHS:
        int monthDiff = Months.monthsBetween(startDate, date).getMonths();
        isScheduledDate = (monthDiff % repaidEvery) == 0;
        if (isScheduledDate) {
            LocalDate modifiedDate = startDate.plusMonths(monthDiff);
            isScheduledDate = modifiedDate.isEqual(date);
        }
        break;
    case YEARS:
        int yearDiff = Years.yearsBetween(startDate, date).getYears();
        isScheduledDate = (yearDiff % repaidEvery) == 0;
        if (isScheduledDate) {
            LocalDate modifiedDate = startDate.plusYears(yearDiff);
            isScheduledDate = modifiedDate.isEqual(date);
        }
        break;
    case INVALID:
        break;
    }
    return isScheduledDate;
}

From source file:com.gst.portfolio.loanaccount.loanschedule.domain.LoanApplicationTerms.java

License:Apache License

public BigDecimal calculatePeriodsBetweenDates(final LocalDate startDate, final LocalDate endDate) {
    BigDecimal numberOfPeriods = BigDecimal.ZERO;
    switch (this.repaymentPeriodFrequencyType) {
    case DAYS:/*w w  w.ja v  a 2  s  .c  om*/
        int numOfDays = Days.daysBetween(startDate, endDate).getDays();
        numberOfPeriods = BigDecimal.valueOf((double) numOfDays);
        break;
    case WEEKS:
        int numberOfWeeks = Weeks.weeksBetween(startDate, endDate).getWeeks();
        int daysLeftAfterWeeks = Days.daysBetween(startDate.plusWeeks(numberOfWeeks), endDate).getDays();
        numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfWeeks))
                .add(BigDecimal.valueOf((double) daysLeftAfterWeeks / 7));
        break;
    case MONTHS:
        int numberOfMonths = Months.monthsBetween(startDate, endDate).getMonths();
        LocalDate startDateAfterConsideringMonths = null;
        LocalDate endDateAfterConsideringMonths = null;
        int diffDays = 0;
        if (this.loanCalendar == null) {
            startDateAfterConsideringMonths = startDate.plusMonths(numberOfMonths);
            startDateAfterConsideringMonths = CalendarUtils.adjustDate(startDateAfterConsideringMonths,
                    getSeedDate(), this.repaymentPeriodFrequencyType);
            endDateAfterConsideringMonths = startDate.plusMonths(numberOfMonths + 1);
            endDateAfterConsideringMonths = CalendarUtils.adjustDate(endDateAfterConsideringMonths,
                    getSeedDate(), this.repaymentPeriodFrequencyType);
        } else {
            LocalDate expectedStartDate = startDate;
            if (!CalendarUtils.isValidRedurringDate(loanCalendar.getRecurrence(),
                    loanCalendar.getStartDateLocalDate().minusMonths(getRepaymentEvery()), startDate)) {
                expectedStartDate = CalendarUtils.getNewRepaymentMeetingDate(loanCalendar.getRecurrence(),
                        startDate.minusMonths(getRepaymentEvery()), startDate.minusMonths(getRepaymentEvery()),
                        getRepaymentEvery(),
                        CalendarUtils
                                .getMeetingFrequencyFromPeriodFrequencyType(getLoanTermPeriodFrequencyType()),
                        this.holidayDetailDTO.getWorkingDays(), isSkipRepaymentOnFirstDayOfMonth, numberOfDays);
            }
            if (!expectedStartDate.isEqual(startDate)) {
                diffDays = Days.daysBetween(startDate, expectedStartDate).getDays();
            }
            if (numberOfMonths == 0) {
                startDateAfterConsideringMonths = expectedStartDate;
            } else {
                startDateAfterConsideringMonths = CalendarUtils.getNewRepaymentMeetingDate(
                        loanCalendar.getRecurrence(), expectedStartDate,
                        expectedStartDate.plusMonths(numberOfMonths), getRepaymentEvery(),
                        CalendarUtils
                                .getMeetingFrequencyFromPeriodFrequencyType(getLoanTermPeriodFrequencyType()),
                        this.holidayDetailDTO.getWorkingDays(), isSkipRepaymentOnFirstDayOfMonth, numberOfDays);
            }
            endDateAfterConsideringMonths = CalendarUtils.getNewRepaymentMeetingDate(
                    loanCalendar.getRecurrence(), startDateAfterConsideringMonths,
                    startDateAfterConsideringMonths.plusDays(1), getRepaymentEvery(),
                    CalendarUtils.getMeetingFrequencyFromPeriodFrequencyType(getLoanTermPeriodFrequencyType()),
                    this.holidayDetailDTO.getWorkingDays(), isSkipRepaymentOnFirstDayOfMonth, numberOfDays);
        }
        int daysLeftAfterMonths = Days.daysBetween(startDateAfterConsideringMonths, endDate).getDays()
                + diffDays;
        int daysInPeriodAfterMonths = Days
                .daysBetween(startDateAfterConsideringMonths, endDateAfterConsideringMonths).getDays();
        numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfMonths))
                .add(BigDecimal.valueOf((double) daysLeftAfterMonths / daysInPeriodAfterMonths));
        break;
    case YEARS:
        int numberOfYears = Years.yearsBetween(startDate, endDate).getYears();
        LocalDate startDateAfterConsideringYears = startDate.plusYears(numberOfYears);
        LocalDate endDateAfterConsideringYears = startDate.plusYears(numberOfYears + 1);
        int daysLeftAfterYears = Days.daysBetween(startDateAfterConsideringYears, endDate).getDays();
        int daysInPeriodAfterYears = Days
                .daysBetween(startDateAfterConsideringYears, endDateAfterConsideringYears).getDays();
        numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfYears))
                .add(BigDecimal.valueOf((double) daysLeftAfterYears / daysInPeriodAfterYears));
        break;
    default:
        break;
    }
    return numberOfPeriods;
}

From source file:com.gst.portfolio.loanaccount.loanschedule.domain.LoanApplicationTerms.java

License:Apache License

private boolean isFallingInRepaymentPeriod(LocalDate fromDate, LocalDate toDate) {
    boolean isSameAsRepaymentPeriod = false;
    if (this.interestCalculationPeriodMethod.getValue()
            .equals(InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD.getValue())) {
        switch (this.repaymentPeriodFrequencyType) {
        case WEEKS:
            int days = Days.daysBetween(fromDate, toDate).getDays();
            isSameAsRepaymentPeriod = (days % 7) == 0;
            break;
        case MONTHS:
            boolean isFromDateOnEndDate = false;
            if (fromDate.getDayOfMonth() > fromDate.plusDays(1).getDayOfMonth()) {
                isFromDateOnEndDate = true;
            }//from  ww w.ja  v a  2s  . c o  m
            boolean isToDateOnEndDate = false;
            if (toDate.getDayOfMonth() > toDate.plusDays(1).getDayOfMonth()) {
                isToDateOnEndDate = true;
            }

            if (isFromDateOnEndDate && isToDateOnEndDate) {
                isSameAsRepaymentPeriod = true;
            } else {

                int months = getPeriodsBetween(fromDate, toDate);
                fromDate = fromDate.plusMonths(months);
                isSameAsRepaymentPeriod = fromDate.isEqual(toDate);
            }

            break;
        default:
            break;
        }
    }
    return isSameAsRepaymentPeriod;
}

From source file:com.gst.portfolio.savings.domain.DepositAccountTermAndPreClosure.java

License:Apache License

public Integer getActualDepositPeriod(final LocalDate interestPostingUpToDate,
        final SavingsPeriodFrequencyType periodFrequencyType) {
    LocalDate depositFromDate = getExpectedFirstDepositOnDate();

    if (depositFromDate == null)
        depositFromDate = this.account.accountSubmittedOrActivationDate();

    Integer actualDepositPeriod = this.depositPeriod;
    if (depositFromDate == null || getMaturityLocalDate() == null
            || interestPostingUpToDate.isEqual(getMaturityLocalDate())) {
        return actualDepositPeriod;
    }//from   w  w  w  . ja  va 2 s  . co m

    final SavingsPeriodFrequencyType depositPeriodFrequencyType = periodFrequencyType;
    switch (depositPeriodFrequencyType) {
    case DAYS:
        actualDepositPeriod = Days.daysBetween(depositFromDate, interestPostingUpToDate).getDays();
        break;
    case WEEKS:
        actualDepositPeriod = Weeks.weeksBetween(depositFromDate, interestPostingUpToDate).getWeeks();
        break;
    case MONTHS:
        actualDepositPeriod = Months.monthsBetween(depositFromDate, interestPostingUpToDate).getMonths();
        break;
    case YEARS:
        actualDepositPeriod = Years.yearsBetween(depositFromDate, interestPostingUpToDate).getYears();
        break;
    case INVALID:
        actualDepositPeriod = this.depositPeriod;// default value
        break;
    }
    return actualDepositPeriod;
}

From source file:com.gst.portfolio.savings.domain.SavingsHelper.java

License:Apache License

public List<LocalDateInterval> determineInterestPostingPeriods(
        final LocalDate startInterestCalculationLocalDate, final LocalDate interestPostingUpToDate,
        final SavingsPostingInterestPeriodType postingPeriodType, final Integer financialYearBeginningMonth,
        List<LocalDate> postInterestAsOn) {

    final List<LocalDateInterval> postingPeriods = new ArrayList<>();
    LocalDate periodStartDate = startInterestCalculationLocalDate;
    LocalDate periodEndDate = periodStartDate;
    LocalDate actualPeriodStartDate = periodStartDate;

    while (!periodStartDate.isAfter(interestPostingUpToDate)
            && !periodEndDate.isAfter(interestPostingUpToDate)) {

        final LocalDate interestPostingLocalDate = determineInterestPostingPeriodEndDateFrom(periodStartDate,
                postingPeriodType, interestPostingUpToDate, financialYearBeginningMonth);

        periodEndDate = interestPostingLocalDate.minusDays(1);

        if (!postInterestAsOn.isEmpty()) {
            for (LocalDate transactiondate : postInterestAsOn) {
                if (periodStartDate.isBefore(transactiondate)
                        && (periodEndDate.isAfter(transactiondate) || periodEndDate.isEqual(transactiondate))) {
                    periodEndDate = transactiondate.minusDays(1);
                    actualPeriodStartDate = periodEndDate;
                    break;
                }//from w ww.j a va  2s. c  o m
            }
        }

        postingPeriods.add(LocalDateInterval.create(periodStartDate, periodEndDate));

        if (actualPeriodStartDate.isEqual(periodEndDate)) {
            periodEndDate = actualPeriodStartDate.plusDays(1);
            periodStartDate = actualPeriodStartDate.plusDays(1);
        } else {
            periodEndDate = interestPostingLocalDate;
            periodStartDate = interestPostingLocalDate;
        }
    }

    return postingPeriods;
}

From source file:com.gst.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Override
public CommandProcessingResult close(final Long savingsId, final JsonCommand command) {
    final AppUser user = this.context.authenticatedUser();

    this.savingsAccountTransactionDataValidator.validateClosing(command);
    final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId);
    final boolean isLinkedWithAnyActiveLoan = this.accountAssociationsReadPlatformService
            .isLinkedWithAnyActiveAccount(savingsId);

    if (isLinkedWithAnyActiveLoan) {
        final String defaultUserMessage = "Closing savings account with id:" + savingsId
                + " is not allowed, since it is linked with one of the active accounts";
        throw new SavingsAccountClosingNotAllowedException("linked", defaultUserMessage, savingsId);
    }//from ww w  . j  a  v  a  2s. c  o  m

    entityDatatableChecksWritePlatformService.runTheCheckForProduct(savingsId, EntityTables.SAVING.getName(),
            StatusEnum.CLOSE.getCode().longValue(), EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(),
            account.productId());

    final boolean isWithdrawBalance = command.booleanPrimitiveValueOfParameterNamed(withdrawBalanceParamName);

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    final LocalDate closedDate = command
            .localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName);
    final boolean isPostInterest = command
            .booleanPrimitiveValueOfParameterNamed(SavingsApiConstants.postInterestValidationOnClosure);
    // postInterest(account,closedDate,flag);
    if (isPostInterest) {
        boolean postInterestOnClosingDate = false;
        List<SavingsAccountTransaction> savingTransactions = account.getTransactions();
        for (SavingsAccountTransaction savingTransaction : savingTransactions) {
            if (savingTransaction.isInterestPosting() && savingTransaction.isNotReversed()
                    && closedDate.isEqual(savingTransaction.getTransactionLocalDate())) {
                postInterestOnClosingDate = true;
                break;
            }
        }
        if (postInterestOnClosingDate == false) {
            throw new PostInterestClosingDateException();
        }
    }

    final Map<String, Object> changes = new LinkedHashMap<>();

    if (isWithdrawBalance
            && account.getSummary().getAccountBalance(account.getCurrency()).isGreaterThanZero()) {

        final BigDecimal transactionAmount = account.getSummary().getAccountBalance();

        final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService
                .createAndPersistPaymentDetail(command, changes);

        final boolean isAccountTransfer = false;
        final boolean isRegularTransaction = true;
        final boolean isApplyWithdrawFee = false;
        final boolean isInterestTransfer = false;
        final SavingsTransactionBooleanValues transactionBooleanValues = new SavingsTransactionBooleanValues(
                isAccountTransfer, isRegularTransaction, isApplyWithdrawFee, isInterestTransfer,
                isWithdrawBalance);

        this.savingsAccountDomainService.handleWithdrawal(account, fmt, closedDate, transactionAmount,
                paymentDetail, transactionBooleanValues);

    }

    final Map<String, Object> accountChanges = account.close(user, command, DateUtils.getLocalDateOfTenant());
    changes.putAll(accountChanges);
    if (!changes.isEmpty()) {
        this.savingAccountRepositoryWrapper.save(account);
        final String noteText = command.stringValueOfParameterNamed("note");
        if (StringUtils.isNotBlank(noteText)) {
            final Note note = Note.savingNote(account, noteText);
            changes.put("note", noteText);
            this.noteRepository.save(note);
        }

    }

    // disable all standing orders linked to the savings account
    this.disableStandingInstructionsLinkedToClosedSavings(account);
    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsId) //
            .with(changes) //
            .build();
}

From source file:com.qubit.solution.fenixedu.integration.ldap.service.LdapIntegration.java

License:Open Source License

@Atomic
private static void updatePerson(final Person person, final String instituionalEmail,
        final String personalEmail, final String birthDate, final String documentID, final String sex,
        final String givenNames, final String surnames) {

    // if (person.getDocumentIdNumber() != null &&
    // !person.getDocumentIdNumber().equals(documentID)) {
    // throw new IllegalStateException(
    // "Seems we are trying to update a person that does not match the ID.
    // This should not happen!");
    // }//from  w  ww.j a  va  2 s  . c om

    String institutionalEmailAddressValue = person.getInstitutionalEmailAddressValue();
    if (!StringUtils.isEmpty(instituionalEmail) && (institutionalEmailAddressValue == null
            || !institutionalEmailAddressValue.equals(instituionalEmail))) {
        person.setInstitutionalEmailAddressValue(instituionalEmail);
    }

    List<? extends PartyContact> personalEmails = person.getPartyContacts(EmailAddress.class,
            PartyContactType.PERSONAL);
    if (!StringUtils.isEmpty(personalEmail) && personalEmails.stream()
            .filter(email -> email.getPresentationValue().equals(personalEmail)).count() == 0) {
        EmailAddress.createEmailAddress(person, personalEmail, PartyContactType.PERSONAL, false);
    }

    if (!StringUtils.isEmpty(birthDate)) {
        String format = "yyyyMMddHHmmss'Z'";
        if (birthDate.contains(".")) {
            format = "yyyyMMddHHmmss.SSS'Z'";
        }
        LocalDate parseLocalDate = new DateTimeFormatterFactory(format).createDateTimeFormatter()
                .parseLocalDate(birthDate);
        YearMonthDay dateOfBirthYearMonthDay = person.getDateOfBirthYearMonthDay();
        if (dateOfBirthYearMonthDay == null || !parseLocalDate.isEqual(dateOfBirthYearMonthDay)) {
            YearMonthDay yearMonthDay = new YearMonthDay(parseLocalDate.getYear(),
                    parseLocalDate.getMonthOfYear(), parseLocalDate.getDayOfMonth());
            person.setDateOfBirthYearMonthDay(yearMonthDay);
        }
    }

    if (!StringUtils.isEmpty(documentID) && !person.getDocumentIdNumber().equals(documentID)) {
        person.setDocumentIdNumber(documentID);
    }

    if (!StringUtils.isEmpty(sex)) {
        Gender genderInLdap = "M".equals(sex) ? Gender.MALE : "F".equals(sex) ? Gender.FEMALE : null;
        if (genderInLdap != null && person.getGender() != genderInLdap) {
            person.setGender(genderInLdap);
        }
    }

    if (!StringUtils.isEmpty(givenNames) && !StringUtils.isEmpty(surnames)
            && !equalInAnyLanguage(person.getPartyName(), givenNames + " " + surnames)) {
        String displayName = givenNames.split(" ")[0] + " " + surnames.split(" ")[0];
        person.getProfile().changeName(givenNames, surnames, displayName);
    }

}

From source file:com.redhat.engineering.jenkins.report.plugin.ReportPluginPortlet.java

License:Open Source License

/**
 * Graph of duration of tests over time.
 *//* w w  w .j  a  va2 s. com*/
public Graph getSummaryGraph() {
    // The standard equals doesn't work because two LocalDate objects can
    // be differente even if the date is the same (different internal timestamp)
    Comparator<LocalDate> localDateComparator = new Comparator<LocalDate>() {

        @Override
        public int compare(LocalDate d1, LocalDate d2) {
            if (d1.isEqual(d2)) {
                return 0;
            }
            if (d1.isAfter(d2)) {
                return 1;
            }
            return -1;
        }
    };

    // We need a custom comparator for LocalDate objects
    final Map<LocalDate, TestResultAggrSummary> summaries = //new HashMap<LocalDate, TestResultSummary>();
            new TreeMap<LocalDate, TestResultAggrSummary>(localDateComparator);
    LocalDate today = new LocalDate();

    // for each job, for each day, add last build of the day to summary
    for (Job job : getDashboard().getJobs()) {
        Filter filter = job.getAction(ReportPluginProjectAction.class).getInitializedFilter();
        filter.addCombinationFilter(combinationFilter);
        Run run = job.getFirstBuild();

        if (run != null) { // execute only if job has builds
            LocalDate runDay = new LocalDate(run.getTimestamp());
            LocalDate firstDay = (dateRange != 0) ? new LocalDate().minusDays(dateRange) : runDay;

            while (run != null) {
                runDay = new LocalDate(run.getTimestamp());
                Run nextRun = run.getNextBuild();

                if (nextRun != null) {
                    LocalDate nextRunDay = new LocalDate(nextRun.getTimestamp());
                    // skip run before firstDay, but keep if next build is after start date
                    if (!runDay.isBefore(firstDay)
                            || runDay.isBefore(firstDay) && !nextRunDay.isBefore(firstDay)) {
                        // if next run is not the same day, use this test to summarize
                        if (nextRunDay.isAfter(runDay)) {
                            summarize(summaries, run.getAction(ReportPluginBuildAction.class).getTestResults(),
                                    filter, (runDay.isBefore(firstDay) ? firstDay : runDay),
                                    nextRunDay.minusDays(1));
                        }
                    }
                } else {
                    // use this run's test result from last run to today
                    summarize(summaries, run.getAction(ReportPluginBuildAction.class).getTestResults(), filter,
                            (runDay.isBefore(firstDay) ? firstDay : runDay), today);
                }
                run = nextRun;
            }
        }
    }

    return new Graph(-1, getGraphWidth(), getGraphHeight()) {

        protected JFreeChart createGraph() {
            return GraphHelper.createChart(buildDataSet(summaries));
        }
    };
}