Example usage for org.joda.time LocalDate isBefore

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

Introduction

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

Prototype

public boolean isBefore(ReadablePartial partial) 

Source Link

Document

Is this partial earlier than the specified partial.

Usage

From source file:org.mifosplatform.portfolio.loanaccount.loanschedule.domain.AbstractLoanScheduleGenerator.java

License:Mozilla Public License

/**
 * calculates Interest stating date as per the settings
 *//*from  w w  w.  j a  v a  2s .c o m*/
private LocalDate calculateInterestStartDateForPeriod(final LoanApplicationTerms loanApplicationTerms,
        LocalDate periodStartDate, final LocalDate idealDisbursementDate,
        LocalDate periodStartDateApplicableForInterest) {
    if (periodStartDate.isBefore(idealDisbursementDate)) {
        if (loanApplicationTerms.getInterestChargedFromLocalDate() != null) {
            periodStartDateApplicableForInterest = loanApplicationTerms.getInterestChargedFromLocalDate();
        } else {
            periodStartDateApplicableForInterest = idealDisbursementDate;
        }
    }
    return periodStartDateApplicableForInterest;
}

From source file:org.mifosplatform.portfolio.loanaccount.loanschedule.domain.DecliningBalanceInterestLoanScheduleGenerator.java

License:Mozilla Public License

