Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:com.aimluck.eip.project.ProjectTaskSimpleSelectData.java

/**
 * ResultData???? <BR>//from ww w . ja v  a 2  s.c  o  m
 * 
 * @param record
 *          
 * @return ResultData
 */
@Override
protected Object getResultData(EipTProjectTask record) {
    ProjectTaskResultData data = ProjectUtils.getProjectTaskResultData(record);
    Integer taskId = (int) data.getTaskId().getValue();

    // ?
    int cntChild = ProjectUtils.getCountChildrenTask(taskId);

    // ??2??true
    // ??
    data.setHasChildren(cntChild >= 2);

    // ?
    data.setHasChildrenForForm(cntChild > 0);

    // ?
    int lapsedDays = ProjectUtils.getLapsedDays(ProjectUtils.toString(record.getStartPlanDate()),
            ProjectUtils.toString(Calendar.getInstance().getTime()));
    // 
    int taskDays = ProjectUtils.getLapsedDays(ProjectUtils.toString(record.getStartPlanDate()),
            ProjectUtils.toString(record.getEndPlanDate()));
    data.setPlanTerm(taskDays);

    if (lapsedDays > taskDays) {
        // ???
        lapsedDays = taskDays;
    }

    // ?
    data.setPlanProgressRate(ProjectUtils.getPlanWorkload(lapsedDays, taskDays));

    // 
    List<ProjectTaskMemberResultData> memberList = data.getMemberList();
    BigDecimal workload = BigDecimal.valueOf(0);
    workload = workload.setScale(1);
    for (int i = 0; i < memberList.size(); i++) {
        ProjectTaskMemberResultData member = memberList.get(i);
        workload = workload.add(member.getWorkload());
    }
    data.setWorkload(workload);

    // 
    BigDecimal forecastWorkload = BigDecimal.valueOf(0);
    if (data.getProgressRate().getValue() != 0) {
        forecastWorkload = workload.multiply(BigDecimal.valueOf(100))
                .divide(BigDecimal.valueOf(data.getProgressRate().getValue()), 2, BigDecimal.ROUND_HALF_UP);
    }
    data.setForecastWorkload(forecastWorkload);

    // 
    data.setIndentFlg(indentFlg);

    return data;
}

From source file:org.openbravo.erpCommon.utility.CashVATUtil.java

/**
 * Creates the records into the Cash VAT management table (InvoiceTaxCashVAT), calculating the
 * percentage paid/collected tax amount and taxable amount. Only for cash vat tax rates
 * /* ww  w  .  j  a  v a2s.  c  om*/
 */
