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.mifos.application.meeting.business.MeetingBO.java

License:Open Source License

public boolean queryDateIsInMeetingIntervalForFixedDate(LocalDate queryDate, LocalDate fixedDate) {
    LocalDate startOfMeetingInterval = startDateForMeetingInterval(fixedDate);
    LocalDate endOfMeetingInterval;
    if (isWeekly()) {
        endOfMeetingInterval = startOfMeetingInterval.plusWeeks(getRecurAfter());
    } else if (isMonthly()) {
        endOfMeetingInterval = startOfMeetingInterval.plusMonths(getRecurAfter());
    } else {/*from ww w  .java 2 s  . co  m*/
        // we don't handle meeting intervals in days
        return false;
    }
    return (queryDate.isEqual(startOfMeetingInterval) || queryDate.isAfter(startOfMeetingInterval))
            && queryDate.isBefore(endOfMeetingInterval);
}

From source file:org.mifos.application.servicefacade.SavingsServiceFacadeWebTier.java

License:Open Source License

@Override
public SavingsAccountClosureDto retrieveClosingDetails(Long savingsId, LocalDate closureDate) {

    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    SavingsBO savingsAccount = this.savingsDao.findById(savingsId);

    InterestScheduledEvent postingSchedule = savingsInterestScheduledEventFactory
            .createScheduledEventFrom(savingsAccount.getInterestPostingMeeting());
    LocalDate nextPostingDate = new LocalDate(savingsAccount.getNextIntPostDate());
    LocalDate startOfPostingPeriod = postingSchedule.findFirstDateOfPeriodForMatchingDate(nextPostingDate);

    CalendarPeriod postingPeriodAtClosure;
    if (startOfPostingPeriod.isAfter(closureDate)) {
        postingPeriodAtClosure = new CalendarPeriod(closureDate, closureDate);
    } else {/*from www  . ja  v a 2s  .  com*/
        postingPeriodAtClosure = new CalendarPeriod(startOfPostingPeriod, closureDate);
    }

    List<EndOfDayDetail> allEndOfDayDetailsForAccount = savingsDao
            .retrieveAllEndOfDayDetailsFor(savingsAccount.getCurrency(), Long.valueOf(savingsId));

    InterestPostingPeriodResult postingPeriodAtClosureResult = determinePostingPeriodResult(
            postingPeriodAtClosure, savingsAccount, allEndOfDayDetailsForAccount);

    Money endOfAccountBalance = postingPeriodAtClosureResult.getPeriodBalance();
    Money interestAmountAtClosure = postingPeriodAtClosureResult.getPeriodInterest();

    List<ListElement> depositPaymentTypes = retrieveDepositPaymentTypes(userContext);

    return new SavingsAccountClosureDto(new LocalDate(), endOfAccountBalance.toString(),
            interestAmountAtClosure.toString(), depositPaymentTypes);
}

From source file:org.mifos.application.servicefacade.SavingsServiceFacadeWebTier.java

License:Open Source License