@Override
public PrincipalInterest calculatePrincipalInterestComponentsForPeriod(
        final PaymentPeriodsInOneYearCalculator calculator,
        final double interestCalculationGraceOnRepaymentPeriodFraction, final Money totalCumulativePrincipal,
        @SuppressWarnings("unused") final Money totalCumulativeInterest,
        @SuppressWarnings("unused") final Money totalInterestDueForLoan,
        final Money cumulatingInterestPaymentDueToGrace, final Money outstandingBalance,
        final LoanApplicationTerms loanApplicationTerms, final int periodNumber, final MathContext mc,
        final TreeMap<LocalDate, Money> principalVariation, final Map<LocalDate, Money> compoundingMap,
        final LocalDate periodStartDate, final LocalDate periodEndDate, final int daysForInterestInFullPeriod) {

    LocalDate interestStartDate = periodStartDate;
    Money interestForThisInstallment = totalCumulativePrincipal.zero();
    Money compoundedMoney = totalCumulativePrincipal.zero();
    Money compoundedInterest = totalCumulativePrincipal.zero();
    Money balanceForInterestCalculation = outstandingBalance;
    Money cumulatingInterestDueToGrace = cumulatingInterestPaymentDueToGrace;
    final int daysInPeriodApplicableForInterest = Days.daysBetween(periodStartDate, periodEndDate).getDays();
    if (principalVariation != null) {
        // identifies rest date after current date for reducing all
        // compounding
        // values
        LocalDate compoundingEndDate = principalVariation.ceilingKey(DateUtils.getLocalDateOfTenant());
        if (compoundingEndDate == null) {
            compoundingEndDate = DateUtils.getLocalDateOfTenant();
        }//w w w  . j  a  v  a 2s.  co m

        for (Map.Entry<LocalDate, Money> principal : principalVariation.entrySet()) {

            if (!principal.getKey().isAfter(periodEndDate)) {
                int interestForDays = Days.daysBetween(interestStartDate, principal.getKey()).getDays();
                if (interestForDays > 0) {
                    final PrincipalInterest result = loanApplicationTerms.calculateTotalInterestForPeriod(
                            calculator, interestCalculationGraceOnRepaymentPeriodFraction, periodNumber, mc,
                            cumulatingInterestDueToGrace, interestForDays, balanceForInterestCalculation);
                    if (loanApplicationTerms.getInterestCalculationPeriodMethod().isDaily()) {
                        interestForThisInstallment = interestForThisInstallment.plus(result.interest());
                        cumulatingInterestDueToGrace = result.interestPaymentDueToGrace();
                    } else {
                        interestForThisInstallment = interestForThisInstallment.plus(calculateInterestForDays(
                                daysForInterestInFullPeriod, result.interest().getAmount(), interestForDays));
                        cumulatingInterestDueToGrace = cumulatingInterestDueToGrace
                                .plus(calculateInterestForDays(
                                        daysForInterestInFullPeriod, result.interestPaymentDueToGrace()
                                                .minus(cumulatingInterestDueToGrace).getAmount(),
                                        interestForDays));
                    }

                    interestStartDate = principal.getKey();
                }
                Money compoundFee = totalCumulativePrincipal.zero();
                if (compoundingMap.containsKey(principal.getKey())) {
                    Money interestToBeCompounded = totalCumulativePrincipal.zero();
                    // for interest compounding
                    if (loanApplicationTerms.getInterestRecalculationCompoundingMethod()
                            .isInterestCompoundingEnabled()) {
                        interestToBeCompounded = interestForThisInstallment.minus(compoundedInterest);
                        balanceForInterestCalculation = balanceForInterestCalculation
                                .plus(interestToBeCompounded);
                        compoundedInterest = interestForThisInstallment;
                    }
                    // fee compounding will be done after calculation
                    compoundFee = compoundingMap.get(principal.getKey());
                    compoundedMoney = compoundedMoney.plus(interestToBeCompounded).plus(compoundFee);
                }
                balanceForInterestCalculation = balanceForInterestCalculation.plus(principal.getValue())
                        .plus(compoundFee);
            }

        }
        if (!periodEndDate.isBefore(compoundingEndDate)) {
            balanceForInterestCalculation = balanceForInterestCalculation.minus(compoundedMoney);
            compoundingMap.clear();
        } else if (compoundedMoney.isGreaterThanZero()) {
            compoundingMap.put(periodEndDate, compoundedMoney);
            compoundingMap.put(compoundingEndDate, compoundedMoney.negated());
            clearMapDetails(periodEndDate, compoundingMap);
        }
    }
    int interestForDays = Days.daysBetween(interestStartDate, periodEndDate).getDays();

    final PrincipalInterest result = loanApplicationTerms.calculateTotalInterestForPeriod(calculator,
            interestCalculationGraceOnRepaymentPeriodFraction, periodNumber, mc, cumulatingInterestDueToGrace,
            interestForDays, balanceForInterestCalculation);
    if (loanApplicationTerms.getInterestCalculationPeriodMethod().isDaily()) {
        interestForThisInstallment = interestForThisInstallment.plus(result.interest());
        cumulatingInterestDueToGrace = result.interestPaymentDueToGrace();
    } else {
        interestForThisInstallment = interestForThisInstallment.plus(calculateInterestForDays(
                daysForInterestInFullPeriod, result.interest().getAmount(), interestForDays));
        cumulatingInterestDueToGrace = cumulatingInterestDueToGrace
                .plus(calculateInterestForDays(daysForInterestInFullPeriod,
                        result.interestPaymentDueToGrace().minus(cumulatingInterestDueToGrace).getAmount(),
                        interestForDays));
    }

    Money interestForPeriod = interestForThisInstallment;
    if (interestForPeriod.isGreaterThanZero()) {
        interestForPeriod = interestForPeriod.minus(cumulatingInterestPaymentDueToGrace);
    } else {
        interestForPeriod = cumulatingInterestDueToGrace.minus(cumulatingInterestPaymentDueToGrace);
    }
    Money principalForThisInstallment = loanApplicationTerms.calculateTotalPrincipalForPeriod(calculator,
            daysInPeriodApplicableForInterest, outstandingBalance, periodNumber, mc, interestForPeriod);

    // update cumulative fields for principal & interest
    final Money interestBroughtFowardDueToGrace = cumulatingInterestDueToGrace;
    final Money totalCumulativePrincipalToDate = totalCumulativePrincipal.plus(principalForThisInstallment);

    // adjust if needed
    principalForThisInstallment = loanApplicationTerms.adjustPrincipalIfLastRepaymentPeriod(
            principalForThisInstallment, totalCumulativePrincipalToDate, periodNumber);

    return new PrincipalInterest(principalForThisInstallment, interestForThisInstallment,
            interestBroughtFowardDueToGrace);
}