public static void createInvoiceTaxCashVAT(final FIN_PaymentDetail paymentDetail,
        final FIN_PaymentSchedule paymentSchedule, final BigDecimal amount) {
    try {
        OBContext.setAdminMode(true);
        final Invoice invoice = paymentSchedule.getInvoice();
        if (invoice != null && invoice.isCashVAT()) {
            // A previous cash vat line with this payment detail means we are reactivating the payment.
            // In this case we delete the line
            final List<InvoiceTaxCashVAT> previousITCashVATs = getInvoiceTaxCashVAT(paymentDetail);
            if (previousITCashVATs != null && !previousITCashVATs.isEmpty()) {
                for (InvoiceTaxCashVAT previousITCV : previousITCashVATs) {
                    OBDal.getInstance().remove(previousITCV);
                }
            } else {
                final boolean calculateAmountsBasedOnPercentage;
                BigDecimal percentage = null; /* Calculate it later on */
                final BigDecimal outstandingAmt = invoice.getOutstandingAmount();
                if (outstandingAmt.compareTo(amount) == 0) {
                    // We are fully paying the invoice. We need to subtract amounts instead of calculating
                    // them on the fly
                    calculateAmountsBasedOnPercentage = false;
                } else {
                    // Calculate amounts based on the paid percentage
                    calculateAmountsBasedOnPercentage = true;
                    final boolean isReversal = invoice.getDocumentType().isReversal();
                    final BigDecimal grandTotalAmt = isReversal ? invoice.getGrandTotalAmount().negate()
                            : invoice.getGrandTotalAmount();
                    final int currencyPrecission = invoice.getCurrency().getStandardPrecision().intValue();
                    percentage = amount.multiply(_100).divide(grandTotalAmt, currencyPrecission,
                            RoundingMode.HALF_UP);
                }

                for (final InvoiceTax invoiceTax : invoice.getInvoiceTaxList()) {
                    if (invoiceTax.getTax().isCashVAT()) {
                        final InvoiceTaxCashVAT iTCashVAT = OBProvider.getInstance()
                                .get(InvoiceTaxCashVAT.class);
                        iTCashVAT.setOrganization(invoiceTax.getOrganization());
                        iTCashVAT.setInvoiceTax(invoiceTax);
                        iTCashVAT.setFINPaymentDetail(paymentDetail);
                        final BigDecimal taxAmount;
                        final BigDecimal taxableAmount;
                        if (calculateAmountsBasedOnPercentage) {
                            taxAmount = calculatePercentageAmount(percentage, invoiceTax.getTaxAmount(),
                                    invoice.getCurrency());
                            taxableAmount = calculatePercentageAmount(percentage, invoiceTax.getTaxableAmount(),
                                    invoice.getCurrency());
                        } else {
                            final Map<String, BigDecimal> outstandingAmounts = getTotalOutstandingCashVATAmount(
                                    invoiceTax.getId());
                            percentage = outstandingAmounts.get("percentage");
                            taxAmount = outstandingAmounts.get("taxAmt");
                            taxableAmount = outstandingAmounts.get("taxableAmt");
                        }
                        iTCashVAT.setPercentage(percentage);
                        iTCashVAT.setTaxAmount(taxAmount);
                        iTCashVAT.setTaxableAmount(taxableAmount);
                        invoiceTax.getInvoiceTaxCashVATList().add(iTCashVAT);
                        OBDal.getInstance().save(invoiceTax);
                        OBDal.getInstance().save(iTCashVAT);
                    }
                }
            }
            OBDal.getInstance().flush();
        }
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Riemann zeta function./*from  w w w.  j a  va2  s. co m*/
 *
 * @param n  The positive integer argument.
 *           32
 * @param mc Specification of the accuracy of the result.
 * @return zeta(n).
 */
static public BigDecimal zeta(final int n, final MathContext mc) {
    if (n <= 0) {
        throw new ProviderException("Unimplemented zeta at negative argument " + n);
    }

    if (n == 1) {
        throw new ArithmeticException("Pole at zeta(1) ");
    }

    if (n % 2 == 0) {
        /* Even indices. Abramowitz-Stegun 23.2.16. Start with 2^(n-1)*B(n)/n!
         */
        Rational b = (new Bernoulli()).at(n).abs();
        b = b.divide((new Factorial()).at(n));
        b = b.multiply(BigInteger.ONE.shiftLeft(n - 1));
        /* to be multiplied by pi^n. Absolute error in the result of pi^n is n times
         * error in pi times pi^(n-1). Relative error is n*error(pi)/pi, requested by mc.
         * Need one more digit in pi if n=10, two digits if n=100 etc, and add one extra digit.
         */
        MathContext mcpi = new MathContext(mc.getPrecision() + (int) (Math.log10(10.0 * n)));
        final BigDecimal piton = pi(mcpi).pow(n, mc);

        return multiplyRound(piton, b);

    } else if (n == 3) {
        /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
         * Error propagation: S31 is roughly 0.087, S33 roughly 0.131
         */
        int[] a31 = { 1, -7, -1, 10, -1, -7, 1, 0 };

        int[] a33 = { 1, 1, -1, -2, -1, 1, 1, 0 };
        BigDecimal S31 = broadhurstBBP(3, 1, a31, mc);
        BigDecimal S33 = broadhurstBBP(3, 3, a33, mc);
        S31 = S31.multiply(new BigDecimal(48));
        S33 = S33.multiply(new BigDecimal(32));

        return S31.add(S33).divide(new BigDecimal(7), mc);

    } else if (n == 5) {
        /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
         * Error propagation: S51 is roughly -11.15, S53 roughly 22.165, S55 is roughly 0.031
         * 9*2048*S51/6265 = -3.28. 7*2038*S53/61651= 5.07. 738*2048*S55/61651= 0.747.
         * The result is of the order 1.03, so we add 2 digits to S51 and S52 and one digit to S55.
         */
        int[] a51 = { 31, -1614, -31, -6212, -31, -1614, 31, 74552 };

        int[] a53 = { 173, 284, -173, -457, -173, 284, 173, -111 };

        int[] a55 = { 1, 0, -1, -1, -1, 0, 1, 1 };
        BigDecimal S51 = broadhurstBBP(5, 1, a51, new MathContext(2 + mc.getPrecision()));
        BigDecimal S53 = broadhurstBBP(5, 3, a53, new MathContext(2 + mc.getPrecision()));
        BigDecimal S55 = broadhurstBBP(5, 5, a55, new MathContext(1 + mc.getPrecision()));
        S51 = S51.multiply(new BigDecimal(18432));
        S53 = S53.multiply(new BigDecimal(14336));
        S55 = S55.multiply(new BigDecimal(1511424));

        return S51.add(S53).subtract(S55).divide(new BigDecimal(62651), mc);

    } else {
        /* Cohen et al Exp Math 1 (1) (1992) 25
         */
        Rational betsum = new Rational();
        Bernoulli bern = new Bernoulli();
        Factorial fact = new Factorial();

        for (int npr = 0; npr <= (n + 1) / 2; npr++) {
            Rational b = bern.at(2 * npr).multiply(bern.at(n + 1 - 2 * npr));
            b = b.divide(fact.at(2 * npr)).divide(fact.at(n + 1 - 2 * npr));
            b = b.multiply(1 - 2 * npr);

            if (npr % 2 == 0) {
                betsum = betsum.add(b);
            } else {
                betsum = betsum.subtract(b);
            }

        }
        betsum = betsum.divide(n - 1);
        /* The first term, including the facor (2pi)^n, is essentially most
         * of the result, near one. The second term below is roughly in the range 0.003 to 0.009.
         * So the precision here is matching the precisionn requested by mc, and the precision
         * requested for 2*pi is in absolute terms adjusted.
         */
        MathContext mcloc = new MathContext(2 + mc.getPrecision() + (int) (Math.log10((double) (n))));
        BigDecimal ftrm = pi(mcloc).multiply(new BigDecimal(2));
        ftrm = ftrm.pow(n);

        ftrm = multiplyRound(ftrm, betsum.BigDecimalValue(mcloc));
        BigDecimal exps = new BigDecimal(0);
        /* the basic accuracy of the accumulated terms before multiplication with 2
         */

        double eps = Math.pow(10., -mc.getPrecision());

        if (n % 4 == 3) {
            /* since the argument n is at least 7 here, the drop
             * of the terms is at rather constant pace at least 10^-3, for example
             * 0.0018, 0.2e-7, 0.29e-11, 0.74e-15 etc for npr=1,2,3.... We want 2 times these terms
             * fall below eps/10.
             */
            int kmax = mc.getPrecision() / 3;
            eps /= kmax;
            /* need an error of eps for 2/(exp(2pi)-1) = 0.0037
             * The absolute error is 4*exp(2pi)*err(pi)/(exp(2pi)-1)^2=0.0075*err(pi)
             */
            BigDecimal exp2p = pi(new MathContext(3 + err2prec(3.14, eps / 0.0075)));
            exp2p = exp(exp2p.multiply(new BigDecimal(2)));
            BigDecimal c = exp2p.subtract(BigDecimal.ONE);
            exps = divideRound(1, c);

            for (int npr = 2; npr <= kmax; npr++) {
                /* the error estimate above for npr=1 is the worst case of
                 * the absolute error created by an error in 2pi. So we can
                 * safely re-use the exp2p value computed above without
                 * reassessment of its error.
                 */
                c = powRound(exp2p, npr).subtract(BigDecimal.ONE);
                c = multiplyRound(c, (new BigInteger("" + npr)).pow(n));
                c = divideRound(1, c);
                exps = exps.add(c);

            }
        } else {
            /* since the argument n is at least 9 here, the drop
             * of the terms is at rather constant pace at least 10^-3, for example
             * 0.0096, 0.5e-7, 0.3e-11, 0.6e-15 etc. We want these terms
             * fall below eps/10.
             */
            int kmax = (1 + mc.getPrecision()) / 3;
            eps /= kmax;
            /* need an error of eps for 2/(exp(2pi)-1)*(1+4*Pi/8/(1-exp(-2pi)) = 0.0096
             * at k=7 or = 0.00766 at k=13 for example.
             * The absolute error is 0.017*err(pi) at k=9, 0.013*err(pi) at k=13, 0.012 at k=17
             */
            BigDecimal twop = pi(new MathContext(3 + err2prec(3.14, eps / 0.017)));
            twop = twop.multiply(new BigDecimal(2));
            BigDecimal exp2p = exp(twop);
            BigDecimal c = exp2p.subtract(BigDecimal.ONE);
            exps = divideRound(1, c);
            c = BigDecimal.ONE.subtract(divideRound(1, exp2p));
            c = divideRound(twop, c).multiply(new BigDecimal(2));
            c = divideRound(c, n - 1).add(BigDecimal.ONE);
            exps = multiplyRound(exps, c);

            for (int npr = 2; npr <= kmax; npr++) {
                c = powRound(exp2p, npr).subtract(BigDecimal.ONE);
                c = multiplyRound(c, (new BigInteger("" + npr)).pow(n));
                BigDecimal d = divideRound(1, exp2p.pow(npr));
                d = BigDecimal.ONE.subtract(d);
                d = divideRound(twop, d).multiply(new BigDecimal(2 * npr));
                d = divideRound(d, n - 1).add(BigDecimal.ONE);
                d = divideRound(d, c);
                exps = exps.add(d);

            }
        }
        exps = exps.multiply(new BigDecimal(2));

        return ftrm.subtract(exps, mc);

    }
}

From source file:org.fineract.module.stellar.TestPaymentInSimpleNetwork.java

@Test
public void paymentSumApproachesCreditLimit() throws Exception {
    logger.info("paymentSumApproachesCreditLimit test begin");

    final BigDecimal transferIncrement = BigDecimal.valueOf(99.99);
    final BigDecimal lastBit = BigDecimal.valueOf(0.1);

    final AccountListener accountListener = new AccountListener(serverAddress, firstTenantId, secondTenantId);

    //Approach the creditMatcher limit, then go back down to zero.
    Collections.nCopies(10, transferIncrement).parallelStream()
            .forEach((transferAmount) -> makePayment(firstTenantId, firstTenantApiKey, secondTenantId,
                    ASSET_CODE, transferAmount));

    {// w w  w.j  a v  a2s.co  m
        final List<AccountListener.CreditMatcher> transfers = new ArrayList<>();
        transfers.addAll(Collections.nCopies(10,
                creditMatcher(secondTenantId, transferIncrement, ASSET_CODE, firstTenantId)));

        accountListener.waitForCredits(PAY_WAIT * 3, transfers);
    }

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
            VAULT_BALANCE);

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
            transferIncrement.multiply(BigDecimal.TEN));

    logger.info("paymentSumApproachesCreditLimit transfers back");
    Collections.nCopies(10, transferIncrement).parallelStream()
            .forEach((transferAmount) -> makePayment(secondTenantId, secondTenantApiKey, firstTenantId,
                    ASSET_CODE, transferAmount));

    {
        final List<AccountListener.CreditMatcher> transfers = new ArrayList<>();
        transfers.addAll(Collections.nCopies(10, creditMatcher(firstTenantId, transferIncrement, ASSET_CODE,
                vaultMatcher(firstTenantId, secondTenantId))));

        accountListener.waitForCredits(PAY_WAIT * 3, transfers);

        accountListener.waitForCreditsToAccumulate(PAY_WAIT * 3,
                creditMatcher(secondTenantId, transferIncrement.multiply(BigDecimal.TEN), ASSET_CODE,
                        vaultMatcher(firstTenantId, secondTenantId)));

        accountListener.waitForCreditsToAccumulate(PAY_WAIT * 3,
                creditMatcher(firstTenantId, transferIncrement.multiply(BigDecimal.TEN), ASSET_CODE,
                        vaultMatcher(firstTenantId, secondTenantId)));
    }

    checkBalance(firstTenantId, firstTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
            BigDecimal.ZERO);
    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
            BigDecimal.ZERO);

    //Approach the creditMatcher limit again, then go to exactly the creditMatcher limit
    Collections.nCopies(10, transferIncrement).parallelStream()
            .forEach((transferAmount) -> makePayment(firstTenantId, firstTenantApiKey, secondTenantId,
                    ASSET_CODE, transferAmount));
    makePayment(firstTenantId, firstTenantApiKey, secondTenantId, ASSET_CODE, lastBit);

    {
        final List<AccountListener.CreditMatcher> transfers = new ArrayList<>();
        transfers.addAll(Collections.nCopies(10,
                creditMatcher(secondTenantId, transferIncrement, ASSET_CODE, firstTenantId)));
        transfers.add(creditMatcher(secondTenantId, lastBit, ASSET_CODE, firstTenantId));

        accountListener.waitForCredits(PAY_WAIT * 3, transfers);
    }

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
            TRUST_LIMIT);

    //Now try to go over the creditMatcher limit.
    makePayment(firstTenantId, firstTenantApiKey, secondTenantId, ASSET_CODE, lastBit);

    accountListener.waitForCredits(PAY_WAIT,
            creditMatcher(secondTenantId, lastBit, ASSET_CODE, vaultMatcher(firstTenantId, secondTenantId)));

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
            TRUST_LIMIT);

    //Zero out balance for next test.
    makePayment(secondTenantId, secondTenantApiKey, firstTenantId, ASSET_CODE, TRUST_LIMIT);
    accountListener.waitForCredits(PAY_WAIT,
            creditMatcher(firstTenantId, TRUST_LIMIT, ASSET_CODE, vaultMatcher(firstTenantId, secondTenantId)));
}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualServiceImpl.java