@Override
public void closeSavingsAccount(Long savingsId, String notes, SavingsWithdrawalDto closeAccountDto) {

    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    SavingsBO savingsAccount = this.savingsDao.findById(savingsId);
    savingsAccount.updateDetails(userContext);

    PersonnelBO createdBy = this.personnelDao.findPersonnelById(userContext.getId());
    LocalDate closureDate = closeAccountDto.getDateOfWithdrawal();

    // Assumption that all previous interest postings occurred correctly
    InterestScheduledEvent postingSchedule = savingsInterestScheduledEventFactory
            .createScheduledEventFrom(savingsAccount.getInterestPostingMeeting());
    LocalDate nextPostingDate = new LocalDate(savingsAccount.getNextIntPostDate());
    LocalDate startOfPostingPeriod = postingSchedule.findFirstDateOfPeriodForMatchingDate(nextPostingDate);

    CalendarPeriod postingPeriodAtClosure;
    if (startOfPostingPeriod.isAfter(closureDate)) {
        postingPeriodAtClosure = new CalendarPeriod(closureDate, closureDate);
    } else {//from   w  w w .ja v  a 2s  .com
        postingPeriodAtClosure = new CalendarPeriod(startOfPostingPeriod, closureDate);
    }

    List<EndOfDayDetail> allEndOfDayDetailsForAccount = savingsDao
            .retrieveAllEndOfDayDetailsFor(savingsAccount.getCurrency(), Long.valueOf(savingsId));

    InterestPostingPeriodResult postingPeriodAtClosureResult = determinePostingPeriodResult(
            postingPeriodAtClosure, savingsAccount, allEndOfDayDetailsForAccount);
    savingsAccount.postInterest(postingSchedule, postingPeriodAtClosureResult, createdBy);

    AccountNotesEntity notesEntity = new AccountNotesEntity(new DateTimeService().getCurrentJavaSqlDate(),
            notes, createdBy, savingsAccount);

    try {
        CustomerBO customer = savingsAccount.getCustomer();
        if (closeAccountDto.getCustomerId() != null) {
            List<CustomerBO> clientList = new CustomerPersistence().getActiveAndOnHoldChildren(
                    savingsAccount.getCustomer().getSearchId(), savingsAccount.getCustomer().getOfficeId(),
                    CustomerLevel.CLIENT);

            for (CustomerBO client : clientList) {
                if (closeAccountDto.getCustomerId().intValue() == client.getCustomerId().intValue()) {
                    customer = client;
                    break;
                }
            }
        }

        Money amount = new Money(savingsAccount.getCurrency(), closeAccountDto.getAmount().toString());
        PaymentTypeEntity paymentType = new PaymentTypeEntity(closeAccountDto.getModeOfPayment().shortValue());
        Date receiptDate = null;
        if (closeAccountDto.getDateOfReceipt() != null) {
            receiptDate = closeAccountDto.getDateOfReceipt().toDateMidnight().toDate();
        }
        AccountPaymentEntity closeAccount = new AccountPaymentEntity(savingsAccount, amount,
                closeAccountDto.getReceiptId(), receiptDate, paymentType,
                closeAccountDto.getDateOfWithdrawal().toDateMidnight().toDate());

        this.transactionHelper.startTransaction();
        this.transactionHelper.beginAuditLoggingFor(savingsAccount);

        savingsAccount.closeAccount(closeAccount, notesEntity, customer, createdBy);
        this.savingsDao.save(savingsAccount);
        this.transactionHelper.commitTransaction();
    } catch (BusinessRuleException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getMessageKey(), e);
    } catch (PersistenceException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } finally {
        this.transactionHelper.closeSession();
    }
}

From source file:org.mifos.application.servicefacade.SavingsServiceFacadeWebTier.java

License:Open Source License

@Override
public List<AdjustableSavingsPaymentDto> retrievePaymentsForAdjustment(Integer accountId) {
    SavingsBO savingsAccount = this.savingsDao.findById(accountId);

    List<AdjustableSavingsPaymentDto> adjustablePayments = new ArrayList<AdjustableSavingsPaymentDto>();
    for (AccountPaymentEntity payment : savingsAccount.getAccountPayments()) {
        if (payment.isSavingsDepositOrWithdrawal() && payment.getAmount().isGreaterThan(Money.zero())) {
            AdjustableSavingsPaymentDto adjustableSavingsPaymentDto = new AdjustableSavingsPaymentDto(
                    payment.getPaymentId(), payment.getReceiptNumber(), payment.getAmount().getAmount(),
                    new LocalDate(payment.getPaymentDate()),
                    (payment.getReceiptDate() == null) ? null : new LocalDate(payment.getReceiptDate()),
                    payment.getPaymentType().getName(), payment.isSavingsDeposit());
            adjustablePayments.add(adjustableSavingsPaymentDto);
        }//  w  w  w .j  av a  2 s. c  o  m
    }

    Collections.sort(adjustablePayments, new Comparator<AdjustableSavingsPaymentDto>() {
        @Override
        public int compare(AdjustableSavingsPaymentDto o1, AdjustableSavingsPaymentDto o2) {
            int result;
            LocalDate firstDate = o1.getPaymentDate();
            LocalDate secondDate = o2.getPaymentDate();
            // sort by date
            if (firstDate.isAfter(secondDate)) {
                result = -1;
            } else if (firstDate.isBefore(secondDate)) {
                result = 1;
            } else { // withdrawal comes after deposit
                if (o1.isWithdrawal() && !o2.isWithdrawal()) {
                    result = -1;
                } else if (!o1.isWithdrawal() && o2.isWithdrawal()) {
                    result = 1;
                } else {
                    result = 0;
                }
            }
            return result;
        }
    });
    return adjustablePayments;
}

From source file:org.mifos.clientportfolio.loan.ui.CashFlowSummaryFormBean.java

License:Open Source License