From source file:org.mifosplatform.portfolio.loanaccount.loanschedule.domain.LoanApplicationTerms.java

License:Mozilla Public License

private BigDecimal calculatePeriodsInLoanTerm() {

    BigDecimal periodsInLoanTerm = BigDecimal.valueOf(this.loanTermFrequency);
    switch (this.interestCalculationPeriodMethod) {
    case DAILY:/*from   ww w.  j av a2s  .c om*/
        // number of days from 'ideal disbursement' to final date

        LocalDate loanStartDate = getExpectedDisbursementDate();
        if (getInterestChargedFromDate() != null && loanStartDate.isBefore(getInterestChargedFromLocalDate())) {
            loanStartDate = getInterestChargedFromLocalDate();
        }

        final int periodsInLoanTermInteger = Days.daysBetween(loanStartDate, this.loanEndDate).getDays();
        periodsInLoanTerm = BigDecimal.valueOf(periodsInLoanTermInteger);
        break;
    case INVALID:
        break;
    case SAME_AS_REPAYMENT_PERIOD:
        break;
    }

    return periodsInLoanTerm;
}

From source file:org.mifosplatform.portfolio.loanaccount.loanschedule.domain.LoanApplicationTerms.java

License:Mozilla Public License

public void setFixedEmiAmountForPeriod(LocalDate periodDate) {
    LocalDate startDate = expectedDisbursementDate;
    for (LoanTermVariationsData loanVariationTermsData : this.emiAmountVariations) {
        if (!periodDate.isBefore(loanVariationTermsData.getTermApplicableFrom())
                && !startDate.isAfter(loanVariationTermsData.getTermApplicableFrom())) {
            if (loanVariationTermsData.getTermValue() != null) {
                this.fixedEmiAmount = loanVariationTermsData.getTermValue();
                startDate = loanVariationTermsData.getTermApplicableFrom();
            }//from w w  w . ja va2 s . c  om
        }
    }
}

From source file:org.mifosplatform.portfolio.loanaccount.rescheduleloan.data.LoanRescheduleRequestDataValidator.java

License:Mozilla Public License

/**
 * Validates the request to create a new loan reschedule entry
 * /*ww  w. j av a2 s .  c  o m*/
 * @param jsonCommand
 *            the JSON command object (instance of the JsonCommand class)
 * @return void
 **/
