Example usage for org.joda.time LocalDate isAfter

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

Introduction

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

Prototype

public boolean isAfter(ReadablePartial partial) 

Source Link

Document

Is this partial later than the specified partial.

Usage

From source file:org.mifosplatform.portfolio.calendar.service.CalendarWritePlatformServiceJpaRepositoryImpl.java

License:Mozilla Public License

@Override
public CommandProcessingResult updateCalendar(final JsonCommand command) {

    /*//w w  w.j av a  2  s. co  m
     * Validate all the data for updating the calendar
     */

    this.fromApiJsonDeserializer.validateForUpdate(command.json());

    Boolean areActiveEntitiesSynced = false;
    final Long calendarId = command.entityId();

    final Collection<Integer> loanStatuses = new ArrayList<>(
            Arrays.asList(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(), LoanStatus.APPROVED.getValue(),
                    LoanStatus.ACTIVE.getValue()));

    final Integer numberOfActiveLoansSyncedWithThisCalendar = this.calendarInstanceRepository
            .countOfLoansSyncedWithCalendar(calendarId, loanStatuses);

    /*
     * areActiveEntitiesSynced is set to true, if there are any active loans
     * synced to this calendar.
     */

    if (numberOfActiveLoansSyncedWithThisCalendar > 0) {
        areActiveEntitiesSynced = true;
    }

    final Calendar calendarForUpdate = this.calendarRepository.findOne(calendarId);
    if (calendarForUpdate == null) {
        throw new CalendarNotFoundException(calendarId);
    }

    final Date oldStartDate = calendarForUpdate.getStartDate();
    final LocalDate currentDate = DateUtils.getLocalDateOfTenant();
    // create calendar history before updating calendar
    final CalendarHistory calendarHistory = new CalendarHistory(calendarForUpdate, oldStartDate);

    Map<String, Object> changes = null;

    final Boolean reschedulebasedOnMeetingDates = command.booleanObjectValueOfParameterNamed(
            CALENDAR_SUPPORTED_PARAMETERS.RESCHEDULE_BASED_ON_MEETING_DATES.getValue());

    /*
     * System allows to change the meeting date by two means,
     * 
     * Option 1: reschedulebasedOnMeetingDates = false or reschedulebasedOnMeetingDates is not passed 
     * By directly editing the recurring day with effective from
     * date and system decides the next meeting date based on some sensible
     * logic (i.e., number of minimum days between two repayments)
     * 
     * 
     * Option 2: reschedulebasedOnMeetingDates = true 
     * By providing alternative meeting date for one of future
     * meeting date and derive the day of recurrence from the new meeting
     * date. Ex: User proposes new meeting date say "14/Nov/2014" for
     * present meeting date "12/Nov/2014", based on this input other values
     * re derived and loans are rescheduled
     * 
     */

    LocalDate newMeetingDate = null;
    LocalDate presentMeetingDate = null;

    if (reschedulebasedOnMeetingDates != null && reschedulebasedOnMeetingDates) {

        newMeetingDate = command
                .localDateValueOfParameterNamed(CALENDAR_SUPPORTED_PARAMETERS.NEW_MEETING_DATE.getValue());
        presentMeetingDate = command
                .localDateValueOfParameterNamed(CALENDAR_SUPPORTED_PARAMETERS.PRESENT_MEETING_DATE.getValue());

        /*
         * New meeting date proposed will become the new start date for the
         * updated calendar
         */

        changes = calendarForUpdate.updateStartDateAndDerivedFeilds(newMeetingDate);

    } else {
        changes = calendarForUpdate.update(command, areActiveEntitiesSynced);
    }

    if (!changes.isEmpty()) {
        // update calendar history table only if there is a change in
        // calendar start date.
        if (currentDate.isAfter(new LocalDate(oldStartDate))) {
            final Date endDate = calendarForUpdate.getStartDateLocalDate().minusDays(1).toDate();
            calendarHistory.updateEndDate(endDate);
            this.calendarHistoryRepository.save(calendarHistory);
        }

        this.calendarRepository.saveAndFlush(calendarForUpdate);

        if (this.configurationDomainService.isRescheduleFutureRepaymentsEnabled()
                && calendarForUpdate.isRepeating()) {
            // fetch all loan calendar instances associated with modifying
            // calendar.
            final Collection<CalendarInstance> loanCalendarInstances = this.calendarInstanceRepository
                    .findByCalendarIdAndEntityTypeId(calendarId, CalendarEntityType.LOANS.getValue());

            if (!CollectionUtils.isEmpty(loanCalendarInstances)) {
                // update all loans associated with modifying calendar
                this.loanWritePlatformService.applyMeetingDateChanges(calendarForUpdate, loanCalendarInstances,
                        reschedulebasedOnMeetingDates, presentMeetingDate, newMeetingDate);

            }
        }
    }

    return new CommandProcessingResultBuilder() //
            .withCommandId(command.commandId()) //
            .withEntityId(calendarForUpdate.getId()) //
            .with(changes) //
            .build();
}