private void validatePaymentsAndAmounts(MessageContext messageContext, List<DateTime> actualPaymentDates,
        List<Number> actualPaymentAmounts) {
    int index = 0;
    LocalDate lastPaymentDate = null;
    BigDecimal totalPayment = BigDecimal.ZERO;

    for (Number actualPayment : actualPaymentAmounts) {
        String installment = Integer.valueOf(index + 1).toString();
        LocalDate paymentDate = new LocalDate(actualPaymentDates.get(index));

        if (paymentDate.isBefore(new LocalDate(this.disbursementDate))) {

            String defaultMessage = "The payment date cannot be before disbursement date";
            ErrorEntry fieldError = new ErrorEntry("paymentDate.before.disbursementDate.invalid",
                    "disbursementDate", defaultMessage);
            fieldError.setArgs(Arrays.asList(installment));

            addErrorMessageToContext(messageContext, fieldError);
        }/*from  w  ww . j ava2 s . c om*/

        if (paymentDate.isAfter(new LocalDate()) && actualPayment.doubleValue() > 0) {

            String defaultMessage = "The payment date cannot be in the future.";
            ErrorEntry fieldError = new ErrorEntry("paymentDate.is.future.date.invalid", "disbursementDate",
                    defaultMessage);
            fieldError.setArgs(Arrays.asList(installment));

            addErrorMessageToContext(messageContext, fieldError);
        }

        if (lastPaymentDate != null) {
            if (!paymentDate.isEqual(lastPaymentDate) && !paymentDate.isAfter(lastPaymentDate)) {
                String defaultMessage = "The payment date cannot be before the previous payment date";
                ErrorEntry fieldError = new ErrorEntry("paymentDate.before.lastPaymentDate.invalid",
                        "disbursementDate", defaultMessage);
                fieldError.setArgs(Arrays.asList(installment));

                addErrorMessageToContext(messageContext, fieldError);
            }
        }

        BigDecimal payment = BigDecimal.valueOf(actualPayment.doubleValue());
        if (payment.doubleValue() > BigDecimal.ZERO.doubleValue()) {
            totalPayment = totalPayment.add(payment);
        }
        index++;
        lastPaymentDate = paymentDate;
    }

    BigDecimal totalAllowedPayments = this.loanPrincipal.add(this.totalLoanFees).add(this.totalLoanInterest);
    if (totalPayment.doubleValue() > totalAllowedPayments.doubleValue()) {
        String defaultMessage = "Exceeds total payments allowed for loan.";
        ErrorEntry fieldError = new ErrorEntry("totalPayments.exceeded.invalid", "disbursementDate",
                defaultMessage);
        addErrorMessageToContext(messageContext, fieldError);
    }
}

From source file:org.mifos.clientportfolio.loan.ui.DateValidator.java

License:Open Source License

public boolean isFutureDate(LocalDate date) {
    return date.isAfter(new LocalDate());
}

From source file:org.mifos.clientportfolio.newloan.domain.LoanDisbursementCoupledToCustomerMeetingScheduleStrategyImpl.java

License:Open Source License

@Override
public boolean isDisbursementDateValidInRelationToSchedule(LocalDate disbursementDate) {

    boolean result = false;

    if (disbursementDate.isEqual(this.nextValidCustomerMeetingDate)) {
        result = true;/*from  ww  w . j a  va 2  s . co  m*/
    } else if (disbursementDate.isAfter(this.nextValidCustomerMeetingDate)) {
        LocalDate matchingDate = this.nextValidCustomerMeetingDate;
        matchingDate = new LocalDate(
                scheduledEvent.nextEventDateAfter(matchingDate.toDateMidnight().toDateTime()));
        while (matchingDate.isBefore(disbursementDate)) {
            matchingDate = new LocalDate(
                    scheduledEvent.nextEventDateAfter(matchingDate.toDateMidnight().toDateTime()));
        }

        if (matchingDate.isEqual(disbursementDate)) {
            result = true;
        }
    }

    return result;
}

From source file:org.mifos.customers.business.CustomerAccountBO.java

License:Open Source License

/**
 * Create an initial meeting schedule with fees attached, if any.
 *
 * <p>PostConditions:</p>// www . j  a  v a  2s.c  om
 *
 * <ul>
 * <li> <code>numberOfMeetingDatesToGenerateOnCreation</code> {@link CustomerScheduleEntity}s are created
 *      starting with <code>customerMeeting</code>'s start date, scheduled according to <code>customerMeeting</code>'s
 *      frequency and recurrence, and subject to rules for scheduling around on working days and around holidays. See
 *      {@link HolidayAndWorkingDaysAndMoratoriaScheduledDateGeneration} for scheduling rules.</li>
 * <li> One-time upfront fees are attached to the first meeting.</li>
 * <li> Periodic fees are attached to the first meeting and subsequent meetings that match the fee's frequency
 *      and recurrence</li>
 * <li> The <code>lastAppliedDate</code> for each fee is set to the date of the latest meeting to which the fee
 *      is attached
 * </ul>
 */