public void validateForCreateAction(final JsonCommand jsonCommand, final Loan loan) {

    final String jsonString = jsonCommand.json();

    if (StringUtils.isBlank(jsonString)) {
        throw new InvalidJsonException();
    }

    final Type typeToken = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString,
            RescheduleLoansApiConstants.CREATE_REQUEST_DATA_PARAMETERS);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors)
            .resource(StringUtils.lowerCase(RescheduleLoansApiConstants.ENTITY_NAME));

    final JsonElement jsonElement = jsonCommand.parsedJson();

    if (!loan.status().isActive()) {
        dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode("loan.is.not.active",
                "Loan is not active");
    }

    final Long loanId = this.fromJsonHelper.extractLongNamed(RescheduleLoansApiConstants.loanIdParamName,
            jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.loanIdParamName).value(loanId).notNull()
            .integerGreaterThanZero();

    final LocalDate submittedOnDate = this.fromJsonHelper
            .extractLocalDateNamed(RescheduleLoansApiConstants.submittedOnDateParamName, jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.submittedOnDateParamName)
            .value(submittedOnDate).notNull();

    if (submittedOnDate != null && loan.getDisbursementDate().isAfter(submittedOnDate)) {
        dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.submittedOnDateParamName)
                .failWithCode("before.loan.disbursement.date",
                        "Submission date cannot be before the loan disbursement date");
    }

    final LocalDate rescheduleFromDate = this.fromJsonHelper
            .extractLocalDateNamed(RescheduleLoansApiConstants.rescheduleFromDateParamName, jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName)
            .value(rescheduleFromDate).notNull();

    final Integer graceOnPrincipal = this.fromJsonHelper
            .extractIntegerWithLocaleNamed(RescheduleLoansApiConstants.graceOnPrincipalParamName, jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.graceOnPrincipalParamName)
            .value(graceOnPrincipal).ignoreIfNull().integerGreaterThanZero();

    final Integer graceOnInterest = this.fromJsonHelper
            .extractIntegerWithLocaleNamed(RescheduleLoansApiConstants.graceOnInterestParamName, jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.graceOnInterestParamName)
            .value(graceOnInterest).ignoreIfNull().integerGreaterThanZero();

    final Integer extraTerms = this.fromJsonHelper
            .extractIntegerWithLocaleNamed(RescheduleLoansApiConstants.extraTermsParamName, jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.extraTermsParamName).value(extraTerms)
            .ignoreIfNull().integerGreaterThanZero();

    final Long rescheduleReasonId = this.fromJsonHelper
            .extractLongNamed(RescheduleLoansApiConstants.rescheduleReasonIdParamName, jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleReasonIdParamName)
            .value(rescheduleReasonId).notNull().integerGreaterThanZero();

    final String rescheduleReasonComment = this.fromJsonHelper
            .extractStringNamed(RescheduleLoansApiConstants.rescheduleReasonCommentParamName, jsonElement);
    dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleReasonCommentParamName)
            .value(rescheduleReasonComment).ignoreIfNull().notExceedingLengthOf(500);

    final LocalDate adjustedDueDate = this.fromJsonHelper
            .extractLocalDateNamed(RescheduleLoansApiConstants.adjustedDueDateParamName, jsonElement);

    if (adjustedDueDate != null && rescheduleFromDate != null && adjustedDueDate.isBefore(rescheduleFromDate)) {
        dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName)
                .failWithCode("adjustedDueDate.before.rescheduleFromDate",
                        "Adjusted due date cannot be before the reschedule from date");
    }

    // at least one of the following must be provided => graceOnPrincipal,
    // graceOnInterest, extraTerms, newInterestRate
    if (!this.fromJsonHelper.parameterExists(RescheduleLoansApiConstants.graceOnPrincipalParamName, jsonElement)
            && !this.fromJsonHelper.parameterExists(RescheduleLoansApiConstants.graceOnInterestParamName,
                    jsonElement)
            && !this.fromJsonHelper.parameterExists(RescheduleLoansApiConstants.extraTermsParamName,
                    jsonElement)
            && !this.fromJsonHelper.parameterExists(RescheduleLoansApiConstants.newInterestRateParamName,
                    jsonElement)
            && !this.fromJsonHelper.parameterExists(RescheduleLoansApiConstants.adjustedDueDateParamName,
                    jsonElement)) {
        dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.graceOnPrincipalParamName).notNull();
    }

    if (rescheduleFromDate != null) {
        LoanRepaymentScheduleInstallment installment = loan.getRepaymentScheduleInstallment(rescheduleFromDate);

        if (installment == null) {
            dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName)
                    .failWithCode("repayment.schedule.installment.does.not.exist",
                            "Repayment schedule installment does not exist");
        }

        if (installment != null && installment.isObligationsMet()) {
            dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName)
                    .failWithCode("repayment.schedule.installment.obligation.met",
                            "Repayment schedule installment obligation met");
        }

        if (installment != null && installment.isPartlyPaid()) {
            dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName)
                    .failWithCode("repayment.schedule.installment.partly.paid",
                            "Repayment schedule installment is partly paid");
        }
    }

    if (loanId != null) {
        List<LoanRescheduleRequestData> loanRescheduleRequestData = this.loanRescheduleRequestReadPlatformService
                .readLoanRescheduleRequests(loanId, LoanStatus.APPROVED.getValue());

        if (loanRescheduleRequestData.size() > 0) {
            dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode("loan.already.rescheduled",
                    "The loan can only be rescheduled once.");
        }
    }

    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }
}

From source file:org.mifosplatform.portfolio.loanaccount.service.LoanAccrualWritePlatformServiceImpl.java