From source file:org.mifosplatform.portfolio.client.domain.Client.java

License:Mozilla Public License

public static Client createNew(final AppUser currentUser, final Office clientOffice,
        final Group clientParentGroup, final Staff staff, final SavingsProduct savingsProduct,
        final CodeValue gender, final CodeValue clientType, final CodeValue clientClassification,
        final JsonCommand command) {

    final String accountNo = command.stringValueOfParameterNamed(ClientApiConstants.accountNoParamName);
    final String externalId = command.stringValueOfParameterNamed(ClientApiConstants.externalIdParamName);
    final String mobileNo = command.stringValueOfParameterNamed(ClientApiConstants.mobileNoParamName);

    final String firstname = command.stringValueOfParameterNamed(ClientApiConstants.firstnameParamName);
    final String middlename = command.stringValueOfParameterNamed(ClientApiConstants.middlenameParamName);
    final String lastname = command.stringValueOfParameterNamed(ClientApiConstants.lastnameParamName);
    final String fullname = command.stringValueOfParameterNamed(ClientApiConstants.fullnameParamName);

    final LocalDate dataOfBirth = command
            .localDateValueOfParameterNamed(ClientApiConstants.dateOfBirthParamName);

    ClientStatus status = ClientStatus.PENDING;
    boolean active = false;
    if (command.hasParameter("active")) {
        active = command.booleanPrimitiveValueOfParameterNamed(ClientApiConstants.activeParamName);
    }/*w w w  .  j a va2  s .co m*/

    LocalDate activationDate = null;
    LocalDate officeJoiningDate = null;
    if (active) {
        status = ClientStatus.ACTIVE;
        activationDate = command.localDateValueOfParameterNamed(ClientApiConstants.activationDateParamName);
        officeJoiningDate = activationDate;
    }

    LocalDate submittedOnDate = new LocalDate();
    if (active && submittedOnDate.isAfter(activationDate)) {
        submittedOnDate = activationDate;
    }
    if (command.hasParameter(ClientApiConstants.submittedOnDateParamName)) {
        submittedOnDate = command.localDateValueOfParameterNamed(ClientApiConstants.submittedOnDateParamName);
    }
    final SavingsAccount account = null;
    return new Client(currentUser, status, clientOffice, clientParentGroup, accountNo, firstname, middlename,
            lastname, fullname, activationDate, officeJoiningDate, externalId, mobileNo, staff, submittedOnDate,
            savingsProduct, account, dataOfBirth, gender, clientType, clientClassification);
}

From source file:org.mifosplatform.portfolio.group.service.GroupingTypesWritePlatformServiceJpaRepositoryImpl.java

License:Mozilla Public License

