List of usage examples for org.joda.time LocalDate toString
public String toString(String pattern)
From source file:com.gst.infrastructure.campaigns.sms.domain.SmsCampaign.java
License:Apache License
public void activate(final AppUser currentUser, final DateTimeFormatter formatter, final LocalDate activationLocalDate) { if (isActive()) { // handle errors if already activated final String defaultUserMessage = "Cannot activate campaign. Campaign is already active."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.campaign.already.active", defaultUserMessage, SmsCampaignValidator.activationDateParamName, activationLocalDate.toString(formatter)); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); }// w ww . java 2s. c o m this.approvedOnDate = activationLocalDate.toDate(); this.approvedBy = currentUser; this.status = SmsCampaignStatus.ACTIVE.getValue(); validate(); }
From source file:com.gst.portfolio.calendar.service.CalendarUtils.java
License:Apache License
public static String getRRuleReadable(final LocalDate startDate, final String recurringRule) { String humanReadable = ""; RRule rrule;// w w w .j a v a 2 s.co m Recur recur = null; try { rrule = new RRule(recurringRule); rrule.validate(); recur = rrule.getRecur(); } catch (final ValidationException e) { throw new PlatformDataIntegrityException("error.msg.invalid.recurring.rule", "The Recurring Rule value: " + recurringRule + " is not valid.", "recurrence", recurringRule); } catch (final ParseException e) { throw new PlatformDataIntegrityException("error.msg.recurring.rule.parsing.error", "Error in pasring the Recurring Rule value: " + recurringRule, "recurrence", recurringRule); } if (recur == null) { return humanReadable; } if (recur.getFrequency().equals(Recur.DAILY)) { if (recur.getInterval() == 1) { humanReadable = "Daily"; } else { humanReadable = "Every " + recur.getInterval() + " days"; } } else if (recur.getFrequency().equals(Recur.WEEKLY)) { if (recur.getInterval() == 1 || recur.getInterval() == -1) { humanReadable = "Weekly"; } else { humanReadable = "Every " + recur.getInterval() + " weeks"; } humanReadable += " on "; final WeekDayList weekDayList = recur.getDayList(); for (@SuppressWarnings("rawtypes") final Iterator iterator = weekDayList.iterator(); iterator.hasNext();) { final WeekDay weekDay = (WeekDay) iterator.next(); humanReadable += DayNameEnum.from(weekDay.getDay()).getCode(); } } else if (recur.getFrequency().equals(Recur.MONTHLY)) { NumberList nthDays = recur.getSetPosList(); Integer nthDay = null; if (!nthDays.isEmpty()) nthDay = (Integer) nthDays.get(0); NumberList monthDays = recur.getMonthDayList(); Integer monthDay = null; if (!monthDays.isEmpty()) monthDay = (Integer) monthDays.get(0); WeekDayList weekdays = recur.getDayList(); WeekDay weekDay = null; if (!weekdays.isEmpty()) weekDay = (WeekDay) weekdays.get(0); if (nthDay != null && weekDay != null) { NthDayType nthDayType = NthDayType.fromInt(nthDay); NthDayNameEnum nthDayName = NthDayNameEnum.from(nthDayType.toString()); DayNameEnum weekdayType = DayNameEnum.from(weekDay.getDay()); if (recur.getInterval() == 1 || recur.getInterval() == -1) { humanReadable = "Monthly on " + nthDayName.getCode().toLowerCase() + " " + weekdayType.getCode().toLowerCase(); } else { humanReadable = "Every " + recur.getInterval() + " months on " + nthDayName.getCode().toLowerCase() + " " + weekdayType.getCode().toLowerCase(); } } else if (monthDay != null) { if (monthDay == -1) { if (recur.getInterval() == 1 || recur.getInterval() == -1) { humanReadable = "Monthly on last day"; } else { humanReadable = "Every " + recur.getInterval() + " months on last day"; } } else { if (recur.getInterval() == 1 || recur.getInterval() == -1) { humanReadable = "Monthly on day " + monthDay; } else { humanReadable = "Every " + recur.getInterval() + " months on day " + monthDay; } } } else { if (recur.getInterval() == 1 || recur.getInterval() == -1) { humanReadable = "Monthly on day " + startDate.getDayOfMonth(); } else { humanReadable = "Every " + recur.getInterval() + " months on day " + startDate.getDayOfMonth(); } } } else if (recur.getFrequency().equals(Recur.YEARLY)) { if (recur.getInterval() == 1) { humanReadable = "Annually on " + startDate.toString("MMM") + " " + startDate.getDayOfMonth(); } else { humanReadable = "Every " + recur.getInterval() + " years on " + startDate.toString("MMM") + " " + startDate.getDayOfMonth(); } } if (recur.getCount() > 0) { if (recur.getCount() == 1) { humanReadable = "Once"; } humanReadable += ", " + recur.getCount() + " times"; } final Date endDate = recur.getUntil(); final LocalDate date = new LocalDate(endDate); final DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MMMM YY"); final String formattedDate = date.toString(fmt); if (endDate != null) { humanReadable += ", until " + formattedDate; } return humanReadable; }
From source file:com.gst.portfolio.client.domain.Client.java
License:Apache License
public void activate(final AppUser currentUser, final DateTimeFormatter formatter, final LocalDate activationLocalDate) { if (isActive()) { final String defaultUserMessage = "Cannot activate client. Client is already active."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.clients.already.active", defaultUserMessage, ClientApiConstants.activationDateParamName, activationLocalDate.toString(formatter)); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); }//from w w w. j a va2 s.c o m this.activationDate = activationLocalDate.toDate(); this.activatedBy = currentUser; this.officeJoiningDate = this.activationDate; this.status = ClientStatus.ACTIVE.getValue(); // in case a closed client is being re open this.closureDate = null; this.closureReason = null; this.closedBy = null; validate(); }
From source file:com.gst.portfolio.client.service.ClientChargeWritePlatformServiceJpaRepositoryImpl.java
License:Apache License
@Override public CommandProcessingResult addCharge(Long clientId, JsonCommand command) { try {//from ww w.j av a 2 s . com this.clientChargeDataValidator.validateAdd(command.json()); final Client client = clientRepository.getActiveClientInUserScope(clientId); final Long chargeDefinitionId = command.longValueOfParameterNamed(ClientApiConstants.chargeIdParamName); final Charge charge = this.chargeRepository.findOneWithNotFoundDetection(chargeDefinitionId); // validate for client charge if (!charge.isClientCharge()) { final String errorMessage = "Charge with identifier " + charge.getId() + " cannot be applied to a Client"; throw new ChargeCannotBeAppliedToException("client", errorMessage, charge.getId()); } final ClientCharge clientCharge = ClientCharge.createNew(client, charge, command); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); LocalDate activationDate = client.getActivationLocalDate(); LocalDate dueDate = clientCharge.getDueLocalDate(); if (dueDate.isBefore(activationDate)) { baseDataValidator.reset().parameter(ClientApiConstants.dueAsOfDateParamName) .value(dueDate.toString(fmt)) .failWithCodeNoParameterAddedToErrorCode("dueDate.before.activationDate"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } validateDueDateOnWorkingDay(clientCharge, fmt); this.clientChargeRepository.saveAndFlush(clientCharge); return new CommandProcessingResultBuilder() // .withEntityId(clientCharge.getId()) // .withOfficeId(clientCharge.getClient().getOffice().getId()) // .withClientId(clientCharge.getClient().getId()) // .build(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(clientId, null, dve); return CommandProcessingResult.empty(); } }
From source file:com.gst.portfolio.client.service.ClientChargeWritePlatformServiceJpaRepositoryImpl.java
License:Apache License
/** * Validates transaction to ensure that <br> * charge is active <br>/*w w w.j a v a 2s. c om*/ * transaction date is valid (between client activation and todays date) * <br> * charge is not already paid or waived <br> * amount is not more than total due * * @param client * @param clientCharge * @param fmt * @param transactionDate * @param amountPaid * @param requiresTransactionDateValidation * if set to false, transaction date specific validation is * skipped * @param requiresTransactionAmountValidation * if set to false transaction amount validation is skipped * @return */ private void validatePaymentDateAndAmount(final Client client, final ClientCharge clientCharge, final DateTimeFormatter fmt, final LocalDate transactionDate, final BigDecimal amountPaid, final boolean requiresTransactionDateValidation, final boolean requiresTransactionAmountValidation) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); if (clientCharge.isNotActive()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("charge.is.not.active"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (requiresTransactionDateValidation) { validateTransactionDateOnWorkingDay(transactionDate, clientCharge, fmt); if (client.getActivationLocalDate() != null && transactionDate.isBefore(client.getActivationLocalDate())) { baseDataValidator.reset().parameter(ClientApiConstants.transactionDateParamName) .value(transactionDate.toString(fmt)) .failWithCodeNoParameterAddedToErrorCode("transaction.before.activationDate"); throw new PlatformApiDataValidationException(dataValidationErrors); } if (DateUtils.isDateInTheFuture(transactionDate)) { baseDataValidator.reset().parameter(ClientApiConstants.transactionDateParamName) .value(transactionDate.toString(fmt)) .failWithCodeNoParameterAddedToErrorCode("transaction.is.futureDate"); throw new PlatformApiDataValidationException(dataValidationErrors); } } // validate charge is not already paid or waived if (clientCharge.isWaived()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( "transaction.invalid.account.charge.is.already.waived"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } else if (clientCharge.isPaid()) { baseDataValidator.reset() .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.paid"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (requiresTransactionAmountValidation) { final Money chargePaid = Money.of(clientCharge.getCurrency(), amountPaid); if (!clientCharge.getAmountOutstanding().isGreaterThanOrEqualTo(chargePaid)) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( "transaction.invalid.charge.amount.paid.in.access"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } }
From source file:com.gst.portfolio.client.service.ClientChargeWritePlatformServiceJpaRepositoryImpl.java
License:Apache License
/** * @param date//from w w w.j av a2 s . c o m * @param officeId * @param jsonPropertyName * @param errorMessageFragment * @param fmt */ private void validateActivityDateFallOnAWorkingDay(final LocalDate date, final Long officeId, final String jsonPropertyName, final String errorMessageFragmentForActivityOnHoliday, final String errorMessageFragmentForActivityOnNonWorkingDay, final DateTimeFormatter fmt) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); if (date != null) { // transaction date should not be on a holiday or non working day if (!this.configurationDomainService.allowTransactionsOnHolidayEnabled() && this.holidayRepository.isHoliday(officeId, date)) { baseDataValidator.reset().parameter(jsonPropertyName).value(date.toString(fmt)) .failWithCodeNoParameterAddedToErrorCode(errorMessageFragmentForActivityOnHoliday); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (!this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled() && !this.workingDaysRepository.isWorkingDay(date)) { baseDataValidator.reset().parameter(jsonPropertyName).value(date.toString(fmt)) .failWithCodeNoParameterAddedToErrorCode(errorMessageFragmentForActivityOnNonWorkingDay); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } }
From source file:com.gst.portfolio.loanaccount.domain.Loan.java
License:Apache License
public Map<String, Object> loanApplicationRejection(final AppUser currentUser, final JsonCommand command, final LoanLifecycleStateMachine loanLifecycleStateMachine) { validateAccountStatus(LoanEvent.LOAN_REJECTED); final Map<String, Object> actualChanges = new LinkedHashMap<>(); final LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.LOAN_REJECTED, LoanStatus.fromInt(this.loanStatus)); if (!statusEnum.hasStateOf(LoanStatus.fromInt(this.loanStatus))) { this.loanStatus = statusEnum.getValue(); actualChanges.put("status", LoanEnumerations.status(this.loanStatus)); final LocalDate rejectedOn = command.localDateValueOfParameterNamed("rejectedOnDate"); final Locale locale = new Locale(command.locale()); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); this.rejectedOnDate = rejectedOn.toDate(); this.rejectedBy = currentUser; this.closedOnDate = rejectedOn.toDate(); this.closedBy = currentUser; actualChanges.put("locale", command.locale()); actualChanges.put("dateFormat", command.dateFormat()); actualChanges.put("rejectedOnDate", rejectedOn.toString(fmt)); actualChanges.put("closedOnDate", rejectedOn.toString(fmt)); if (rejectedOn.isBefore(getSubmittedOnDate())) { final String errorMessage = "The date on which a loan is rejected cannot be before its submittal date: " + getSubmittedOnDate().toString(); throw new InvalidLoanStateTransitionException("reject", "cannot.be.before.submittal.date", errorMessage, rejectedOn, getSubmittedOnDate()); }/* w w w . j ava2 s .co m*/ validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_REJECTED, rejectedOn); if (rejectedOn.isAfter(DateUtils.getLocalDateOfTenant())) { final String errorMessage = "The date on which a loan is rejected cannot be in the future."; throw new InvalidLoanStateTransitionException("reject", "cannot.be.a.future.date", errorMessage, rejectedOn); } } else { final String errorMessage = "Only the loan applications with status 'Submitted and pending approval' are allowed to be rejected."; throw new InvalidLoanStateTransitionException("reject", "cannot.reject", errorMessage); } return actualChanges; }
From source file:com.gst.portfolio.loanaccount.domain.Loan.java
License:Apache License
public Map<String, Object> loanApplicationWithdrawnByApplicant(final AppUser currentUser, final JsonCommand command, final LoanLifecycleStateMachine loanLifecycleStateMachine) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.LOAN_WITHDRAWN, LoanStatus.fromInt(this.loanStatus)); if (!statusEnum.hasStateOf(LoanStatus.fromInt(this.loanStatus))) { this.loanStatus = statusEnum.getValue(); actualChanges.put("status", LoanEnumerations.status(this.loanStatus)); LocalDate withdrawnOn = command.localDateValueOfParameterNamed("withdrawnOnDate"); if (withdrawnOn == null) { withdrawnOn = command.localDateValueOfParameterNamed("eventDate"); }//from www . j a v a 2s. c om final Locale locale = new Locale(command.locale()); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); this.withdrawnOnDate = withdrawnOn.toDate(); this.withdrawnBy = currentUser; this.closedOnDate = withdrawnOn.toDate(); this.closedBy = currentUser; actualChanges.put("locale", command.locale()); actualChanges.put("dateFormat", command.dateFormat()); actualChanges.put("withdrawnOnDate", withdrawnOn.toString(fmt)); actualChanges.put("closedOnDate", withdrawnOn.toString(fmt)); if (withdrawnOn.isBefore(getSubmittedOnDate())) { final String errorMessage = "The date on which a loan is withdrawn cannot be before its submittal date: " + getSubmittedOnDate().toString(); throw new InvalidLoanStateTransitionException("withdraw", "cannot.be.before.submittal.date", errorMessage, command, getSubmittedOnDate()); } validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_WITHDRAWN, withdrawnOn); if (withdrawnOn.isAfter(DateUtils.getLocalDateOfTenant())) { final String errorMessage = "The date on which a loan is withdrawn cannot be in the future."; throw new InvalidLoanStateTransitionException("withdraw", "cannot.be.a.future.date", errorMessage, command); } } else { final String errorMessage = "Only the loan applications with status 'Submitted and pending approval' are allowed to be withdrawn by applicant."; throw new InvalidLoanStateTransitionException("withdraw", "cannot.withdraw", errorMessage); } return actualChanges; }
From source file:com.gst.portfolio.loanaccount.rescheduleloan.service.LoanRescheduleRequestWritePlatformServiceImpl.java
License:Apache License
@Override @Transactional/*from w ww. j a v a 2 s . com*/ public CommandProcessingResult approve(JsonCommand jsonCommand) { try { final Long loanRescheduleRequestId = jsonCommand.entityId(); final LoanRescheduleRequest loanRescheduleRequest = this.loanRescheduleRequestRepository .findOne(loanRescheduleRequestId); if (loanRescheduleRequest == null) { throw new LoanRescheduleRequestNotFoundException(loanRescheduleRequestId); } // validate the request in the JsonCommand object passed as // parameter this.loanRescheduleRequestDataValidator.validateForApproveAction(jsonCommand, loanRescheduleRequest); final AppUser appUser = this.platformSecurityContext.authenticatedUser(); final Map<String, Object> changes = new LinkedHashMap<>(); LocalDate approvedOnDate = jsonCommand.localDateValueOfParameterNamed("approvedOnDate"); final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()) .withLocale(jsonCommand.extractLocale()); changes.put("locale", jsonCommand.locale()); changes.put("dateFormat", jsonCommand.dateFormat()); changes.put("approvedOnDate", approvedOnDate.toString(dateTimeFormatter)); changes.put("approvedByUserId", appUser.getId()); Loan loan = loanRescheduleRequest.getLoan(); final List<Long> existingTransactionIds = new ArrayList<>(loan.findExistingTransactionIds()); final List<Long> existingReversedTransactionIds = new ArrayList<>( loan.findExistingReversedTransactionIds()); ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan, loanRescheduleRequest.getRescheduleFromDate()); Collection<LoanRepaymentScheduleHistory> loanRepaymentScheduleHistoryList = this.loanScheduleHistoryWritePlatformService .createLoanScheduleArchive(loan.getRepaymentScheduleInstallments(), loan, loanRescheduleRequest); final LoanApplicationTerms loanApplicationTerms = loan .constructLoanApplicationTerms(scheduleGeneratorDTO); LocalDate rescheduleFromDate = null; Set<LoanTermVariations> activeLoanTermVariations = loan.getActiveLoanTermVariations(); LoanTermVariations dueDateVariationInCurrentRequest = loanRescheduleRequest .getDueDateTermVariationIfExists(); if (dueDateVariationInCurrentRequest != null && activeLoanTermVariations != null) { LocalDate fromScheduleDate = dueDateVariationInCurrentRequest.fetchTermApplicaDate(); LocalDate currentScheduleDate = fromScheduleDate; LocalDate modifiedScheduleDate = dueDateVariationInCurrentRequest.fetchDateValue(); Map<LocalDate, LocalDate> changeMap = new HashMap<>(); changeMap.put(currentScheduleDate, modifiedScheduleDate); for (LoanTermVariations activeLoanTermVariation : activeLoanTermVariations) { if (activeLoanTermVariation.getTermType().isDueDateVariation() && activeLoanTermVariation .fetchDateValue().equals(dueDateVariationInCurrentRequest.fetchTermApplicaDate())) { activeLoanTermVariation.markAsInactive(); rescheduleFromDate = activeLoanTermVariation.fetchTermApplicaDate(); dueDateVariationInCurrentRequest.setTermApplicableFrom(rescheduleFromDate.toDate()); } else if (!activeLoanTermVariation.fetchTermApplicaDate().isBefore(fromScheduleDate)) { while (currentScheduleDate.isBefore(activeLoanTermVariation.fetchTermApplicaDate())) { currentScheduleDate = this.scheduledDateGenerator.generateNextRepaymentDate( currentScheduleDate, loanApplicationTerms, false, loanApplicationTerms.getHolidayDetailDTO()); modifiedScheduleDate = this.scheduledDateGenerator.generateNextRepaymentDate( modifiedScheduleDate, loanApplicationTerms, false, loanApplicationTerms.getHolidayDetailDTO()); changeMap.put(currentScheduleDate, modifiedScheduleDate); } if (changeMap.containsKey(activeLoanTermVariation.fetchTermApplicaDate())) { activeLoanTermVariation.setTermApplicableFrom( changeMap.get(activeLoanTermVariation.fetchTermApplicaDate()).toDate()); } } } } if (rescheduleFromDate == null) { rescheduleFromDate = loanRescheduleRequest.getRescheduleFromDate(); } for (LoanRescheduleRequestToTermVariationMapping mapping : loanRescheduleRequest .getLoanRescheduleRequestToTermVariationMappings()) { mapping.getLoanTermVariations().updateIsActive(true); } BigDecimal annualNominalInterestRate = null; List<LoanTermVariationsData> loanTermVariations = new ArrayList<>(); loan.constructLoanTermVariations(scheduleGeneratorDTO.getFloatingRateDTO(), annualNominalInterestRate, loanTermVariations); loanApplicationTerms.getLoanTermVariations().setExceptionData(loanTermVariations); /*for (LoanTermVariationsData loanTermVariation : loanApplicationTerms.getLoanTermVariations().getDueDateVariation()) { if (rescheduleFromDate.isBefore(loanTermVariation.getTermApplicableFrom())) { LocalDate applicableDate = this.scheduledDateGenerator.generateNextRepaymentDate(rescheduleFromDate, loanApplicationTerms, false, loanApplicationTerms.getHolidayDetailDTO()); if (loanTermVariation.getTermApplicableFrom().equals(applicableDate)) { LocalDate adjustedDate = this.scheduledDateGenerator.generateNextRepaymentDate(adjustedApplicableDate, loanApplicationTerms, false, loanApplicationTerms.getHolidayDetailDTO()); loanTermVariation.setApplicableFromDate(adjustedDate); } } }*/ final RoundingMode roundingMode = MoneyHelper.getRoundingMode(); final MathContext mathContext = new MathContext(8, roundingMode); final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor = this.loanRepaymentScheduleTransactionProcessorFactory .determineProcessor(loan.transactionProcessingStrategy()); final LoanScheduleGenerator loanScheduleGenerator = this.loanScheduleFactory .create(loanApplicationTerms.getInterestMethod()); final LoanLifecycleStateMachine loanLifecycleStateMachine = null; loan.setHelpers(loanLifecycleStateMachine, this.loanSummaryWrapper, this.loanRepaymentScheduleTransactionProcessorFactory); final LoanScheduleDTO loanSchedule = loanScheduleGenerator.rescheduleNextInstallments(mathContext, loanApplicationTerms, loan, loanApplicationTerms.getHolidayDetailDTO(), loanRepaymentScheduleTransactionProcessor, rescheduleFromDate); loan.updateLoanSchedule(loanSchedule.getInstallments(), appUser); loan.recalculateAllCharges(); ChangedTransactionDetail changedTransactionDetail = loan.processTransactions(); for (LoanRepaymentScheduleHistory loanRepaymentScheduleHistory : loanRepaymentScheduleHistoryList) { this.loanRepaymentScheduleHistoryRepository.save(loanRepaymentScheduleHistory); } loan.updateRescheduledByUser(appUser); loan.updateRescheduledOnDate(new LocalDate()); // update the status of the request loanRescheduleRequest.approve(appUser, approvedOnDate); // update the loan object saveAndFlushLoanWithDataIntegrityViolationChecks(loan); if (changedTransactionDetail != null) { for (final Map.Entry<Long, LoanTransaction> mapEntry : changedTransactionDetail .getNewTransactionMappings().entrySet()) { this.loanTransactionRepository.save(mapEntry.getValue()); // update loan with references to the newly created // transactions loan.addLoanTransaction(mapEntry.getValue()); this.accountTransfersWritePlatformService.updateLoanTransaction(mapEntry.getKey(), mapEntry.getValue()); } } postJournalEntries(loan, existingTransactionIds, existingReversedTransactionIds); this.loanAccountDomainService.recalculateAccruals(loan, true); return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()) .withEntityId(loanRescheduleRequestId).withLoanId(loanRescheduleRequest.getLoan().getId()) .with(changes).build(); } catch (final DataIntegrityViolationException dve) { // handle the data integrity violation handleDataIntegrityViolation(dve); // return an empty command processing result object return CommandProcessingResult.empty(); } }
From source file:com.gst.portfolio.loanaccount.rescheduleloan.service.LoanRescheduleRequestWritePlatformServiceImpl.java
License:Apache License
@Override @Transactional//from www .j a va 2s .c o m public CommandProcessingResult reject(JsonCommand jsonCommand) { try { final Long loanRescheduleRequestId = jsonCommand.entityId(); final LoanRescheduleRequest loanRescheduleRequest = loanRescheduleRequestRepository .findOne(loanRescheduleRequestId); if (loanRescheduleRequest == null) { throw new LoanRescheduleRequestNotFoundException(loanRescheduleRequestId); } // validate the request in the JsonCommand object passed as // parameter this.loanRescheduleRequestDataValidator.validateForRejectAction(jsonCommand, loanRescheduleRequest); final AppUser appUser = this.platformSecurityContext.authenticatedUser(); final Map<String, Object> changes = new LinkedHashMap<>(); LocalDate rejectedOnDate = jsonCommand.localDateValueOfParameterNamed("rejectedOnDate"); final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()) .withLocale(jsonCommand.extractLocale()); changes.put("locale", jsonCommand.locale()); changes.put("dateFormat", jsonCommand.dateFormat()); changes.put("rejectedOnDate", rejectedOnDate.toString(dateTimeFormatter)); changes.put("rejectedByUserId", appUser.getId()); if (!changes.isEmpty()) { loanRescheduleRequest.reject(appUser, rejectedOnDate); Set<LoanRescheduleRequestToTermVariationMapping> loanRescheduleRequestToTermVariationMappings = loanRescheduleRequest .getLoanRescheduleRequestToTermVariationMappings(); for (LoanRescheduleRequestToTermVariationMapping loanRescheduleRequestToTermVariationMapping : loanRescheduleRequestToTermVariationMappings) { loanRescheduleRequestToTermVariationMapping.getLoanTermVariations().markAsInactive(); } } return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()) .withEntityId(loanRescheduleRequestId).withLoanId(loanRescheduleRequest.getLoan().getId()) .with(changes).build(); } catch (final DataIntegrityViolationException dve) { // handle the data integrity violation handleDataIntegrityViolation(dve); // return an empty command processing result object return CommandProcessingResult.empty(); } }