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.angnysa.yaba.service.impl.DefaultTransactionService.java

License:Open Source License

@Override
public List<Transaction> computeTransactions(TransactionDefinition td, LocalDate start, LocalDate end) {

    if (start.isAfter(end)) {
        throw new IllegalArgumentException("start is after end");
    }//from  w  w w  .  ja v a 2 s .  c  o m

    List<Transaction> result = new ArrayList<Transaction>();

    if (td.getPeriod() == null) {
        // non repeating
        if ((td.getDate().isAfter(start) || td.getDate().isEqual(start))
                && (td.getDate().isBefore(end) || td.getDate().isEqual(end))) {

            Transaction at = new Transaction();
            at.setTransactionId(td.getId());
            at.setDate(td.getDate());
            at.setAmount(td.getAmount());
            result.add(at);
        }
    } else {
        // repeating

        // get first valid date
        LocalDate current = td.getDate();
        while (current.isBefore(start)) {
            current = current.plus(td.getPeriod());
        }

        // get true last limit
        if (td.getEnd() != null && td.getEnd().isBefore(end)) {
            end = td.getEnd();
        }

        // list occurrences
        while (current.isBefore(end) || current.isEqual(end)) {

            Transaction at = new Transaction();
            at.setTransactionId(td.getId());
            at.setDate(current);
            if (td.getReconciliation(current) == null) {
                at.setAmount(td.getAmount());
            } else {
                at.setAmount(td.getReconciliation(current));
            }
            result.add(at);

            current = current.plus(td.getPeriod());
        }
    }

    Collections.sort(result, new Comparator<Transaction>() {

        @Override
        public int compare(Transaction t1, Transaction t2) {
            return t1.getDate().compareTo(t2.getDate());
        }
    });

    return result;
}

From source file:org.angnysa.yaba.service.impl.DefaultTransactionService.java

License:Open Source License

@Override
public List<SimulationDetail> simulate(double initial, LocalDate start, LocalDate end, ReadablePeriod period) {

    List<SimulationDetail> result = new ArrayList<SimulationDetail>();

    trs_loop: for (TransactionDefinition td : getAll()) {
        // current insertion point (CIP)
        int cip = 0;
        // the amount added/removed by the current actual transaction (AT)
        double delta = 0D;

        // init/*w w w .  j  a v  a 2 s  .c o  m*/
        if (cip >= result.size()) {
            SimulationDetail detail = new SimulationDetail();
            detail.setDate(start);
            detail.setRemainingAmount(initial);
            result.add(detail);
        }

        for (Transaction t : computeTransactions(td, start, end)) {

            // if the AT occurs after the CIP,
            // update all CIP until we find the next valid CIP
            while (t.getDate().isAfter(result.get(cip).getDate())) {

                result.get(cip).setRemainingAmount(result.get(cip).getRemainingAmount() + delta);

                cip++;

                // init
                if (cip >= result.size()) {

                    LocalDate date = result.get(cip - 1).getDate().plus(period);
                    // if the end date doesn't end a full period, we can have some transactions that cannot be properly used.
                    // we stop here if it's the case.
                    if (date.isAfter(end)) {
                        continue trs_loop;
                    }

                    SimulationDetail detail = new SimulationDetail();
                    detail.setDate(date);
                    detail.setRemainingAmount(initial);
                    result.add(detail);
                }
            }

            // store the AT in its CIP
            result.get(cip).getTransactions().add(t);

            // update the delta
            delta += t.getAmount();
        }

        // update all remaining points
        LocalDate date = result.get(cip).getDate();
        while (!date.isAfter(end)) {

            //init
            if (cip >= result.size()) {
                SimulationDetail detail = new SimulationDetail();
                detail.setDate(date);
                detail.setRemainingAmount(initial);
                result.add(detail);
            }

            result.get(cip).setRemainingAmount(result.get(cip).getRemainingAmount() + delta);

            date = date.plus(period);
            cip++;
        }
    }

    return result;
}

From source file:org.apache.fineract.organisation.teller.data.CashierTransactionDataValidator.java

License:Apache License