private CommandProcessingResult createGroupingType(final JsonCommand command, final GroupTypes groupingType,
        final Long centerId) {
    try {//www  .  ja v  a 2 s.co m
        final String name = command.stringValueOfParameterNamed(GroupingTypesApiConstants.nameParamName);
        final String externalId = command
                .stringValueOfParameterNamed(GroupingTypesApiConstants.externalIdParamName);

        final AppUser currentUser = this.context.authenticatedUser();
        Long officeId = null;
        Group parentGroup = null;

        if (centerId == null) {
            officeId = command.longValueOfParameterNamed(GroupingTypesApiConstants.officeIdParamName);
        } else {
            parentGroup = this.groupRepository.findOneWithNotFoundDetection(centerId);
            officeId = parentGroup.officeId();
        }

        final Office groupOffice = this.officeRepository.findOne(officeId);
        if (groupOffice == null) {
            throw new OfficeNotFoundException(officeId);
        }

        final LocalDate activationDate = command
                .localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName);
        final GroupLevel groupLevel = this.groupLevelRepository.findOne(groupingType.getId());

        validateOfficeOpeningDateisAfterGroupOrCenterOpeningDate(groupOffice, groupLevel, activationDate);

        Staff staff = null;
        final Long staffId = command.longValueOfParameterNamed(GroupingTypesApiConstants.staffIdParamName);
        if (staffId != null) {
            staff = this.staffRepository.findByOfficeHierarchyWithNotFoundDetection(staffId,
                    groupOffice.getHierarchy());
        }

        final Set<Client> clientMembers = assembleSetOfClients(officeId, command);

        final Set<Group> groupMembers = assembleSetOfChildGroups(officeId, command);

        final boolean active = command
                .booleanPrimitiveValueOfParameterNamed(GroupingTypesApiConstants.activeParamName);
        LocalDate submittedOnDate = new LocalDate();
        if (active && submittedOnDate.isAfter(activationDate)) {
            submittedOnDate = activationDate;
        }
        if (command.hasParameter(GroupingTypesApiConstants.submittedOnDateParamName)) {
            submittedOnDate = command
                    .localDateValueOfParameterNamed(GroupingTypesApiConstants.submittedOnDateParamName);
        }

        final Group newGroup = Group.newGroup(groupOffice, staff, parentGroup, groupLevel, name, externalId,
                active, activationDate, clientMembers, groupMembers, submittedOnDate, currentUser);

        boolean rollbackTransaction = false;
        if (newGroup.isActive()) {
            // validate Group creation rules for Group
            if (newGroup.isGroup()) {
                validateGroupRulesBeforeActivation(newGroup);
            }

            if (newGroup.isCenter()) {
                final CommandWrapper commandWrapper = new CommandWrapperBuilder().activateCenter(null).build();
                rollbackTransaction = this.commandProcessingService.validateCommand(commandWrapper,
                        currentUser);
            } else {
                final CommandWrapper commandWrapper = new CommandWrapperBuilder().activateGroup(null).build();
                rollbackTransaction = this.commandProcessingService.validateCommand(commandWrapper,
                        currentUser);
            }
        }

        if (!newGroup.isCenter() && newGroup.hasActiveClients()) {
            final CommandWrapper commandWrapper = new CommandWrapperBuilder()
                    .associateClientsToGroup(newGroup.getId()).build();
            rollbackTransaction = this.commandProcessingService.validateCommand(commandWrapper, currentUser);
        }

        // pre-save to generate id for use in group hierarchy
        this.groupRepository.save(newGroup);

        /*
         * Generate hierarchy for a new center/group and all the child
         * groups if they exist
         */
        newGroup.generateHierarchy();

        this.groupRepository.saveAndFlush(newGroup);
        newGroup.captureStaffHistoryDuringCenterCreation(staff, activationDate);
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(groupOffice.getId()) //
                .withGroupId(newGroup.getId()) //
                .withEntityId(newGroup.getId()) //
                .setRollbackTransaction(rollbackTransaction)//
                .build();

    } catch (final DataIntegrityViolationException dve) {
        handleGroupDataIntegrityIssues(command, dve, groupingType);
        return CommandProcessingResult.empty();
    }
}

From source file:org.mifosplatform.portfolio.loanaccount.domain.AbstractLoanRepaymentScheduleTransactionProcessor.java

License:Mozilla Public License

/**
 * This method is responsible for checking if the current transaction is 'an
 * advance/early payment' based on the details passed through.
 * /* w w w  .java 2s .  c  om*/
 * Default implementation simply processes transactions as 'Late' if the
 * transaction date is after the installment due date.
 */
protected boolean isTransactionALateRepaymentOnInstallment(final int installmentIndex,
        final List<LoanRepaymentScheduleInstallment> installments, final LocalDate transactionDate) {

    LoanRepaymentScheduleInstallment currentInstallment = installments.get(installmentIndex);

    return transactionDate.isAfter(currentInstallment.getDueDate());
}

From source file:org.mifosplatform.portfolio.loanaccount.domain.HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java

License:Mozilla Public License

@Override
protected boolean isTransactionInAdvanceOfInstallment(final int currentInstallmentIndex,
        final List<LoanRepaymentScheduleInstallment> installments, final LocalDate transactionDate,
        final Money transactionAmount) {

    boolean isInAdvance = false;

    LocalDate lastInstallmentDueDate = null;
    int previousInstallmentIndex = 0;
    if (currentInstallmentIndex > 0) {
        previousInstallmentIndex = currentInstallmentIndex - 1;
    }/*from www .  j a  v  a  2 s  . co  m*/

    LoanRepaymentScheduleInstallment previousInstallment = installments.get(previousInstallmentIndex);
    lastInstallmentDueDate = previousInstallment.getDueDate();

    isInAdvance = !(transactionDate.isAfter(lastInstallmentDueDate)
            || (transactionDate.isEqual(lastInstallmentDueDate)));

    return isInAdvance;
}