License:Mozilla Public License

@Override
public String addPeriodicAccruals(final LocalDate tilldate,
        Collection<LoanScheduleAccrualData> loanScheduleAccrualDatas) {
    StringBuilder sb = new StringBuilder();
    Set<Long> loansIds = new HashSet<>();
    LocalDate accruredTill = null;
    Long lastLoanId = null;/*from  w w w  .j  a va2s  . c o  m*/
    Map<Long, Collection<LoanChargeData>> loanChargeMap = new HashMap<>();
    Map<Long, Collection<LoanTransactionData>> loanWaiverTansactions = new HashMap<>();
    Map<Long, Collection<LoanSchedulePeriodData>> loanWaiverSchedules = new HashMap<>();
    for (final LoanScheduleAccrualData accrualData : loanScheduleAccrualDatas) {
        try {
            if (!loansIds.contains(accrualData.getLoanId())) {
                if (accrualData.getWaivedInterestIncome() != null
                        && !loanWaiverTansactions.containsKey(accrualData.getLoanId())) {
                    loanWaiverSchedules.put(accrualData.getLoanId(), this.loanReadPlatformService
                            .fetchWaiverInterestRepaymentData(accrualData.getLoanId()));
                    loanWaiverTansactions.put(accrualData.getLoanId(), this.loanReadPlatformService
                            .retrieveWaiverLoanTransactions(accrualData.getLoanId()));
                }

                if (!loanChargeMap.containsKey(accrualData.getLoanId())) {
                    Collection<LoanChargeData> chargeData = this.loanChargeReadPlatformService
                            .retrieveLoanChargesForAccural(accrualData.getLoanId());
                    loanChargeMap.put(accrualData.getLoanId(), chargeData);
                }
                if (accrualData.getDueDateAsLocaldate().isAfter(tilldate)) {
                    if (accruredTill == null || lastLoanId == null
                            || !lastLoanId.equals(accrualData.getLoanId())) {
                        accruredTill = accrualData.getAccruedTill();
                    }
                    if (accruredTill == null || accruredTill.isBefore(tilldate)) {
                        updateCharges(loanChargeMap.get(accrualData.getLoanId()), accrualData,
                                accrualData.getFromDateAsLocaldate(), tilldate);
                        updateInterestIncome(accrualData, loanWaiverTansactions, loanWaiverSchedules, tilldate);
                        addAccrualTillSpecificDate(tilldate, accrualData);
                    }
                } else {
                    updateCharges(loanChargeMap.get(accrualData.getLoanId()), accrualData,
                            accrualData.getFromDateAsLocaldate(), accrualData.getDueDateAsLocaldate());
                    updateInterestIncome(accrualData, loanWaiverTansactions, loanWaiverSchedules, tilldate);
                    addAccrualAccounting(accrualData);
                    accruredTill = accrualData.getDueDateAsLocaldate();
                }
            }
        } catch (Exception e) {
            loansIds.add(accrualData.getLoanId());
            Throwable realCause = e;
            if (e.getCause() != null) {
                realCause = e.getCause();
            }
            sb.append("failed to add accural transaction for repayment with id "
                    + accrualData.getRepaymentScheduleId() + " with message " + realCause.getMessage());
        }
        lastLoanId = accrualData.getLoanId();
    }
    return sb.toString();
}

From source file:org.mifosplatform.portfolio.loanaccount.service.LoanAccrualWritePlatformServiceImpl.java

License:Mozilla Public License