public void createSchedulesAndFeeSchedulesForFirstTimeActiveCustomer(CustomerBO customer,
        List<AccountFeesEntity> accountFees, MeetingBO customerMeeting, CalendarEvent applicableCalendarEvents,
        DateTime scheduleGenerationStartingFrom) {

    final ScheduledEvent customerMeetingEvent = new RecurringScheduledEventFactoryImpl()
            .createScheduledEventFrom(customerMeeting);
    DateTime beginningFrom = scheduleGenerationStartingFrom;
    // synch up generated schedule for center/group/client or group/client hierarchy
    CustomerBO upmostParent = upmostParentOf(customer);
    if (upmostParent != null) {
        LocalDate parentCustomerActiviationDate = new LocalDate(upmostParent.getCustomerActivationDate());
        LocalDate childCustomerActiviationDate = new LocalDate(customer.getCustomerActivationDate());

        LocalDate validCustomerMeetingMatch = null;
        if (customerMeetingEvent instanceof DailyScheduledEvent) {
            validCustomerMeetingMatch = new LocalDate(
                    parentCustomerActiviationDate.toDateMidnight().toDateTime());
        } else {
            validCustomerMeetingMatch = new LocalDate(
                    customerMeetingEvent.nearestMatchNotTakingIntoAccountScheduleFrequency(
                            parentCustomerActiviationDate.toDateMidnight().toDateTime()));
        }

        while (childCustomerActiviationDate.isAfter(validCustomerMeetingMatch)) {
            validCustomerMeetingMatch = new LocalDate(customerMeetingEvent
                    .rollFrowardDateByFrequency(validCustomerMeetingMatch.toDateMidnight().toDateTime()));
        }

        beginningFrom = validCustomerMeetingMatch.toDateMidnight().toDateTime();
    }

    DateTime meetingStartDate = new DateTime(customer.getCustomerMeetingValue().getMeetingStartDate());
    if (beginningFrom.isBefore(meetingStartDate)) {
        beginningFrom = meetingStartDate;
    }

    createInitialSetOfCustomerScheduleEntities(customer, beginningFrom, applicableCalendarEvents,
            customerMeetingEvent);

    applyFeesToInitialSetOfInstallments(new ArrayList<AccountFeesEntity>(accountFees), customerMeetingEvent);
}

From source file:org.mifos.platform.cashflow.ui.controller.CashFlowController.java

License:Open Source License

private boolean isAfterOrOnDisbursementMonthYear(LocalDate date, LocalDate comparedWith) {
    return isSameMonthYear(date, comparedWith) || (date.isAfter(comparedWith));
}

From source file:org.mifosplatform.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

License:Mozilla Public License