From source file:org.mifosplatform.portfolio.loanaccount.domain.Loan.java

License:Mozilla Public License

public Map<String, Object> loanApplicationApproval(final AppUser currentUser, final JsonCommand command,
        final JsonArray disbursementDataArray, final LoanLifecycleStateMachine loanLifecycleStateMachine) {

    validateAccountStatus(LoanEvent.LOAN_APPROVED);

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

    /*/*w  ww . j  a  va2  s .  c  om*/
     * statusEnum is holding the possible new status derived from
     * loanLifecycleStateMachine.transition.
     */

    final LoanStatus newStatusEnum = loanLifecycleStateMachine.transition(LoanEvent.LOAN_APPROVED,
            LoanStatus.fromInt(this.loanStatus));

    /*
     * FIXME: There is no need to check below condition, if
     * loanLifecycleStateMachine.transition is doing it's responsibility
     * properly. Better implementation approach is, if code passes invalid
     * combination of states (fromState and toState), state machine should
     * return invalidate state and below if condition should check for not
     * equal to invalidateState, instead of check new value is same as
     * present value.
     */

    if (!newStatusEnum.hasStateOf(LoanStatus.fromInt(this.loanStatus))) {
        this.loanStatus = newStatusEnum.getValue();
        actualChanges.put("status", LoanEnumerations.status(this.loanStatus));

        // only do below if status has changed in the 'approval' case
        LocalDate approvedOn = command.localDateValueOfParameterNamed("approvedOnDate");
        String approvedOnDateChange = command.stringValueOfParameterNamed("approvedOnDate");
        if (approvedOn == null) {
            approvedOn = command.localDateValueOfParameterNamed("eventDate");
            approvedOnDateChange = command.stringValueOfParameterNamed("eventDate");
        }

        LocalDate expecteddisbursementDate = command.localDateValueOfParameterNamed("expectedDisbursementDate");

        BigDecimal approvedLoanAmount = command
                .bigDecimalValueOfParameterNamed(LoanApiConstants.approvedLoanAmountParameterName);

        if (approvedLoanAmount != null) {

            // Approved amount has to be less than or equal to principal
            // amount demanded

            if (approvedLoanAmount.compareTo(this.proposedPrincipal) == -1) {

                this.approvedPrincipal = approvedLoanAmount;

                /*
                 * All the calculations are done based on the principal
                 * amount, so it is necessary to set principal amount to
                 * approved amount
                 */

                this.loanRepaymentScheduleDetail.setPrincipal(approvedLoanAmount);

                actualChanges.put(LoanApiConstants.approvedLoanAmountParameterName, approvedLoanAmount);
                actualChanges.put(LoanApiConstants.disbursementPrincipalParameterName, approvedLoanAmount);
            } else if (approvedLoanAmount.compareTo(this.proposedPrincipal) == 1) {
                final String errorMessage = "Loan approved amount can't be greater than loan amount demanded.";
                throw new InvalidLoanStateTransitionException("approval",
                        "amount.can't.be.greater.than.loan.amount.demanded", errorMessage,
                        this.proposedPrincipal, approvedLoanAmount);
            }

            /* Update disbursement details */
            if (disbursementDataArray != null) {
                updateDisbursementDetails(command, actualChanges);
            }
        }
        if (loanProduct.isMultiDisburseLoan()) {

            if (this.disbursementDetails.isEmpty()) {
                final String errorMessage = "For this loan product, disbursement details must be provided";
                throw new MultiDisbursementDataRequiredException(LoanApiConstants.disbursementDataParameterName,
                        errorMessage);
            }

            if (this.disbursementDetails.size() > loanProduct.maxTrancheCount()) {
                final String errorMessage = "Number of tranche shouldn't be greter than "
                        + loanProduct.maxTrancheCount();
                throw new ExceedingTrancheCountException(LoanApiConstants.disbursementDataParameterName,
                        errorMessage, loanProduct.maxTrancheCount(), disbursementDetails.size());
            }
        }
        this.approvedOnDate = approvedOn.toDate();
        this.approvedBy = currentUser;
        actualChanges.put("locale", command.locale());
        actualChanges.put("dateFormat", command.dateFormat());
        actualChanges.put("approvedOnDate", approvedOnDateChange);

        final LocalDate submittalDate = new LocalDate(this.submittedOnDate);
        if (approvedOn.isBefore(submittalDate)) {
            final String errorMessage = "The date on which a loan is approved cannot be before its submittal date: "
                    + submittalDate.toString();
            throw new InvalidLoanStateTransitionException("approval", "cannot.be.before.submittal.date",
                    errorMessage, getApprovedOnDate(), submittalDate);
        }

        if (expecteddisbursementDate != null) {
            this.expectedDisbursementDate = expecteddisbursementDate.toDate();
            actualChanges.put("expectedDisbursementDate", expectedDisbursementDate);

            if (expecteddisbursementDate.isBefore(approvedOn)) {
                final String errorMessage = "The expected disbursement date should be either on or after the approval date: "
                        + approvedOn.toString();
                throw new InvalidLoanStateTransitionException("expecteddisbursal",
                        "should.be.on.or.after.approval.date", errorMessage, getApprovedOnDate(),
                        expecteddisbursementDate);
            }
        }

        validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_APPROVED, approvedOn);

        if (approvedOn.isAfter(DateUtils.getLocalDateOfTenant())) {
            final String errorMessage = "The date on which a loan is approved cannot be in the future.";
            throw new InvalidLoanStateTransitionException("approval", "cannot.be.a.future.date", errorMessage,
                    getApprovedOnDate());
        }

        if (this.loanOfficer != null) {
            final LoanOfficerAssignmentHistory loanOfficerAssignmentHistory = LoanOfficerAssignmentHistory
                    .createNew(this, this.loanOfficer, approvedOn);
            this.loanOfficerHistory.add(loanOfficerAssignmentHistory);
        }
    }

    return actualChanges;
}

