Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

In this page you can find the example usage for java.math BigDecimal divide.

Prototype

public BigDecimal divide(BigDecimal divisor) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose preferred scale is (this.scale() - divisor.scale()) ; if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

Usage

From source file:org.kuali.kfs.module.purap.document.service.impl.PaymentRequestServiceImpl.java

/**
 * Calculates the discount item for this paymentRequest.
 *
 * @param paymentRequestDocument The payment request document whose discount to be calculated.
 *///from   w w w .ja v  a2s . c o m
protected void calculateDiscount(PaymentRequestDocument paymentRequestDocument) {
    PaymentRequestItem discountItem = findDiscountItem(paymentRequestDocument);
    // find out if we really need the discount item
    PaymentTermType pt = paymentRequestDocument.getVendorPaymentTerms();
    if ((pt != null) && (pt.getVendorPaymentTermsPercent() != null)
            && (BigDecimal.ZERO.compareTo(pt.getVendorPaymentTermsPercent()) != 0)) {
        if (discountItem == null) {
            // set discountItem and add to items
            // this is probably not the best way of doing it but should work for now if we start excluding discount from below
            // we will need to manually add
            purapService.addBelowLineItems(paymentRequestDocument);

            // fix up below the line items
            removeIneligibleAdditionalCharges(paymentRequestDocument);

            discountItem = findDiscountItem(paymentRequestDocument);
        }

        // Deleted the discountItem.getExtendedPrice() null and isZero
        PaymentRequestItem fullOrderItem = findFullOrderDiscountItem(paymentRequestDocument);
        KualiDecimal fullOrderAmount = KualiDecimal.ZERO;
        KualiDecimal fullOrderTaxAmount = KualiDecimal.ZERO;

        if (fullOrderItem != null) {
            fullOrderAmount = (ObjectUtils.isNotNull(fullOrderItem.getExtendedPrice()))
                    ? fullOrderItem.getExtendedPrice()
                    : KualiDecimal.ZERO;
            fullOrderTaxAmount = (ObjectUtils.isNotNull(fullOrderItem.getItemTaxAmount()))
                    ? fullOrderItem.getItemTaxAmount()
                    : KualiDecimal.ZERO;
        }
        KualiDecimal totalCost = paymentRequestDocument.getTotalPreTaxDollarAmountAboveLineItems()
                .add(fullOrderAmount);
        PurApItem tradeInItem = paymentRequestDocument.getTradeInItem();
        if (ObjectUtils.isNotNull(tradeInItem)) {
            totalCost = totalCost.add(tradeInItem.getTotalAmount());
        }
        BigDecimal discountAmount = pt.getVendorPaymentTermsPercent().multiply(totalCost.bigDecimalValue())
                .multiply(new BigDecimal(PurapConstants.PREQ_DISCOUNT_MULT));

        // do we really need to set both, not positive, but probably won't hurt
        discountItem.setItemUnitPrice(discountAmount.setScale(2, KualiDecimal.ROUND_BEHAVIOR));
        discountItem.setExtendedPrice(new KualiDecimal(discountAmount));

        // set tax amount
        boolean salesTaxInd = parameterService.getParameterValueAsBoolean(
                KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND);
        boolean useTaxIndicator = paymentRequestDocument.isUseTaxIndicator();

        if (salesTaxInd == true && useTaxIndicator == false) {
            KualiDecimal totalTax = paymentRequestDocument.getTotalTaxAmountAboveLineItems()
                    .add(fullOrderTaxAmount);
            BigDecimal discountTaxAmount = null;
            if (totalCost.isNonZero()) {
                discountTaxAmount = discountAmount.divide(totalCost.bigDecimalValue())
                        .multiply(totalTax.bigDecimalValue());
            } else {
                discountTaxAmount = BigDecimal.ZERO;
            }

            discountItem.setItemTaxAmount(new KualiDecimal(
                    discountTaxAmount.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
        }

        // set document
        discountItem.setPurapDocument(paymentRequestDocument);
    } else { // no discount
        if (discountItem != null) {
            paymentRequestDocument.getItems().remove(discountItem);
        }
    }

}

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

public void updateLoanCharges(final Set<LoanCharge> loanCharges) {
    setOfLoanCharges().clear();/*from   w  ww  . j a va2s .co  m*/
    for (final LoanCharge loanCharge : loanCharges) {
        loanCharge.update(this);
        final BigDecimal amount = calculateAmountPercentageAppliedTo(loanCharge);
        BigDecimal chargeAmt = BigDecimal.ZERO;
        BigDecimal totalChargeAmt = BigDecimal.ZERO;
        if (loanCharge.getChargeCalculation().isPercentageBased()) {
            chargeAmt = loanCharge.getPercentage();
            if (loanCharge.isInstalmentFee()) {
                totalChargeAmt = calculatePerInstallmentChargeAmount(loanCharge);
            }
        } else {
            chargeAmt = loanCharge.amount();
            if (loanCharge.isInstalmentFee()) {
                chargeAmt = chargeAmt
                        .divide(BigDecimal.valueOf(repaymentScheduleDetail().getNumberOfRepayments()));
            }
        }
        loanCharge.update(chargeAmt, loanCharge.getDueLocalDate(), amount,
                repaymentScheduleDetail().getNumberOfRepayments(), totalChargeAmt);
    }
    setOfLoanCharges().addAll(loanCharges);
    updateSummaryWithTotalFeeChargesDueAtDisbursement(deriveSumTotalOfChargesDueAtDisbursement());
}

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

public ChangedTransactionDetail addLoanCharge(final LoanCharge loanCharge,
        final List<Long> existingTransactionIds, final List<Long> existingReversedTransactionIds) {
    ChangedTransactionDetail changedTransactionDetail = null;

    validateLoanIsNotClosed(loanCharge);

    if (isDisbursed() && loanCharge.isDueAtDisbursement()) {
        // Note: added this constraint to restrict adding disbursement
        // charges to a loan
        // after it is disbursed
        // if the loan charge payment type is 'Disbursement'.
        // To undo this constraint would mean resolving how charges due are
        // disbursement are handled at present.
        // When a loan is disbursed and has charges due at disbursement, a
        // transaction is created to auto record
        // payment of the charges (user has no choice in saying they were or
        // werent paid) - so its assumed they were paid.

        final String defaultUserMessage = "This charge which is due at disbursement cannot be added as the loan is already disbursed.";
        throw new LoanChargeCannotBeAddedException("loanCharge", "due.at.disbursement.and.loan.is.disbursed",
                defaultUserMessage, getId(), loanCharge.name());
    }/*w  w  w.j  a  va  2 s  .  c  o m*/

    validateChargeHasValidSpecifiedDateIfApplicable(loanCharge, getDisbursementDate(),
            getLastRepaymentPeriodDueDate());

    this.summary = updateSummaryWithTotalFeeChargesDueAtDisbursement(
            deriveSumTotalOfChargesDueAtDisbursement());

    loanCharge.update(this);

    final BigDecimal amount = calculateAmountPercentageAppliedTo(loanCharge);
    BigDecimal chargeAmt = BigDecimal.ZERO;
    BigDecimal totalChargeAmt = BigDecimal.ZERO;
    if (loanCharge.getChargeCalculation().isPercentageBased()) {
        chargeAmt = loanCharge.getPercentage();
        if (loanCharge.isInstalmentFee()) {
            totalChargeAmt = calculatePerInstallmentChargeAmount(loanCharge);
        }
    } else {
        chargeAmt = loanCharge.amount();
        if (loanCharge.isInstalmentFee()) {
            chargeAmt = chargeAmt.divide(BigDecimal.valueOf(repaymentScheduleDetail().getNumberOfRepayments()));
        }
    }
    loanCharge.update(chargeAmt, loanCharge.getDueLocalDate(), amount,
            repaymentScheduleDetail().getNumberOfRepayments(), totalChargeAmt);

    // NOTE: must add new loan charge to set of loan charges before
    // reporcessing the repayment schedule.
    setOfLoanCharges().add(loanCharge);

    final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor = this.transactionProcessorFactory
            .determineProcessor(this.transactionProcessingStrategy);

    // store Id's of existing loan transactions and existing reversed loan
    // transactions
    existingTransactionIds.addAll(findExistingTransactionIds());
    existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
    final LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper();
    wrapper.reprocess(getCurrency(), getDisbursementDate(), this.repaymentScheduleInstallments,
            setOfLoanCharges());
    if (!loanCharge.isDueAtDisbursement()) {
        final List<LoanTransaction> allNonContraTransactionsPostDisbursement = retreiveListOfTransactionsPostDisbursement();
        changedTransactionDetail = loanRepaymentScheduleTransactionProcessor.handleTransaction(
                getDisbursementDate(), allNonContraTransactionsPostDisbursement, getCurrency(),
                this.repaymentScheduleInstallments, setOfLoanCharges());
        for (final Map.Entry<Long, LoanTransaction> mapEntry : changedTransactionDetail
                .getNewTransactionMappings().entrySet()) {
            mapEntry.getValue().updateLoan(this);
        }
        // this.loanTransactions.addAll(changedTransactionDetail.getNewTransactionMappings().values());
    }

    updateLoanSummaryDerivedFields();

    return changedTransactionDetail;
}

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

public void loanApplicationSubmittal(final AppUser currentUser, final LoanScheduleModel loanSchedule,
        final LoanApplicationTerms loanApplicationTerms, final LoanLifecycleStateMachine lifecycleStateMachine,
        final LocalDate submittedOn, final String externalId, final boolean allowTransactionsOnHoliday,
        final List<Holiday> holidays, final WorkingDays workingDays,
        final boolean allowTransactionsOnNonWorkingDay) {

    updateLoanSchedule(loanSchedule);/* www  .  j a va2s  .  c  o  m*/

    LoanStatus from = null;
    if (this.loanStatus != null) {
        from = LoanStatus.fromInt(this.loanStatus);
    }

    final LoanStatus statusEnum = lifecycleStateMachine.transition(LoanEvent.LOAN_CREATED, from);
    this.loanStatus = statusEnum.getValue();

    this.externalId = externalId;
    this.termFrequency = loanApplicationTerms.getLoanTermFrequency();
    this.termPeriodFrequencyType = loanApplicationTerms.getLoanTermPeriodFrequencyType().getValue();
    this.submittedOnDate = submittedOn.toDate();
    this.submittedBy = currentUser;
    this.expectedDisbursementDate = loanApplicationTerms.getExpectedDisbursementDate().toDate();
    this.expectedFirstRepaymentOnDate = loanApplicationTerms.getRepaymentStartFromDate();
    this.interestChargedFromDate = loanApplicationTerms.getInterestChargedFromDate();

    updateLoanScheduleDependentDerivedFields();

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

    if (this.client != null && this.client.isActivatedAfter(submittedOn)) {
        final String errorMessage = "The date on which a loan is submitted cannot be earlier than client's activation date.";
        throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.client.activation.date",
                errorMessage, submittedOn);
    }

    validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_CREATED, submittedOn);

    if (this.group != null && this.group.isActivatedAfter(submittedOn)) {
        final String errorMessage = "The date on which a loan is submitted cannot be earlier than groups's activation date.";
        throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.group.activation.date",
                errorMessage, submittedOn);
    }

    if (submittedOn.isAfter(getExpectedDisbursedOnLocalDate())) {
        final String errorMessage = "The date on which a loan is submitted cannot be after its expected disbursement date: "
                + getExpectedDisbursedOnLocalDate().toString();
        throw new InvalidLoanStateTransitionException("submittal", "cannot.be.after.expected.disbursement.date",
                errorMessage, submittedOn, getExpectedDisbursedOnLocalDate());
    }

    // charges are optional
    for (final LoanCharge loanCharge : setOfLoanCharges()) {
        BigDecimal amount = null;
        //done by madhav
        if (loanCharge.getChargeTime() == 10) {
            amount = loanCharge.getAmountPercentageAppliedTo();
        } else {
            amount = calculateAmountPercentageAppliedToLease(loanCharge);
        }

        BigDecimal chargeAmt = BigDecimal.ZERO;
        BigDecimal totalChargeAmt = BigDecimal.ZERO;
        if (loanCharge.getChargeCalculation().isPercentageBased()) {
            chargeAmt = loanCharge.getPercentage();
            if (loanCharge.isInstalmentFee()) {
                totalChargeAmt = calculatePerInstallmentChargeAmount(loanCharge);
            }
        } else {
            chargeAmt = loanCharge.amount();
            if (loanCharge.isInstalmentFee()) {
                chargeAmt = chargeAmt
                        .divide(BigDecimal.valueOf(repaymentScheduleDetail().getNumberOfRepayments()));
            }
        }
        loanCharge.update(chargeAmt, loanCharge.getDueLocalDate(), amount,
                repaymentScheduleDetail().getNumberOfRepayments(), totalChargeAmt);
        validateChargeHasValidSpecifiedDateIfApplicable(loanCharge, getDisbursementDate(),
                getLastRepaymentPeriodDueDate());
    }

    // validate if disbursement date is a holiday or a non-working day
    validateDisbursementDateIsOnNonWorkingDay(workingDays, allowTransactionsOnNonWorkingDay);
    validateDisbursementDateIsOnHoliday(allowTransactionsOnHoliday, holidays);
}