private CommandProcessingResult doTransactionForCashier(final Long cashierId, final CashierTxnType txnType,
        JsonCommand command) {//from w  w w  .j  av a2 s .c o  m
    try {
        final AppUser currentUser = this.context.authenticatedUser();

        final Cashier cashier = this.cashierRepository.findOne(cashierId);
        if (cashier == null) {
            throw new CashierNotFoundException(cashierId);
        }

        if (txnType.equals(CashierTxnType.SETTLE)) {

            final TellerData tellerData = this.tellerManagementReadPlatformService
                    .findTeller(cashier.getTeller().getId());

            this.fromApiJsonDeserializer.validateForCashSettleTxnForCashier(command.json(),
                    tellerData.getBalance(), cashier.getStartLocalDate());

        } else if (txnType.equals(CashierTxnType.ALLOCATE)) {

            this.fromApiJsonDeserializer.validateForCashTxnForCashier(command.json(),
                    cashier.getStartLocalDate());

            FinancialActivityAccount mainVaultFinancialActivityAccount = this.financialActivityAccountRepositoryWrapper
                    .findByFinancialActivityTypeWithNotFoundDetection(
                            FINANCIAL_ACTIVITY.CASH_AT_MAINVAULT.getValue());

            JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(
                    false, true, false, false, false, false);

            GLAccountData glAccountData = this.glAccountReadPlatformService.retrieveGLAccountById(
                    mainVaultFinancialActivityAccount.getGlAccount().getId(), associationParametersData);

            final BigDecimal txnAmount = command.bigDecimalValueOfParameterNamed("txnAmount");

            if (txnAmount.compareTo(new BigDecimal(glAccountData.getOrganizationRunningBalance())) > 0) {

                throw new NotEnoughCashInTheMainVaultTellerException(glAccountData.getId());
            }
        }

        final LocalDate transactionDate = command.localDateValueOfParameterNamed("txnDate");
        final LocalDate todaysDate = new LocalDate();

        // make sure that a future date cannot be used as transaction date
        if (transactionDate.isAfter(todaysDate)) {
            throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.FUTURE_DATE,
                    transactionDate.toDate(), null, null);
        }

        final String entityType = command.stringValueOfParameterNamed("entityType");
        final Long entityId = command.longValueOfParameterNamed("entityId");
        if (entityType != null) {
            if (entityType.equals("loan account")) {
                // TODO : Check if loan account exists
                // LoanAccount loan = null;
                // if (loan == null) { throw new
                // LoanAccountFoundException(entityId); }
            } else if (entityType.equals("savings account")) {
                // TODO : Check if loan account exists
                // SavingsAccount savingsaccount = null;
                // if (savingsaccount == null) { throw new
                // SavingsAccountNotFoundException(entityId); }

            }
            if (entityType.equals("client")) {
                // TODO: Check if client exists
                // Client client = null;
                // if (client == null) { throw new
                // ClientNotFoundException(entityId); }
            } else {
                // TODO : Invalid type handling
            }
        }

        final CashierTransaction cashierTxn = CashierTransaction.fromJson(cashier, command);
        cashierTxn.setTxnType(txnType.getId());

        this.cashierTxnRepository.save(cashierTxn);

        // Pass the journal entries
        FinancialActivityAccount mainVaultFinancialActivityAccount = this.financialActivityAccountRepositoryWrapper
                .findByFinancialActivityTypeWithNotFoundDetection(
                        FINANCIAL_ACTIVITY.CASH_AT_MAINVAULT.getValue());
        FinancialActivityAccount tellerCashFinancialActivityAccount = this.financialActivityAccountRepositoryWrapper
                .findByFinancialActivityTypeWithNotFoundDetection(FINANCIAL_ACTIVITY.CASH_AT_TELLER.getValue());
        GLAccount creditAccount = null;
        GLAccount debitAccount = null;
        if (txnType.equals(CashierTxnType.ALLOCATE)) {
            debitAccount = tellerCashFinancialActivityAccount.getGlAccount();
            creditAccount = mainVaultFinancialActivityAccount.getGlAccount();
        } else if (txnType.equals(CashierTxnType.SETTLE)) {
            debitAccount = mainVaultFinancialActivityAccount.getGlAccount();
            creditAccount = tellerCashFinancialActivityAccount.getGlAccount();
        }

        final Office cashierOffice = cashier.getTeller().getOffice();

        // final Long time = System.currentTimeMillis();
        //final String uniqueVal = String.valueOf(time) + currentUser.getId() + cashierOffice.getId();

        final String transactionId = "C" + cashierTxn.getId(); // Long.toHexString(Long.parseLong(uniqueVal));

        ClientTransaction clientTransaction = null;

        final JournalEntry debitJournalEntry = JournalEntry.createNew(cashierOffice, null, // payment
                // detail
                debitAccount, cashierTxn.getCurrencyCode(),
                // transaction
                transactionId, false, // manual entry
                cashierTxn.getTxnDate(), JournalEntryType.DEBIT, cashierTxn.getTxnAmount(),
                cashierTxn.getTxnNote(), // Description
                PortfolioProductType.CASHIERTRANSACTION.getValue(), cashierTxn.getId(), null, // entity Type, entityId, reference number
                null, null, clientTransaction); // Loan and Savings Txn

        final JournalEntry creditJournalEntry = JournalEntry.createNew(cashierOffice, null, // payment
                // detail
                creditAccount, cashierTxn.getCurrencyCode(),
                // transaction
                transactionId, false, // manual entry
                cashierTxn.getTxnDate(), JournalEntryType.CREDIT, cashierTxn.getTxnAmount(),
                cashierTxn.getTxnNote(), // Description
                PortfolioProductType.CASHIERTRANSACTION.getValue(), cashierTxn.getId(), null, // entity Type, entityId, reference number
                null, null, clientTransaction); // Loan and Savings Txn

        this.glJournalEntryRepository.saveAndFlush(debitJournalEntry);
        this.glJournalEntryRepository.saveAndFlush(creditJournalEntry);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(cashier.getId()) //
                .withSubEntityId(cashierTxn.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleTellerDataIntegrityIssues(command, dve);
        return CommandProcessingResult.empty();
    }
}