From source file:org.mifosplatform.portfolio.loanaccount.domain.Loan.java

License:Mozilla Public License

private void handleDisbursementTransaction(final LocalDate disbursedOn, final LocalDateTime createdDate,
        final AppUser currentUser) {

    // add repayment transaction to track incoming money from client to mfi
    // for (charges due at time of disbursement)

    /***/*from   ww  w . j  a v  a2 s.co  m*/
     * TODO Vishwas: do we need to be able to pass in payment type details
     * for repayments at disbursements too?
     ***/
    final Money totalFeeChargesDueAtDisbursement = this.summary
            .getTotalFeeChargesDueAtDisbursement(loanCurrency());
    /**
     * all Charges repaid at disbursal is marked as repaid and
     * "APPLY Charge" transactions are created for all other fees ( which
     * are created during disbursal but not repaid)
     **/
    if (disbursedOn.toDate().equals(this.actualDisbursementDate)) {
        Money disbursentMoney = Money.zero(getCurrency());
        final LoanTransaction chargesPayment = LoanTransaction.repaymentAtDisbursement(getOffice(),
                disbursentMoney, null, disbursedOn, null, createdDate, currentUser);
        final Integer installmentNumber = null;
        for (final LoanCharge charge : charges()) {
            if (charge.isDueAtDisbursement()) {
                if (totalFeeChargesDueAtDisbursement.isGreaterThanZero()
                        && !charge.getChargePaymentMode().isPaymentModeAccountTransfer()) {
                    charge.markAsFullyPaid();
                    // Add "Loan Charge Paid By" details to this transaction
                    final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge,
                            charge.amount(), installmentNumber);
                    chargesPayment.getLoanChargesPaid().add(loanChargePaidBy);
                    disbursentMoney = disbursentMoney.plus(charge.amount());
                }
            } else {
                /**
                 * create a Charge applied transaction if Upfront Accrual,
                 * None or Cash based accounting is enabled
                 **/
                if (isNoneOrCashOrUpfrontAccrualAccountingEnabledOnLoanProduct()) {
                    handleChargeAppliedTransaction(charge, disbursedOn, currentUser);
                }
            }
        }
        if (disbursentMoney.isGreaterThanZero()) {
            final Money zero = Money.zero(getCurrency());
            chargesPayment.updateComponentsAndTotal(zero, zero, disbursentMoney, zero);
            chargesPayment.updateLoan(this);
            this.loanTransactions.add(chargesPayment);
            updateLoanOutstandingBalaces();
        }
    }

    if (getApprovedOnDate() != null && disbursedOn.isBefore(getApprovedOnDate())) {
        final String errorMessage = "The date on which a loan is disbursed cannot be before its approval date: "
                + getApprovedOnDate().toString();
        throw new InvalidLoanStateTransitionException("disbursal", "cannot.be.before.approval.date",
                errorMessage, disbursedOn, getApprovedOnDate());
    }

    if (getExpectedFirstRepaymentOnDate() != null && disbursedOn.isAfter(getExpectedFirstRepaymentOnDate())
            && disbursedOn.toDate().equals(this.actualDisbursementDate)) {
        final String errorMessage = "submittedOnDate cannot be after the loans  expectedFirstRepaymentOnDate: "
                + getExpectedFirstRepaymentOnDate().toString();
        throw new InvalidLoanStateTransitionException("disbursal",
                "cannot.be.after.expected.first.repayment.date", errorMessage, disbursedOn,
                getExpectedFirstRepaymentOnDate());
    }

    validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_DISBURSED, disbursedOn);

    if (disbursedOn.isAfter(new LocalDate())) {
        final String errorMessage = "The date on which a loan with identifier : " + this.accountNumber
                + " is disbursed cannot be in the future.";
        throw new InvalidLoanStateTransitionException("disbursal", "cannot.be.a.future.date", errorMessage,
                disbursedOn);
    }

}