private void calculateHours(String accrualCategoryId, BigDecimal fte, BigDecimal rate,
        Map<String, BigDecimal> accumulatedAmounts) {
    BigDecimal hours = rate.multiply(fte);
    BigDecimal oldHours = accumulatedAmounts.get(accrualCategoryId);
    BigDecimal newHours = oldHours == null ? hours : hours.add(oldHours);
    accumulatedAmounts.put(accrualCategoryId, newHours);
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

/**
 * Figures out the tolerance for a search. For example, if the user is searching for <code>4.00</code>, this method
 * returns <code>0.005</code> because we shold actually match values which are
 * <code>4 (+/-) 0.005</code> according to the FHIR specs.
 *//* w w w.j a  v  a 2 s .c o  m*/
static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) {
    if (cmpValue == ParamPrefixEnum.APPROXIMATE) {
        return theValue.multiply(new BigDecimal(0.1));
    } else {
        String plainString = theValue.toPlainString();
        int dotIdx = plainString.indexOf('.');
        if (dotIdx == -1) {
            return new BigDecimal(0.5);
        }

        int precision = plainString.length() - (dotIdx);
        double mul = Math.pow(10, -precision);
        double val = mul * 5.0d;
        return new BigDecimal(val);
    }
}

From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java

private BigDecimal calculateVolumeCharge(final MemberAccount account, final AccountFee volumeFee,
        final Period period, final BigDecimal additionalReserved, final boolean currentPeriod) {
    Calendar fromDate = period.getBegin();

    // Get the account status right after the last charged period
    AccountStatus status = accountService.getStatus(account, fromDate);

    // When there is some additional amount to consider as reserved, add it to the status
    status.setReservedAmount(status.getReservedAmount().add(additionalReserved));

    // Calculate the total days. We want the entire charged period. For example: if the fee was enabled in the middle of a month, it would be the
    // entire month. Likewise, if no end limit was given, the current period will be used (ie, and the last day in the current month)
    TimePeriod recurrence = volumeFee.getRecurrence();
    Period totalPeriod = recurrence.currentPeriod(period.getBegin());
    int totalDays = totalPeriod.getDays() + 1;

    // Calculate each difference, with the corresponding reserved amount
    Calendar lastDay = fromDate;/*  w w w .j  a v  a 2  s.c o m*/
    Calendar lastChargedDay = fromDate;
    BigDecimal result = BigDecimal.ZERO;
    IteratorList<AccountDailyDifference> diffs = accountDao.iterateDailyDifferences(account, period);
    if (LOG.isDebugEnabled()) {
        LOG.debug("********************************");
        LOG.debug(FormatObject.formatObject(period.getBegin()) + "\t" + status.getBalance() + "\t"
                + status.getAvailableBalance());
    }
    try {
        if (diffs.hasNext()) {
            // There are differences - the lastChargedAvailable balance will be obtained within the loop
            for (AccountDailyDifference diff : diffs) {
                Calendar day = diff.getDay();
                int days = DateHelper.daysBetween(lastDay, day);
                // Get the available balance at that day
                BigDecimal available = status.getAvailableBalanceWithoutCreditLimit();
                if (volumeFee.getChargeMode().isNegative()) {
                    // If the charge is over negative amounts, consider the negated amount
                    available = available.negate();
                }
                // Take the free base into account
                if (volumeFee.getFreeBase() != null) {
                    available = available.subtract(volumeFee.getFreeBase());
                }
                // If the available balance was significant, calculate the charge
                if (available.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal volume = new BigDecimal(available.doubleValue() * days / totalDays);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(FormatObject.formatObject(day) + "\t" + diff.getBalance() + "\t"
                                + status.getAvailableBalanceWithoutCreditLimit().add(diff.getBalance()) + "\t"
                                + days + "\t" + totalDays + "\t" + volume);
                    }
                    BigDecimal toCharge = volume.multiply(volumeFee.getAmount())
                            .divide(BigDecimalHelper.ONE_HUNDRED);
                    // status.setReservedAmount(status.getReservedAmount().add(toCharge));
                    result = result.add(toCharge);
                    lastChargedDay = day;
                }
                lastDay = day;
                status.setBalance(status.getBalance().add(diff.getBalance()));
                status.setReservedAmount(status.getReservedAmount().add(diff.getReserved()));
            }
        }
    } finally {
        DataIteratorHelper.close(diffs);
    }

    Calendar toDate = period.getEnd();
    boolean lastPaymentInPeriodEnd = !toDate.before(lastChargedDay);
    LocalSettings settings = settingsService.getLocalSettings();

    // Only if the last payment was not today we have to take into account the results so far
    if (DateHelper.daysBetween(lastChargedDay, Calendar.getInstance()) != 0) {
        BigDecimal resultSoFar = settings.round(result);
        status.setReservedAmount(status.getReservedAmount().add(resultSoFar));
    }

    // Calculate the avaliable balance after the last diff, which will remain the same until the period end
    BigDecimal finalAvailableBalance = status.getAvailableBalanceWithoutCreditLimit();
    if (volumeFee.getChargeMode().isNegative()) {
        finalAvailableBalance = finalAvailableBalance.negate();
    }
    if (volumeFee.getFreeBase() != null) {
        finalAvailableBalance = finalAvailableBalance.subtract(volumeFee.getFreeBase());
    }

    // Consider the last time slice, between the last diff and the period end, if any
    if (lastPaymentInPeriodEnd && finalAvailableBalance.compareTo(BigDecimal.ZERO) > 0) {
        int days = DateHelper.daysBetween(lastChargedDay, toDate) + (currentPeriod ? 0 : 1);
        // Here, the lastChargedAvailableBalance is already subtracted from the free base (if any)
        BigDecimal volume = new BigDecimal(finalAvailableBalance.doubleValue() * days / totalDays);
        BigDecimal toCharge = volume.multiply(volumeFee.getAmount()).divide(BigDecimalHelper.ONE_HUNDRED);
        result = result.add(toCharge);
        if (LOG.isDebugEnabled()) {
            status.setReservedAmount(settings.round(status.getReservedAmount().add(toCharge)));
            LOG.debug(FormatObject.formatObject(lastChargedDay) + "\t0\t"
                    + status.getAvailableBalanceWithoutCreditLimit() + "\t" + days + "\t" + totalDays + "\t"
                    + volume);
        }
    }

    return settings.round(result);
}