private void addAccrualTillSpecificDate(final LocalDate tilldate, final LoanScheduleAccrualData accrualData)
        throws Exception {
    LocalDate interestStartDate = accrualData.getFromDateAsLocaldate();
    if (accrualData.getInterestCalculatedFrom() != null
            && accrualData.getFromDateAsLocaldate().isBefore(accrualData.getInterestCalculatedFrom())) {
        if (accrualData.getInterestCalculatedFrom().isBefore(accrualData.getDueDateAsLocaldate())) {
            interestStartDate = accrualData.getInterestCalculatedFrom();
        } else {/*from   w  w w  .  j a v  a 2  s .co m*/
            interestStartDate = accrualData.getDueDateAsLocaldate();
        }
    }

    int totalNumberOfDays = Days.daysBetween(interestStartDate, accrualData.getDueDateAsLocaldate()).getDays();
    LocalDate startDate = accrualData.getFromDateAsLocaldate();
    if (accrualData.getInterestCalculatedFrom() != null
            && startDate.isBefore(accrualData.getInterestCalculatedFrom())) {
        if (accrualData.getInterestCalculatedFrom().isBefore(tilldate)) {
            startDate = accrualData.getInterestCalculatedFrom();
        } else {
            startDate = tilldate;
        }
    }
    int daysToBeAccrued = Days.daysBetween(startDate, tilldate).getDays();
    double interestPerDay = accrualData.getAccruableIncome().doubleValue() / totalNumberOfDays;
    BigDecimal amount = BigDecimal.ZERO;
    BigDecimal interestportion = null;
    BigDecimal feeportion = accrualData.getDueDateFeeIncome();
    BigDecimal penaltyportion = accrualData.getDueDatePenaltyIncome();
    if (daysToBeAccrued >= totalNumberOfDays) {
        interestportion = accrualData.getAccruableIncome();
    } else {
        double iterest = interestPerDay * daysToBeAccrued;
        interestportion = BigDecimal.valueOf(iterest);
    }
    interestportion = interestportion.setScale(accrualData.getCurrencyData().decimalPlaces(),
            RoundingMode.HALF_EVEN);

    BigDecimal totalAccInterest = accrualData.getAccruedInterestIncome();
    BigDecimal totalAccPenalty = accrualData.getAccruedPenaltyIncome();
    BigDecimal totalAccFee = accrualData.getAccruedFeeIncome();

    if (interestportion != null) {
        if (totalAccInterest == null) {
            totalAccInterest = BigDecimal.ZERO;
        }
        interestportion = interestportion.subtract(totalAccInterest);
        amount = amount.add(interestportion);
        totalAccInterest = totalAccInterest.add(interestportion);
        if (interestportion.compareTo(BigDecimal.ZERO) == 0) {
            interestportion = null;
        }
    }
    if (feeportion != null) {
        if (totalAccFee == null) {
            totalAccFee = BigDecimal.ZERO;
        }
        feeportion = feeportion.subtract(totalAccFee);
        amount = amount.add(feeportion);
        totalAccFee = totalAccFee.add(feeportion);
        if (feeportion.compareTo(BigDecimal.ZERO) == 0) {
            feeportion = null;
        }
    }

    if (penaltyportion != null) {
        if (totalAccPenalty == null) {
            totalAccPenalty = BigDecimal.ZERO;
        }
        penaltyportion = penaltyportion.subtract(totalAccPenalty);
        amount = amount.add(penaltyportion);
        totalAccPenalty = totalAccPenalty.add(penaltyportion);
        if (penaltyportion.compareTo(BigDecimal.ZERO) == 0) {
            penaltyportion = null;
        }
    }
    if (amount.compareTo(BigDecimal.ZERO) == 1) {
        addAccrualAccounting(accrualData, amount, interestportion, totalAccInterest, feeportion, totalAccFee,
                penaltyportion, totalAccPenalty, tilldate);
    }
}

From source file:org.mifosplatform.portfolio.savings.domain.SavingsAccount.java

License:Mozilla Public License