From source file:org.mifosplatform.portfolio.loanaccount.domain.Loan.java

License:Mozilla Public License

public void updateLoanRepaymentScheduleDates(final LocalDate meetingStartDate, final String recuringRule,
        final boolean isHolidayEnabled, final List<Holiday> holidays, final WorkingDays workingDays,
        final Boolean reschedulebasedOnMeetingDates, final LocalDate presentMeetingDate,
        final LocalDate newMeetingDate) {

    // first repayment's from date is same as disbursement date.
    /*//from w w w. j ava2  s. co m
     * meetingStartDate is used as seedDate Capture the seedDate from user
     * and use the seedDate as meetingStart date
     */

    LocalDate tmpFromDate = getDisbursementDate();
    final PeriodFrequencyType repaymentPeriodFrequencyType = this.loanRepaymentScheduleDetail
            .getRepaymentPeriodFrequencyType();
    final Integer loanRepaymentInterval = this.loanRepaymentScheduleDetail.getRepayEvery();
    final String frequency = CalendarUtils
            .getMeetingFrequencyFromPeriodFrequencyType(repaymentPeriodFrequencyType);

    LocalDate newRepaymentDate = null;
    Boolean isFirstTime = true;

    for (final LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : this.repaymentScheduleInstallments) {

        LocalDate oldDueDate = loanRepaymentScheduleInstallment.getDueDate();

        if (oldDueDate.isEqual(presentMeetingDate) || oldDueDate.isAfter(presentMeetingDate)) {

            if (isFirstTime) {

                isFirstTime = false;
                newRepaymentDate = newMeetingDate;

            } else {
                // tmpFromDate.plusDays(1) is done to make sure
                // getNewRepaymentMeetingDate method returns next meeting
                // date and not the same as tmpFromDate
                newRepaymentDate = CalendarUtils.getNewRepaymentMeetingDate(recuringRule, tmpFromDate,
                        tmpFromDate.plusDays(1), loanRepaymentInterval, frequency, workingDays);
            }

            if (isHolidayEnabled) {
                newRepaymentDate = HolidayUtil.getRepaymentRescheduleDateToIfHoliday(newRepaymentDate,
                        holidays);
            }

            loanRepaymentScheduleInstallment.updateDueDate(newRepaymentDate);
            // reset from date to get actual daysInPeriod

            if (!isFirstTime) {
                loanRepaymentScheduleInstallment.updateFromDate(tmpFromDate);
            }

            tmpFromDate = newRepaymentDate;// update with new repayment
            // date
        } else {
            tmpFromDate = oldDueDate;
        }
    }
}

From source file:org.mifosplatform.portfolio.loanaccount.domain.Loan.java

License:Mozilla Public License