From source file:org.openbravo.costing.AverageCostAdjustment.java

@Override
protected void calculateNegativeStockCorrectionAdjustmentAmount(CostAdjustmentLine costAdjLine) {
    MaterialTransaction basetrx = costAdjLine.getInventoryTransaction();
    boolean areBaseTrxBackdatedFixed = getCostingRule().isBackdatedTransactionsFixed() && !CostingUtils
            .getCostingRuleFixBackdatedFrom(getCostingRule()).before(basetrx.getTransactionProcessDate());
    BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBaseTrxBackdatedFixed);
    BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBaseTrxBackdatedFixed, getCostCurrency());

    Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0);
    BigDecimal trxPrice = curCosting.getPrice();
    BigDecimal adjustAmt = currentStock.multiply(trxPrice).setScale(stdCurPrecission, RoundingMode.HALF_UP)
            .subtract(currentValueAmt);// www  . j  a  va  2s.c o m

    costAdjLine.setCurrency((Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId));
    costAdjLine.setAdjustmentAmount(adjustAmt);
    OBDal.getInstance().save(costAdjLine);
}

From source file:com.salesmanager.central.invoice.InvoiceDetailsAction.java

/**
 * Gather all invoice lines and persist to the appropriate order tables
 * /*from  w  w w  .j a  v a  2  s .  c  om*/
 * @return
 */