From source file:org.egov.services.recoveries.RecoveryService.java

public BigDecimal getDeductionAmount(final String recoveryCode, final String partyType,
        final String subPartyType, final String docType, final BigDecimal grossAmount, final Date asOnDate)
        throws Exception {

    final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy", Constants.LOCALE);
    BigDecimal incomeTax = new BigDecimal(0);
    BigDecimal surcharge = new BigDecimal(0);
    BigDecimal education = new BigDecimal(0);
    BigDecimal total = new BigDecimal(0);
    BigDecimal deductionAmt = new BigDecimal(0);
    EgDeductionDetails egDeductionDetails = null;

    if (null == recoveryCode || recoveryCode.trim().equals("")) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Recovery Code is missing");
        throw new ValidationException(EMPTY, "Recovery Code is missing");
    }/*from w  ww.  j  ava  2s  .c o m*/

    if (null == partyType || partyType.trim().equals("")) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Party Type is missing");
        throw new ValidationException(EMPTY, "Party Type is missing");
    }

    if (null == grossAmount) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Gross Amount is missing");
        throw new ValidationException(EMPTY, "Gross Amount is missing");
    }

    if (null == asOnDate) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("AsOnDate is missing");
        throw new ValidationException(EMPTY, "AsOnDate is missing");
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("getDeductionAmount() -> recoveryCode :" + recoveryCode + " | partyType :" + partyType
                + " | grossAmount :" + grossAmount + " | asOnDate :" + dateFormatter.format(asOnDate)
                + " | docType :" + docType);

    EgwTypeOfWork egwTypeOfWork = null;
    EgPartytype egSubPartytype = null;

    final EgPartytype egPartytype = getPartytypeByCode(partyType);
    final Recovery recovery = getTdsByTypeAndPartyType(recoveryCode, egPartytype);

    if (recovery == null)
        throw new ValidationException(EMPTY,
                "Recovery with " + recoveryCode + " code  and " + egPartytype + " party type is invalid.");
    if (recovery.getRecoveryMode() == 'M')
        return BigDecimal.valueOf(-1);

    if (null != docType)
        egwTypeOfWork = getTypeOfWorkByCode(docType);

    if (null != subPartyType)
        egSubPartytype = getSubPartytypeByCode(subPartyType);

    try {
        egDeductionDetails = egDeductionDetHibernateDao.findEgDeductionDetailsForDeduAmt(recovery, egPartytype,
                egSubPartytype, egwTypeOfWork, asOnDate);
    } catch (final Exception e) {
        LOGGER.error("Exception in egDeductionDetails fetching :" + e);
        throw new ValidationException(EMPTY, "Error while fetching the date for this " + recoveryCode
                + " code for this " + dateFormatter.format(asOnDate) + " date. " + e.getMessage());
    }

    if (null == egDeductionDetails)
        throw new ValidationException(EMPTY, "There is no data for this " + recoveryCode + " code for this "
                + dateFormatter.format(asOnDate) + " date.");

    if (null != recovery.getCalculationType() && recovery.getCalculationType().equalsIgnoreCase("flat")) {
        if (null != egDeductionDetails.getFlatAmount())
            deductionAmt = egDeductionDetails.getFlatAmount();
    } else {
        if (null != egDeductionDetails.getIncometax())
            incomeTax = egDeductionDetails.getIncometax();
        if (null != egDeductionDetails.getSurcharge())
            surcharge = egDeductionDetails.getSurcharge();
        if (null != egDeductionDetails.getEducation())
            education = egDeductionDetails.getEducation();
        total = incomeTax.add(surcharge).add(education);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("total IT/SC/EC " + total);
        deductionAmt = grossAmount.multiply(total.divide(new BigDecimal(100)));
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("deductionAmt :" + deductionAmt);
    return deductionAmt = deductionAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
}

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