public void payCharge(final SavingsAccountCharge savingsAccountCharge, final BigDecimal amountPaid,
        final LocalDate transactionDate, final DateTimeFormatter formatter, final AppUser user) {

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource(SAVINGS_ACCOUNT_RESOURCE_NAME);

    if (isClosed()) {
        baseDataValidator.reset()//from   w  ww.  j av a  2  s.c  om
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.closed");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (isNotActive()) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.not.active");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (savingsAccountCharge.isNotActive()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("charge.is.not.active");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (getActivationLocalDate() != null && transactionDate.isBefore(getActivationLocalDate())) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName)
                .value(getActivationLocalDate().toString(formatter))
                .failWithCodeNoParameterAddedToErrorCode("transaction.before.activationDate");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (DateUtils.isDateInTheFuture(transactionDate)) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName)
                .value(getSubmittedOnLocalDate().toString(formatter))
                .failWithCodeNoParameterAddedToErrorCode("transaction.is.futureDate");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (savingsAccountCharge.isSavingsActivation()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(
                "transaction.not.valid.cannot.pay.activation.time.charge.is.automated");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (savingsAccountCharge.isAnnualFee()) {
        final LocalDate annualFeeDueDate = savingsAccountCharge.getDueLocalDate();
        if (annualFeeDueDate == null) {
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("no.annualfee.settings");
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }

        if (!annualFeeDueDate.equals(transactionDate)) {
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("invalid.date");
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }

        Date currentAnnualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate();
        if (currentAnnualFeeNextDueDate != null
                && new LocalDate(currentAnnualFeeNextDueDate).isEqual(transactionDate)) {
            baseDataValidator.reset().parameter("dueDate").value(transactionDate.toString(formatter))
                    .failWithCodeNoParameterAddedToErrorCode("transaction.exists.on.date");

            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    // validate charge is not already paid or waived
    if (savingsAccountCharge.isWaived()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(
                "transaction.invalid.account.charge.is.already.waived");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    } else if (savingsAccountCharge.isPaid()) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.paid");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    final Money chargePaid = Money.of(currency, amountPaid);
    if (!savingsAccountCharge.getAmountOutstanding(getCurrency()).isGreaterThanOrEqualTo(chargePaid)) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.charge.amount.paid.in.access");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    this.payCharge(savingsAccountCharge, chargePaid, transactionDate, user);
}

From source file:org.neo4j.data.generator.domains.medicalrecords.encounters.EncounterSequenceGenerator.java

License:Open Source License

public List<Encounter> encountersSince(LocalDate dateOfBirth) {
    ArrayList<Encounter> encounters = new ArrayList<Encounter>();
    LocalDate currentDate = dateOfBirth;
    LocalDate today = new LocalDate();
    while (currentDate.isBefore(today)) {
        encounters.add(encounterGenerator.nextEncounter(currentDate));
        currentDate = currentDate.plusDays((int) (Math.random() * 365 * MAX_YEARS_BETWEEN_ENCOUNTERS));
    }// w  w  w .j a v a2s  .c o m
    return encounters;
}

From source file:org.netxilia.functions.DateFunctions.java

License:Open Source License

public int NETWORKDAYS(ReadablePartial startDate, ReadablePartial endDate, Iterator<ReadablePartial> holidays) {
    LocalDate startLocalDate = DateUtils.toLocalDate(startDate, ORIGIN_DATE);
    LocalDate endLocalDate = DateUtils.toLocalDate(endDate, ORIGIN_DATE);
    if (endLocalDate.isBefore(startLocalDate)) {
        return -NETWORKDAYS(endDate, startDate, holidays);
    }//from   w ww  .j  a va 2 s . co m

    Set<LocalDate> holidaySet = new HashSet<LocalDate>();
    if (holidays != null) {
        while (holidays.hasNext()) {
            holidaySet.add(DateUtils.toLocalDate(holidays.next(), ORIGIN_DATE));
        }
    }

    HolidayCalendar<LocalDate> holidayCalendar = new DefaultHolidayCalendar<LocalDate>(holidaySet);

    DateCalculator<LocalDate> calc = new LocalDateCalculator("", startLocalDate, holidayCalendar, null);

    int workDays = 0;
    outer: for (LocalDate crtDate = startLocalDate; !crtDate.isAfter(endLocalDate); crtDate = crtDate
            .plusDays(1)) {
        while (calc.isNonWorkingDay(crtDate)) {
            crtDate = crtDate.plusDays(1);
            if (crtDate.isAfter(endLocalDate)) {
                break outer;
            }
        }
        workDays++;
    }

    return workDays;
}