public void validateCashierAllowedDateAndTime(final Cashier cashier, final Teller teller) {
    Long staffId = cashier.getStaff().getId();
    final LocalDate fromDate = new LocalDate(cashier.getStartDate());
    final LocalDate endDate = new LocalDate(cashier.getEndDate());
    final LocalDate tellerFromDate = teller.getStartLocalDate();
    final LocalDate tellerEndDate = teller.getEndLocalDate();
    /**/*from  ww w .  ja v  a  2s .com*/
     * to validate cashier date range in range of teller date range
     */
    if (fromDate.isBefore(tellerFromDate) || endDate.isBefore(tellerFromDate)
            || (tellerEndDate != null && fromDate.isAfter(tellerEndDate) || endDate.isAfter(tellerEndDate))) {
        throw new CashierDateRangeOutOfTellerDateRangeException();
    }
    /**
     * to validate cashier has not been assigned for same duration
     */
    String sql = "select count(*) from m_cashiers c where c.staff_id = " + staffId + " AND " + "(('" + fromDate
            + "' BETWEEN c.start_date AND c.end_date OR '" + endDate + "' BETWEEN c.start_date AND c.end_date )"
            + " OR ( c.start_date BETWEEN '" + fromDate + "' AND '" + endDate + "' OR c.end_date BETWEEN '"
            + fromDate + "' AND '" + endDate + "'))";
    if (!cashier.isFullDay()) {
        String startTime = cashier.getStartTime();
        String endTime = cashier.getEndTime();
        sql = sql + " AND ( Time(c.start_time) BETWEEN TIME('" + startTime + "') and TIME('" + endTime
                + "') or Time(c.end_time) BETWEEN TIME('" + startTime + "') and TIME('" + endTime + "')) ";
    }
    int count = this.jdbcTemplate.queryForObject(sql, Integer.class);
    if (count > 0) {
        throw new CashierAlreadyAlloacated();
    }
}

From source file:org.apache.fineract.portfolio.calendar.service.CalendarWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Override
public CommandProcessingResult updateCalendar(final JsonCommand command) {

    /** Validate to check if Edit is Allowed **/
    this.validateIsEditMeetingAllowed(command.getGroupId());
    /*//from w w  w  .ja  va 2s  . com
     * 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.apache.fineract.portfolio.client.domain.Client.java

License:Apache 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 Integer legalForm, 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  . ja  v  a 2 s  .  c  o 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, legalForm);
}

From source file:org.apache.fineract.portfolio.floatingrates.domain.FloatingRate.java

License:Apache License

private void updateRatePeriods(final Set<FloatingRatePeriod> newRatePeriods, final AppUser appUser) {
    final LocalDate today = DateUtils.getLocalDateOfTenant();
    if (this.floatingRatePeriods != null) {
        for (FloatingRatePeriod ratePeriod : this.floatingRatePeriods) {
            LocalDate fromDate = LocalDate.fromDateFields(ratePeriod.getFromDate());
            if (fromDate.isAfter(today)) {
                ratePeriod.setActive(false);
                ratePeriod.setModifiedBy(appUser);
                ratePeriod.setModifiedOn(today.toDate());
            }//from w w  w.  j  a v  a  2 s .  c  o m
        }
    }
    for (FloatingRatePeriod newRatePeriod : newRatePeriods) {
        newRatePeriod.updateFloatingRate(this);
        this.floatingRatePeriods.add(newRatePeriod);
    }
}

From source file:org.apache.fineract.portfolio.group.service.GroupingTypesWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

private CommandProcessingResult createGroupingType(final JsonCommand command, final GroupTypes groupingType,
        final Long centerId) {
    try {//from   w  w  w.  ja va2 s .co m
        final String accountNo = command
                .stringValueOfParameterNamed(GroupingTypesApiConstants.accountNoParamName);
        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, accountNo);

        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();

        /* Generate account number if required */
        generateAccountNumberIfRequired(newGroup);

        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.apache.fineract.portfolio.interestratechart.data.InterestRateChartDataValidator.java

License:Apache License

public void validateForCreate(final String json, final DataValidatorBuilder baseDataValidator) {
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();/*from ww w.  ja  v  a  2 s  . c  om*/
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
            INTERESTRATE_CHART_CREATE_REQUEST_DATA_PARAMETERS);

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    if (this.fromApiJsonHelper.parameterExists(nameParamName, element)) {
        final String name = this.fromApiJsonHelper.extractStringNamed(nameParamName, element);
        baseDataValidator.reset().parameter(nameParamName).value(name).notBlank();
    }

    if (this.fromApiJsonHelper.parameterExists(descriptionParamName, element)) {
        final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element);
        baseDataValidator.reset().parameter(descriptionParamName).value(description).notNull();
    }

    final LocalDate fromDate = this.fromApiJsonHelper.extractLocalDateNamed(fromDateParamName, element);
    baseDataValidator.reset().parameter(fromDateParamName).value(fromDate).notNull();

    LocalDate toDate = null;
    if (this.fromApiJsonHelper.parameterExists(endDateParamName, element)) {
        toDate = this.fromApiJsonHelper.extractLocalDateNamed(endDateParamName, element);
        baseDataValidator.reset().parameter(endDateParamName).value(toDate).notNull();
    }

    if (fromDate != null && toDate != null) {
        if (fromDate.isAfter(toDate)) {
            baseDataValidator.parameter(fromDateParamName).value(fromDate)
                    .failWithCode("from.date.is.after.to.date");
        }
    }

    // validate chart Slabs
    validateChartSlabs(element, baseDataValidator);
}