public String saveInvoice() {

    try {

        this.prepareInvoiceReferences();

        // gather cart lines
        /**
         * <tr>
         * <td class="item">
         * <input type="hidden" name ="cartlineid-+data.lineId+"
         * id="cartlineid- +data.lineId+ " value=" + data.lineId+ "> <input
         * type="hidden"
         * name="productid-"+data.lineId+" id="productid-" +data.lineId+ "
         * value=" + data.productId + "> <input type="hidden" name="ids[]"
         * value="+data.lineId+"> <input type="hidden"
         * name="productname-"+data
         * .lineId+" id="productname-" +data.lineId+ "
         * value=" + data.productName + "> <div
         * id="productText">" + data.productName + " </div> " + prop + "</td>
         * <td class="quantity">"; <div
         * id="qmessage-"+data.lineId+"\"></div> <input type="text"
         * name="quantity-" +data.lineId+
         * " value="1" id="quantity-" +data.lineId+ " maxlength="3" />";</td>
         * <td class="price"><div
         * id="pmessage-"+data.lineId+"></div><input type="
         * text" name="price-" +data.lineId+ " value=" + data.priceText + "
         * id="price-" +data.lineId+ " size="5" maxlength="5" /></td>
         * </tr>
         */

        Context ctx = super.getContext();

        // check that customer.customerId is there

        // order
        Order savedOrder = SessionUtil.getOrder(super.getServletRequest());

        // check sdate edate
        savedOrder.setDatePurchased(DateUtil.getDate(sdate));
        savedOrder.setOrderDateFinished(DateUtil.getDate(edate));
        savedOrder.setOrderId(this.getOrder().getOrderId());
        savedOrder.setDisplayInvoicePayments(this.getOrder().isDisplayInvoicePayments());

        OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);

        Customer customer = SessionUtil.getCustomer(super.getServletRequest());
        customer.setLocale(super.getLocale());

        this.setCustomerText(formatCustomer(customer));

        // get latest shipping information
        ShippingInformation shippingInformation = SessionUtil.getShippingInformation(super.getServletRequest());

        Shipping shipping = null;

        if (shippingInformation != null && shippingInformation.getShippingMethodId() != null) {
            shipping = new Shipping();
            shipping.setHandlingCost(shippingInformation.getHandlingCost());
            shipping.setShippingCost(shippingInformation.getShippingCost());
            shipping.setShippingDescription(shippingInformation.getShippingMethod());

            shipping.setShippingModule(shippingInformation.getShippingModule());
        }

        int cartLines = 0;

        List ids = this.getIds();

        List processProducts = new ArrayList();

        Map products = SessionUtil.getOrderProducts(super.getServletRequest());

        if (ids == null || ids.size() == 0) {
            MessageUtil.addErrorMessage(super.getServletRequest(),
                    LabelUtil.getInstance().getText(super.getLocale(), "error.cart.recalculate"));
            return ERROR;
        }

        Iterator idIterator = ids.iterator();
        boolean hasError = false;

        OrderProduct op = null;

        while (idIterator.hasNext()) {
            Object o = idIterator.next();

            int iKey = -1;
            try {
                iKey = (Integer) o;
            } catch (Exception ignore) {
                continue;
            }
            try {
                cartLines = cartLines + iKey;
                // now get the productid, quantity and price
                String sProductId = super.getServletRequest().getParameter("productid-" + iKey);
                String sQuantity = super.getServletRequest().getParameter("quantity-" + iKey);
                String sPrice = super.getServletRequest().getParameter("price-" + iKey);
                // get orderproduct
                op = (OrderProduct) products.get(String.valueOf(iKey));
                if (op == null) {
                    // throw an exception
                    MessageUtil.addErrorMessage(super.getServletRequest(),
                            LabelUtil.getInstance().getText(super.getLocale(), "error.cart.recalculate"));
                    return ERROR;
                }

                op.setPriceText(sPrice);
                op.setQuantityText(sQuantity);

                processProducts.add(op);

                // validate quantity and price

                long productId = Long.parseLong(sProductId);

                int quantity = 0;
                try {
                    quantity = Integer.parseInt(sQuantity);
                } catch (Exception e) {
                    // TODO: handle exception
                    hasError = true;
                    if (op != null) {
                        op.setErrorMessage(
                                LabelUtil.getInstance().getText(super.getLocale(), "errors.quantity.invalid"));
                    }
                }

                BigDecimal price = new BigDecimal("0");
                try {
                    price = CurrencyUtil.validateCurrency(sPrice, ctx.getCurrency());
                } catch (Exception e) {
                    // TODO: handle exception
                    hasError = true;
                    if (op != null) {
                        op.setPriceErrorMessage(
                                LabelUtil.getInstance().getText(super.getLocale(), "messages.price.invalid"));
                    }
                }

                // set the submited data
                op.setProductQuantity(quantity);
                op.setProductPrice(price);

                op.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(price, ctx.getCurrency()));

                double finalPrice = price.doubleValue();
                BigDecimal bdFinalPrice = new BigDecimal(finalPrice);
                op.setCostText(CurrencyUtil.displayFormatedAmountWithCurrency(bdFinalPrice, ctx.getCurrency()));
                op.setPriceText(CurrencyUtil.displayFormatedAmountNoCurrency(price, ctx.getCurrency()));

                BigDecimal bdFinalPriceQty = bdFinalPrice.multiply(new BigDecimal(quantity));

                //op.setFinalPrice(bdFinalPrice);
                op.setFinalPrice(bdFinalPriceQty);

            } catch (Exception e) {
                log.error(e);
                super.setTechnicalMessage();
                hasError = true;
            }

        }

        summary = oservice.calculateTotal(savedOrder, processProducts, customer, shipping, ctx.getCurrency(),
                super.getLocale());
        OrderProduct[] opArray = new OrderProduct[processProducts.size()];
        OrderProduct[] objects = (OrderProduct[]) processProducts.toArray(opArray);
        summary.setOrderProducts(objects);

        MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
        MerchantStore store = mservice.getMerchantStore(ctx.getMerchantid());

        super.getServletRequest().setAttribute("ORDERTOTALSUMMARY", summary);

        if (hasError) {
            return ERROR;
        }

        oservice.saveInvoice(ctx.getMerchantid(), savedOrder.getOrderId(), savedOrder.getDatePurchased(),
                savedOrder.getOrderDateFinished(), this.getComments(), savedOrder.isDisplayInvoicePayments(),
                processProducts, customer, shipping, store, super.getLocale());

        // url
        LabelUtil lhelper = LabelUtil.getInstance();
        lhelper.setLocale(super.getLocale());
        StringBuffer url = new StringBuffer().append("<a href='")
                .append(FileUtil.getInvoiceUrl(savedOrder, customer)).append("&request_locale=")
                .append(customer.getCustomerLang()).append("_").append(super.getLocale().getCountry())
                .append("' target='_blank'>");
        url.append(lhelper.getText(customer.getCustomerLang(), "label.email.invoice.viewinvoice"))
                .append("</a>");

        this.setInvoiceUrl(url.toString());

        super.setSuccessMessage();

        return SUCCESS;

    } catch (Exception e) {
        log.error(e);
        super.setTechnicalMessage();
        return ERROR;
    }

}