public Map<String, Object> loanApplicationModification(final JsonCommand command,
        final Set<LoanCharge> possiblyModifedLoanCharges,
        final Set<LoanCollateral> possiblyModifedLoanCollateralItems, final AprCalculator aprCalculator,
        final Set<LoanFeeMaster> possiblyModifedLoanDeposits) {

    final Map<String, Object> actualChanges = this.loanRepaymentScheduleDetail
            .updateLoanApplicationAttributes(command, aprCalculator);
    if (!actualChanges.isEmpty()) {
        final boolean recalculateLoanSchedule = !(actualChanges.size() == 1
                && actualChanges.containsKey("inArrearsTolerance"));
        actualChanges.put("recalculateLoanSchedule", recalculateLoanSchedule);
    }/*from   w w w  .ja v a  2  s.  com*/

    final String dateFormatAsInput = command.dateFormat();
    final String localeAsInput = command.locale();

    final String accountNoParamName = "accountNo";
    if (command.isChangeInStringParameterNamed(accountNoParamName, this.accountNumber)) {
        final String newValue = command.stringValueOfParameterNamed(accountNoParamName);
        actualChanges.put(accountNoParamName, newValue);
        this.accountNumber = StringUtils.defaultIfEmpty(newValue, null);
    }

    final String externalIdParamName = "externalId";
    if (command.isChangeInStringParameterNamed(externalIdParamName, this.externalId)) {
        final String newValue = command.stringValueOfParameterNamed(externalIdParamName);
        actualChanges.put(externalIdParamName, newValue);
        this.externalId = StringUtils.defaultIfEmpty(newValue, null);
    }

    // add clientId, groupId and loanType changes to actual changes

    final String clientIdParamName = "clientId";
    final Long clientId = this.client == null ? null : this.client.getId();
    if (command.isChangeInLongParameterNamed(clientIdParamName, clientId)) {
        final Long newValue = command.longValueOfParameterNamed(clientIdParamName);
        actualChanges.put(clientIdParamName, newValue);
    }

    // FIXME: AA - We may require separate api command to move loan from one
    // group to another
    final String groupIdParamName = "groupId";
    final Long groupId = this.group == null ? null : this.group.getId();
    if (command.isChangeInLongParameterNamed(groupIdParamName, groupId)) {
        final Long newValue = command.longValueOfParameterNamed(groupIdParamName);
        actualChanges.put(groupIdParamName, newValue);
    }

    final String productIdParamName = "productId";
    if (command.isChangeInLongParameterNamed(productIdParamName, this.loanProduct.getId())) {
        final Long newValue = command.longValueOfParameterNamed(productIdParamName);
        actualChanges.put(productIdParamName, newValue);
        actualChanges.put("recalculateLoanSchedule", true);
    }

    Long existingFundId = null;
    if (this.fund != null) {
        existingFundId = this.fund.getId();
    }
    final String fundIdParamName = "fundId";
    if (command.isChangeInLongParameterNamed(fundIdParamName, existingFundId)) {
        final Long newValue = command.longValueOfParameterNamed(fundIdParamName);
        actualChanges.put(fundIdParamName, newValue);
    }

    Long existingLoanOfficerId = null;
    if (this.loanOfficer != null) {
        existingLoanOfficerId = this.loanOfficer.getId();
    }
    final String loanOfficerIdParamName = "loanOfficerId";
    if (command.isChangeInLongParameterNamed(loanOfficerIdParamName, existingLoanOfficerId)) {
        final Long newValue = command.longValueOfParameterNamed(loanOfficerIdParamName);
        actualChanges.put(loanOfficerIdParamName, newValue);
    }

    Long existingLoanPurposeId = null;
    if (this.loanPurpose != null) {
        existingLoanPurposeId = this.loanPurpose.getId();
    }
    final String loanPurposeIdParamName = "loanPurposeId";
    if (command.isChangeInLongParameterNamed(loanPurposeIdParamName, existingLoanPurposeId)) {
        final Long newValue = command.longValueOfParameterNamed(loanPurposeIdParamName);
        actualChanges.put(loanPurposeIdParamName, newValue);
    }

    final String strategyIdParamName = "transactionProcessingStrategyId";
    if (command.isChangeInLongParameterNamed(strategyIdParamName, this.transactionProcessingStrategy.getId())) {
        final Long newValue = command.longValueOfParameterNamed(strategyIdParamName);
        actualChanges.put(strategyIdParamName, newValue);
    }

    final String submittedOnDateParamName = "submittedOnDate";
    if (command.isChangeInLocalDateParameterNamed(submittedOnDateParamName, getSubmittedOnDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(submittedOnDateParamName);
        actualChanges.put(submittedOnDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);

        final LocalDate newValue = command.localDateValueOfParameterNamed(submittedOnDateParamName);
        this.submittedOnDate = newValue.toDate();
    }

    final String expectedDisbursementDateParamName = "expectedDisbursementDate";
    if (command.isChangeInLocalDateParameterNamed(expectedDisbursementDateParamName,
            getExpectedDisbursedOnLocalDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(expectedDisbursementDateParamName);
        actualChanges.put(expectedDisbursementDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);
        actualChanges.put("recalculateLoanSchedule", true);

        final LocalDate newValue = command.localDateValueOfParameterNamed(expectedDisbursementDateParamName);
        this.expectedDisbursementDate = newValue.toDate();
        removeFirstDisbursementTransaction();
    }

    final String repaymentsStartingFromDateParamName = "repaymentsStartingFromDate";
    if (command.isChangeInLocalDateParameterNamed(repaymentsStartingFromDateParamName,
            getExpectedFirstRepaymentOnDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(repaymentsStartingFromDateParamName);
        actualChanges.put(repaymentsStartingFromDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);
        actualChanges.put("recalculateLoanSchedule", true);

        final LocalDate newValue = command.localDateValueOfParameterNamed(repaymentsStartingFromDateParamName);
        if (newValue != null) {
            this.expectedFirstRepaymentOnDate = newValue.toDate();
        } else {
            this.expectedFirstRepaymentOnDate = null;
        }
    }

    final String syncDisbursementParameterName = "syncDisbursementWithMeeting";
    if (command.isChangeInBooleanParameterNamed(syncDisbursementParameterName,
            isSyncDisbursementWithMeeting())) {
        final Boolean valueAsInput = command.booleanObjectValueOfParameterNamed(syncDisbursementParameterName);
        actualChanges.put(syncDisbursementParameterName, valueAsInput);
        this.syncDisbursementWithMeeting = valueAsInput;
    }

    final String interestChargedFromDateParamName = "interestChargedFromDate";
    if (command.isChangeInLocalDateParameterNamed(interestChargedFromDateParamName,
            getInterestChargedFromDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(interestChargedFromDateParamName);
        actualChanges.put(interestChargedFromDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);
        actualChanges.put("recalculateLoanSchedule", true);

        final LocalDate newValue = command.localDateValueOfParameterNamed(interestChargedFromDateParamName);
        if (newValue != null) {
            this.interestChargedFromDate = newValue.toDate();
        } else {
            this.interestChargedFromDate = null;
        }
    }

    if (getSubmittedOnDate().isAfter(new LocalDate())) {
        final String errorMessage = "The date on which a loan is submitted cannot be in the future.";
        throw new InvalidLoanStateTransitionException("submittal", "cannot.be.a.future.date", errorMessage,
                getSubmittedOnDate());
    }

    if (!(this.client == null)) {
        if (getSubmittedOnDate().isBefore(this.client.getActivationLocalDate())) {
            final String errorMessage = "The date on which a loan is submitted cannot be earlier than client's activation date.";
            throw new InvalidLoanStateTransitionException("submittal",
                    "cannot.be.before.client.activation.date", errorMessage, getSubmittedOnDate());
        }
    } else if (!(this.group == null)) {
        if (getSubmittedOnDate().isBefore(this.group.getActivationLocalDate())) {
            final String errorMessage = "The date on which a loan is submitted cannot be earlier than groups's activation date.";
            throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.group.activation.date",
                    errorMessage, getSubmittedOnDate());
        }
    }

    if (getSubmittedOnDate().isAfter(getExpectedDisbursedOnLocalDate())) {
        final String errorMessage = "The date on which a loan is submitted cannot be after its expected disbursement date: "
                + getExpectedDisbursedOnLocalDate().toString();
        throw new InvalidLoanStateTransitionException("submittal", "cannot.be.after.expected.disbursement.date",
                errorMessage, getSubmittedOnDate(), getExpectedDisbursedOnLocalDate());
    }

    final String chargesParamName = "charges";
    if (command.parameterExists(chargesParamName)) {

        final Set<LoanCharge> existingLoanCharges = setOfLoanCharges();

        if (!possiblyModifedLoanCharges.equals(existingLoanCharges)) {
            actualChanges.put(chargesParamName, getLoanCharges(possiblyModifedLoanCharges));

            actualChanges.put("recalculateLoanSchedule", true);

            for (final LoanCharge loanCharge : possiblyModifedLoanCharges) {
                final BigDecimal amount = calculateAmountPercentageAppliedTo(loanCharge);
                BigDecimal chargeAmt = BigDecimal.ZERO;
                BigDecimal totalChargeAmt = BigDecimal.ZERO;
                if (loanCharge.getChargeCalculation().isPercentageBased()) {
                    chargeAmt = loanCharge.getPercentage();
                    if (loanCharge.isInstalmentFee()) {
                        totalChargeAmt = calculatePerInstallmentChargeAmount(loanCharge);
                    }
                } else {
                    chargeAmt = loanCharge.amount();
                    if (loanCharge.isInstalmentFee()) {
                        chargeAmt = chargeAmt
                                .divide(BigDecimal.valueOf(repaymentScheduleDetail().getNumberOfRepayments()));
                    }
                }
                loanCharge.update(chargeAmt, loanCharge.getDueLocalDate(), amount,
                        repaymentScheduleDetail().getNumberOfRepayments(), totalChargeAmt);
                validateChargeHasValidSpecifiedDateIfApplicable(loanCharge, getDisbursementDate(),
                        getLastRepaymentPeriodDueDate());
            }
        }
    }

    final String collateralParamName = "collateral";
    if (command.parameterExists(collateralParamName)) {

        if (!possiblyModifedLoanCollateralItems.equals(this.collateral)) {
            actualChanges.put(collateralParamName,
                    listOfLoanCollateralData(possiblyModifedLoanCollateralItems));
        }
    }

    final String loanTermFrequencyParamName = "loanTermFrequency";
    if (command.isChangeInIntegerParameterNamed(loanTermFrequencyParamName, this.termFrequency)) {
        final Integer newValue = command.integerValueOfParameterNamed(loanTermFrequencyParamName);
        actualChanges.put(externalIdParamName, newValue);
        this.termFrequency = newValue;
    }

    final String loanTermFrequencyTypeParamName = "loanTermFrequencyType";
    if (command.isChangeInIntegerParameterNamed(loanTermFrequencyTypeParamName, this.termPeriodFrequencyType)) {
        final Integer newValue = command.integerValueOfParameterNamed(loanTermFrequencyTypeParamName);
        final PeriodFrequencyType newTermPeriodFrequencyType = PeriodFrequencyType.fromInt(newValue);
        actualChanges.put(loanTermFrequencyTypeParamName, newTermPeriodFrequencyType.getValue());
        this.termPeriodFrequencyType = newValue;
    }

    final String depositsParamName = "depositArray";
    if (command.parameterExists(depositsParamName)) {

        final Set<LoanFeeMaster> existingLoanDeposits = setOfLoanDeposits();

        if (!possiblyModifedLoanDeposits.equals(existingLoanDeposits)) {

            actualChanges.put(depositsParamName, getLoanDeposit(possiblyModifedLoanDeposits));
            actualChanges.put("recalculateLoanSchedule", true);

            for (final LoanFeeMaster loanDeposit : possiblyModifedLoanDeposits) {
                final BigDecimal amount = calculateAmountPercentageAppliedTo(loanDeposit);
                BigDecimal depositAmt = BigDecimal.ZERO;
                if (loanDeposit.getDepositCalculation().isPercentageBased()) {
                    depositAmt = loanDeposit.getPercentage();
                } else {
                    depositAmt = loanDeposit.getAmount();
                }
                loanDeposit.update(depositAmt, amount, BigDecimal.ZERO);
            }
        }
    }

    return actualChanges;
}

From source file:org.openbravo.test.costing.TestCosting.java

private BigDecimal getAveragePrice(List<BigDecimal> priceList) {
    try {//w w  w . java2  s  .c o m
        BigDecimal priceAvg = amount0;
        for (BigDecimal price : priceList)
            priceAvg = priceAvg.add(price);
        return priceAvg.divide(new BigDecimal(priceList.size()));
    } catch (Exception e) {
        throw new OBException(e);
    }
}