From source file:org.apache.fineract.portfolio.interestratechart.data.InterestRateChartDataValidator.java

License:Apache License

public void validateForUpdate(final String json, final DataValidatorBuilder baseDataValidator) {
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();/*  w ww.j  a  v a  2  s. c om*/
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
            INTERESTRATE_CHART_UPDATE_REQUEST_DATA_PARAMETERS);

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    if (this.fromApiJsonHelper.parameterExists(productIdParamName, element)) {
        final Long savingsProductId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element);
        baseDataValidator.reset().parameter(productIdParamName).value(savingsProductId).notNull()
                .integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists(nameParamName, element)) {
        final String name = this.fromApiJsonHelper.extractStringNamed(nameParamName, element);
        baseDataValidator.reset().parameter(nameParamName).value(name).notBlank();
    }

    if (this.fromApiJsonHelper.parameterExists(descriptionParamName, element)) {
        final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element);
        baseDataValidator.reset().parameter(descriptionParamName).value(description).notNull();
    }

    LocalDate fromDate = null;
    if (this.fromApiJsonHelper.parameterExists(fromDateParamName, element)) {
        fromDate = this.fromApiJsonHelper.extractLocalDateNamed(fromDateParamName, element);
        baseDataValidator.reset().parameter(fromDateParamName).value(fromDate).notNull();
    }

    LocalDate toDate = null;
    if (this.fromApiJsonHelper.parameterExists(endDateParamName, element)) {
        toDate = this.fromApiJsonHelper.extractLocalDateNamed(endDateParamName, element);
        baseDataValidator.reset().parameter(endDateParamName).value(toDate).notNull();
    }

    if (fromDate != null && toDate != null) {
        if (fromDate.isAfter(toDate)) {
            baseDataValidator.parameter(fromDateParamName).value(fromDate)
                    .failWithCode("from.date.is.after.to.date");
        }
    }

    validateChartSlabs(element, baseDataValidator);

}

From source file:org.apache.fineract.portfolio.loanaccount.domain.Loan.java

License:Apache License

private BigDecimal calculateOverdueAmountPercentageAppliedTo(final LoanCharge loanCharge,
        final int penaltyWaitPeriod) {
    LoanRepaymentScheduleInstallment installment = loanCharge.getOverdueInstallmentCharge().getInstallment();
    LocalDate graceDate = LocalDate.now().minusDays(penaltyWaitPeriod);
    Money amount = Money.zero(getCurrency());
    if (graceDate.isAfter(installment.getDueDate())) {
        amount = calculateOverdueAmountPercentageAppliedTo(installment, loanCharge.getChargeCalculation());
        if (!amount.isGreaterThanZero()) {
            loanCharge.setActive(false);
        }//  w w w .  j  av a2  s. c  om
    } else {
        loanCharge.setActive(false);
    }
    return amount.getAmount();
}