From source file:org.efaps.esjp.accounting.transaction.evaluation.DocumentInfo_Base.java

/**
 * Apply exchange gain loss./* ww w  .j  av  a 2  s. c  o m*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @throws EFapsException on error
 */
public void applyExchangeGainLoss(final Parameter _parameter) throws EFapsException {
    final AccountInfo gainAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGEGAIN);
    final AccountInfo lossAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGELOSS);

    if (gainAcc != null && lossAcc != null) {
        final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment);
        queryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, getInstance());
        final MultiPrintQuery multi = queryBldr.getPrint();
        final SelectBuilder selDocInst = new SelectBuilder().linkto(CISales.Payment.FromAbstractLink)
                .instance();
        final SelectBuilder selCurInst = new SelectBuilder().linkto(CISales.Payment.CurrencyLink).instance();
        multi.addSelect(selDocInst, selCurInst);
        multi.addAttribute(CISales.Payment.Amount, CISales.Payment.Date);
        multi.execute();
        while (multi.next()) {
            final Instance docInst = multi.getSelect(selDocInst);
            final PrintQuery print = new PrintQuery(docInst);
            final SelectBuilder selDocCurInst = new SelectBuilder()
                    .linkto(CISales.DocumentSumAbstract.RateCurrencyId).instance();
            print.addSelect(selDocCurInst);
            print.addAttribute(CIERP.DocumentAbstract.Date);
            print.execute();
            final Instance curInst = multi.getSelect(selCurInst);
            final Instance docCurInst = print.getSelect(selDocCurInst);
            final DateTime docDate = print.getAttribute(CIERP.DocumentAbstract.Date);
            final DateTime dateTmp = multi.getAttribute(CISales.Payment.Date);
            final BigDecimal amountTmp = multi.getAttribute(CISales.Payment.Amount);

            if (!curInst.equals(Currency.getBaseCurrency()) || !docCurInst.equals(Currency.getBaseCurrency())) {
                final Currency currency = new Currency();
                final RateInfo[] rateInfos1 = currency.evaluateRateInfos(_parameter, dateTmp, curInst,
                        docCurInst);
                final RateInfo[] rateInfos2 = currency.evaluateRateInfos(_parameter, docDate, curInst,
                        docCurInst);
                final int idx;
                // payment in BaseCurreny ==> Document was not BaseCurrency therefore current against target
                if (curInst.equals(Currency.getBaseCurrency())) {
                    idx = 2;
                    // Document in  BaseCurrency ==> payment was not BaseCurrency therefore current against base
                } else if (docCurInst.equals(Currency.getBaseCurrency())) {
                    idx = 0;
                    // neither Document nor payment are BaseCurrency but are the same
                } else if (curInst.equals(docCurInst)) {
                    idx = 0;
                } else {
                    idx = 0;
                }

                final BigDecimal rate1 = RateInfo.getRate(_parameter, rateInfos1[idx],
                        docInst.getType().getName());
                final BigDecimal rate2 = RateInfo.getRate(_parameter, rateInfos2[idx],
                        docInst.getType().getName());
                if (rate1.compareTo(rate2) != 0) {
                    final BigDecimal amount1 = amountTmp.divide(rate1, BigDecimal.ROUND_HALF_UP);
                    final BigDecimal amount2 = amountTmp.divide(rate2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal gainLoss = amount1.subtract(amount2);
                    if (idx == 2) {
                        gainLoss = gainLoss.multiply(rate1);
                    }
                    if (gainLoss.compareTo(BigDecimal.ZERO) != 0) {
                        final boolean out = getInstance().getType()
                                .isKindOf(CISales.PaymentDocumentOutAbstract);
                        if (out) {
                            final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) > 0;
                            for (final AccountInfo accinfo : getCreditAccounts()) {
                                if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) {
                                    final BigDecimal accAmount;
                                    if (accinfo.getRateInfo().getCurrencyInstance()
                                            .equals(Currency.getBaseCurrency())) {
                                        accAmount = gainLoss;
                                    } else {
                                        accAmount = gainLoss.multiply(accinfo.getRate(_parameter));
                                    }
                                    accinfo.addAmount(accAmount.negate());
                                }
                            }
                            if (gain) {
                                gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addCredit(gainAcc);
                            } else {
                                lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addDebit(lossAcc);
                            }
                        } else {
                            final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) < 0;
                            for (final AccountInfo accinfo : getDebitAccounts()) {
                                if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) {
                                    final BigDecimal accAmount;
                                    if (!accinfo.getRateInfo().getCurrencyInstance()
                                            .equals(Currency.getBaseCurrency())) {
                                        accAmount = gainLoss;
                                    } else {
                                        accAmount = gainLoss.multiply(accinfo.getRate(_parameter));
                                    }
                                    accinfo.addAmount(accAmount);
                                }
                            }
                            if (gain) {
                                gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addDebit(gainAcc);
                            } else {
                                lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addCredit(lossAcc);
                            }
                        }
                    }
                }
            }
        }
    }
}