public void updateLoanRepaymentScheduleDates(final LocalDate meetingStartDate, final String recuringRule,
        final boolean isHolidayEnabled, final List<Holiday> holidays, final WorkingDays workingDays) {

    // first repayment's from date is same as disbursement date.
    LocalDate tmpFromDate = getDisbursementDate();
    final PeriodFrequencyType repaymentPeriodFrequencyType = this.loanRepaymentScheduleDetail
            .getRepaymentPeriodFrequencyType();
    final Integer loanRepaymentInterval = this.loanRepaymentScheduleDetail.getRepayEvery();
    final String frequency = CalendarUtils
            .getMeetingFrequencyFromPeriodFrequencyType(repaymentPeriodFrequencyType);

    LocalDate newRepaymentDate = null;
    LocalDate seedDate = meetingStartDate;

    for (final LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : this.repaymentScheduleInstallments) {

        LocalDate oldDueDate = loanRepaymentScheduleInstallment.getDueDate();

        // FIXME: AA this won't update repayment dates before current date.

        if (oldDueDate.isAfter(seedDate) && oldDueDate.isAfter(DateUtils.getLocalDateOfTenant())) {

            newRepaymentDate = CalendarUtils.getNewRepaymentMeetingDate(recuringRule, seedDate, oldDueDate,
                    loanRepaymentInterval, frequency, workingDays);

            final LocalDate maxDateLimitForNewRepayment = getMaxDateLimitForNewRepayment(
                    repaymentPeriodFrequencyType, loanRepaymentInterval, tmpFromDate);

            if (newRepaymentDate.isAfter(maxDateLimitForNewRepayment)) {
                newRepaymentDate = CalendarUtils.getNextRepaymentMeetingDate(recuringRule, seedDate,
                        tmpFromDate, loanRepaymentInterval, frequency, workingDays);
            }/*  w  ww .  j av a 2  s  .c o m*/

            if (isHolidayEnabled) {
                newRepaymentDate = HolidayUtil.getRepaymentRescheduleDateToIfHoliday(newRepaymentDate,
                        holidays);
            }

            loanRepaymentScheduleInstallment.updateDueDate(newRepaymentDate);
            // reset from date to get actual daysInPeriod
            loanRepaymentScheduleInstallment.updateFromDate(tmpFromDate);
            tmpFromDate = newRepaymentDate;// update with new repayment
            // date
        } else {
            tmpFromDate = oldDueDate;
        }
    }
}

From source file:org.mifosplatform.portfolio.loanaccount.domain.Loan.java

License:Mozilla Public License

public void regenerateRepaymentScheduleWithInterestRecalculation(final ScheduleGeneratorDTO generatorDTO,
        final AppUser currentUser) {

    LocalDate lastTransactionDate = getLastUserTransactionDate();
    final LoanScheduleModel loanSchedule = getRecalculatedSchedule(generatorDTO);
    if (loanSchedule == null) {
        return;//from w  w w .  java  2s .  c o  m
    }
    updateLoanSchedule(loanSchedule, currentUser);
    LocalDate lastRepaymentDate = this.getLastRepaymentPeriodDueDate();
    Set<LoanCharge> charges = this.charges();
    for (LoanCharge loanCharge : charges) {
        if (!loanCharge.isDueAtDisbursement()) {
            updateOverdueScheduleInstallment(loanCharge);
            if (loanCharge.getDueLocalDate() == null
                    || (!lastRepaymentDate.isBefore(loanCharge.getDueLocalDate()))) {
                if (!loanCharge.isWaived() && (loanCharge.getDueLocalDate() == null
                        || !lastTransactionDate.isAfter(loanCharge.getDueLocalDate()))) {
                    recalculateLoanCharge(loanCharge, generatorDTO.getPenaltyWaitPeriod());
                    loanCharge.updateWaivedAmount(getCurrency());
                }
            } else {
                loanCharge.setActive(false);
            }
        }
    }

    final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor = this.transactionProcessorFactory
            .determineProcessor(this.transactionProcessingStrategy);
    final List<LoanTransaction> allNonContraTransactionsPostDisbursement = retreiveListOfTransactionsPostDisbursement();
    final List<LoanTransaction> copyTransactions = new ArrayList<>();
    for (LoanTransaction loanTransaction : allNonContraTransactionsPostDisbursement) {
        copyTransactions.add(LoanTransaction.copyTransactionProperties(loanTransaction));
    }
    loanRepaymentScheduleTransactionProcessor.populateDerivedFeildsWithoutReprocess(getDisbursementDate(),
            copyTransactions, getCurrency(), this.repaymentScheduleInstallments, charges());

    updateLoanSummaryDerivedFields();
}