Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

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

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:org.egov.ptis.service.dashboard.SurveyDashboardService.java

private void getTaxDifferences(Map<String, Long> completedApplicationsMap,
        Map<String, List<Map<String, BigDecimal>>> approvedTotalMap, SurveyResponse surveyResponse,
        Bucket bucket, Map<String, List<BigDecimal>> taxMap) {
    BigDecimal approvedSysTax;/*  w  w  w . j  a va2 s  .co  m*/
    BigDecimal approvedTotalTax;
    String name = bucket.getKeyAsString();
    if (taxMap.containsKey(name)) {
        surveyResponse.setExptdIncr(taxMap.get(name).get(0).subtract(taxMap.get(name).get(1)).doubleValue());
        surveyResponse
                .setDiffFromSurveytax(taxMap.get(name).get(0).subtract(taxMap.get(name).get(2)).doubleValue());
    }
    if (completedApplicationsMap.get(name) != null)
        surveyResponse.setTotalCompleted(completedApplicationsMap.get(name));
    surveyResponse.setTotalPending(surveyResponse.getTotalReceived() - surveyResponse.getTotalCompleted()
            - surveyResponse.getTotalCancelled());
    if (approvedTotalMap.containsKey(name)) {
        approvedSysTax = approvedTotalMap.get(name).get(0).get("approvedSystemTax");
        approvedTotalTax = approvedTotalMap.get(name).get(1).get("totalApprovedTax");
        surveyResponse.setActlIncr(approvedTotalTax.subtract(approvedSysTax).doubleValue());
    }
    surveyResponse.setDifference(surveyResponse.getExptdIncr() - surveyResponse.getActlIncr());
}

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;/* www .  ja  v a2s . 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.gradoop.flink.datagen.transactions.foodbroker.config.FoodBrokerConfig.java

/**
 * Adds positive or negative influence to the start value, depending on the
 * quality of the master data objects.//from  ww  w  .  j ava  2s .c  o m
 *
 * @param influencingMasterDataQuality list of influencing master data quality
 * @param higherIsBetter true if positiv influence shall be added, negative
 *                       influence otherwise
 * @param influence influence value to be added to the start value
 * @param startValue the start value
 * @return aggregated start value
 */
protected Float getValue(List<Float> influencingMasterDataQuality, boolean higherIsBetter, Float influence,
        Float startValue) {
    Float value = startValue;

    BigDecimal influenceCount = BigDecimal.ZERO;

    for (float quality : influencingMasterDataQuality) {
        // check quality value of the masterdata and adjust the result value
        influenceCount = influenceCount.add(BigDecimal.valueOf(quality));
    }

    if (influenceCount.compareTo(BigDecimal.ZERO) > 0) {
        influenceCount = influenceCount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // normalize the quality value
        influenceCount = influenceCount.divide(BigDecimal.valueOf(influencingMasterDataQuality.size()), 8,
                RoundingMode.HALF_UP);
        // subtract the avg normal, for standard config it is 0.5
        influenceCount = influenceCount.subtract(getAvgNormal());

        // if the normalized value is greater than the avg
        if (influenceCount.compareTo(BigDecimal.ZERO) == 1) {
            // calculate how much times the value is greater than the difference
            // between the avg normal value and the lowest good value
            influenceCount = influenceCount.divide(
                    BigDecimal.valueOf(getQualityGood()).subtract(getAvgNormal()).abs(), 0,
                    BigDecimal.ROUND_HALF_UP);
            // if the normalized value is LOWER than the avg
        } else if (influenceCount.compareTo(BigDecimal.ZERO) == -1) {
            // calculate how much times the value is smaller than the difference
            // between the avg normal value and the lowest normal value
            influenceCount = influenceCount.divide(
                    BigDecimal.valueOf(getQualityNormal()).subtract(getAvgNormal()).abs(), 0,
                    BigDecimal.ROUND_HALF_UP);
        }
    }
    influence *= influenceCount.intValue();

    if (higherIsBetter) {
        value += influence;
    } else {
        value -= influence;
    }
    return value;
}

From source file:de.hybris.platform.b2bacceleratorservices.jalo.promotions.ProductPriceDiscountPromotionByPaymentType.java

@Override
public List<PromotionResult> evaluate(final SessionContext ctx, final PromotionEvaluationContext promoContext) {
    final List<PromotionResult> promotionResults = new ArrayList<PromotionResult>();
    // Find all valid products in the cart
    final PromotionsManager.RestrictionSetResult restrictionResult = this.findEligibleProductsInBasket(ctx,
            promoContext);/* w  w  w.ja va 2 s . c o m*/

    if (restrictionResult.isAllowedToContinue() && !restrictionResult.getAllowedProducts().isEmpty()) {
        final PromotionOrderView view = promoContext.createView(ctx, this,
                restrictionResult.getAllowedProducts());
        final AbstractOrder order = promoContext.getOrder();

        for (final PromotionOrderEntry entry : view.getAllEntries(ctx)) {
            // Get the next order entry
            final long quantityToDiscount = entry.getQuantity(ctx);
            if (quantityToDiscount > 0) {
                final long quantityOfOrderEntry = entry.getBaseOrderEntry().getQuantity(ctx).longValue();

                // The adjustment to the order entry
                final double originalUnitPrice = entry.getBasePrice(ctx).doubleValue();
                final double originalEntryPrice = quantityToDiscount * originalUnitPrice;

                final Currency currency = promoContext.getOrder().getCurrency(ctx);
                Double discountPriceValue;

                final EnumerationValue paymentType = B2BAcceleratorServicesManager.getInstance()
                        .getPaymentType(ctx, order);

                if (paymentType != null
                        && StringUtils.equalsIgnoreCase(paymentType.getCode(), getPaymentType().getCode())) {
                    promoContext.startLoggingConsumed(this);
                    discountPriceValue = this.getPriceForOrder(ctx, this.getProductDiscountPrice(ctx),
                            promoContext.getOrder(),
                            ProductPriceDiscountPromotionByPaymentType.PRODUCTDISCOUNTPRICE);

                    final BigDecimal adjustedEntryPrice = Helper.roundCurrencyValue(ctx, currency,
                            originalEntryPrice - (quantityToDiscount * discountPriceValue.doubleValue()));
                    // Calculate the unit price and round it
                    final BigDecimal adjustedUnitPrice = Helper.roundCurrencyValue(ctx, currency,
                            adjustedEntryPrice.equals(BigDecimal.ZERO) ? BigDecimal.ZERO
                                    : adjustedEntryPrice.divide(BigDecimal.valueOf(quantityToDiscount),
                                            RoundingMode.HALF_EVEN));

                    for (final PromotionOrderEntryConsumed poec : view.consume(ctx, quantityToDiscount)) {
                        poec.setAdjustedUnitPrice(ctx, adjustedUnitPrice.doubleValue());
                    }

                    final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx,
                            this, promoContext.getOrder(), 1.0F);
                    result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, true));
                    final BigDecimal adjustment = Helper.roundCurrencyValue(ctx, currency,
                            adjustedEntryPrice.subtract(BigDecimal.valueOf(originalEntryPrice)));
                    final PromotionOrderEntryAdjustAction poeac = PromotionsManager.getInstance()
                            .createPromotionOrderEntryAdjustAction(ctx, entry.getBaseOrderEntry(),
                                    quantityOfOrderEntry, adjustment.doubleValue());
                    result.addAction(ctx, poeac);
                    promotionResults.add(result);
                }
            }
        }
        final long remainingCount = view.getTotalQuantity(ctx);
        if (remainingCount > 0) {
            promoContext.startLoggingConsumed(this);
            view.consume(ctx, remainingCount);
            final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx, this,
                    promoContext.getOrder(), 0.5F);
            result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, false));
            promotionResults.add(result);
        }
    }
    return promotionResults;
}

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

/**
 * Riemann zeta function.//from  www.  java2  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.egov.works.services.AbstractEstimateService.java

private void persistReleaseDepositWorksAmountDetails(final DepositWorksUsage depositWorksUsage) {
    AbstractEstimateAppropriation estimateAppropriation = null;
    final BigDecimal creditBalance = depositWorksUsage.getTotalDepositAmount();
    final AbstractEstimate abstractEstimate = depositWorksUsage.getAbstractEstimate();
    final BigDecimal utilizedAmt = depositWorksUsageService
            .getTotalUtilizedAmountForDepositWorks(abstractEstimate.getFinancialDetails().get(0), new Date());
    final BigDecimal balance = creditBalance.subtract(utilizedAmt);
    estimateAppropriation = estimateAppropriationService
            .findByNamedQuery("getLatestDepositWorksUsageForEstimate", abstractEstimate.getId());
    estimateAppropriation.setBalanceAvailable(balance);
    estimateAppropriation.setDepositWorksUsage(depositWorksUsage);
    estimateAppropriationService.persist(estimateAppropriation);
}

From source file:org.kuali.kfs.module.ar.document.validation.impl.CustomerCreditMemoDocumentRule.java

public boolean checkIfCustomerCreditMemoQtyAndCustomerCreditMemoItemAmountValid(
        CustomerCreditMemoDetail customerCreditMemoDetail, BigDecimal unitPrice) {
    KualiDecimal creditAmount = customerCreditMemoDetail.getCreditMemoItemTotalAmount();
    BigDecimal creditQuantity = customerCreditMemoDetail.getCreditMemoItemQuantity();

    // if unit price is zero, leave this validation, as it will cause an exception below by attempting to divide by zero
    if (unitPrice.compareTo(BigDecimal.ZERO) == 0) {
        // no need to report error, because it is already recorded by another validation check.
        return false;
    }/*from  ww  w  .j  a v a2  s.  co m*/

    // determine the expected exact total credit memo quantity, based on actual credit amount entered
    BigDecimal expectedCreditQuantity = creditAmount.bigDecimalValue().divide(unitPrice,
            ArConstants.ITEM_QUANTITY_SCALE, BigDecimal.ROUND_HALF_UP);

    // return false if the expected quantity is 0 while the actual quantity is not
    if (expectedCreditQuantity.compareTo(BigDecimal.ZERO) == 0
            && creditQuantity.compareTo(BigDecimal.ZERO) != 0) {
        return false;
    }

    // determine the deviation percentage that the actual creditQuantity has from expectedCreditQuantity
    BigDecimal deviationPercentage = creditQuantity.subtract(expectedCreditQuantity)
            .divide(expectedCreditQuantity, ArConstants.ITEM_QUANTITY_SCALE, BigDecimal.ROUND_HALF_UP).abs();

    // only allow a certain deviation of creditQuantity from the expectedCreditQuantity
    boolean validFlag = deviationPercentage.compareTo(ALLOWED_QTY_DEVIATION) < 1;

    if (!validFlag) {
        GlobalVariables.getMessageMap().putError(
                ArPropertyConstants.CustomerCreditMemoDocumentFields.CREDIT_MEMO_ITEM_QUANTITY,
                ArKeyConstants.ERROR_CUSTOMER_CREDIT_MEMO_DETAIL_INVALID_DATA_INPUT);
        GlobalVariables.getMessageMap().putError(
                ArPropertyConstants.CustomerCreditMemoDocumentFields.CREDIT_MEMO_ITEM_TOTAL_AMOUNT,
                ArKeyConstants.ERROR_CUSTOMER_CREDIT_MEMO_DETAIL_INVALID_DATA_INPUT);
    }
    return validFlag;
}

From source file:org.egov.collection.service.elasticsearch.CollectionDocumentElasticSearchService.java

public List<TaxPayerDashBoardDetails> returnUlbWiseAggregationResults(
        final CollectionDashBoardRequest collectionDashBoardRequest, final String indexName,
        final Boolean order, final String orderingAggregationName, final int size,
        final List<String> serviceDetails) {
    final List<TaxPayerDashBoardDetails> taxPayers = new ArrayList<>();
    BoolQueryBuilder boolQuery = prepareWhereClause(collectionDashBoardRequest);
    if (!serviceDetails.isEmpty())
        boolQuery = boolQuery.filter(QueryBuilders.termsQuery(BILLING_SERVICE, serviceDetails));
    String groupingField;/*www  .ja  va2  s .c o  m*/
    if (StringUtils.isNotBlank(collectionDashBoardRequest.getUlbCode())
            || StringUtils.isNotBlank(collectionDashBoardRequest.getType())
                    && collectionDashBoardRequest.getType().equals(DASHBOARD_GROUPING_WARDWISE))
        groupingField = REVENUE_WARD;
    else
        groupingField = CITY_NAME;

    Long startTime = System.currentTimeMillis();
    AggregationBuilder aggregation;
    SearchQuery searchQueryColl;
    aggregation = AggregationBuilders.terms(BY_AGGREGATION_FIELD).field(groupingField).size(size)
            .order(Terms.Order.aggregation(orderingAggregationName, order))
            .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field(TOTAL_AMOUNT));
    searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
            .addAggregation(aggregation).build();
    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken by ulbWiseAggregations is : " + timeTaken + MILLISECS);

    TaxPayerDashBoardDetails taxDetail;
    boolean isWard = false;
    startTime = System.currentTimeMillis();
    final Date fromDate = new DateTime().withMonthOfYear(4).dayOfMonth().withMinimumValue().toDate();
    final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    final Date lastYearFromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1);
    final Date lastYearToDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1);
    final StringTerms totalAmountAggr = collAggr.get(BY_AGGREGATION_FIELD);
    for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) {
        taxDetail = new TaxPayerDashBoardDetails();
        taxDetail.setRegionName(collectionDashBoardRequest.getRegionName());
        taxDetail.setDistrictName(collectionDashBoardRequest.getDistrictName());
        taxDetail.setUlbGrade(collectionDashBoardRequest.getUlbGrade());
        final String fieldName = String.valueOf(entry.getKey());
        if (groupingField.equals(REVENUE_WARD)) {
            taxDetail.setWardName(fieldName);
            isWard = true;
        } else
            taxDetail.setUlbName(fieldName);
        final Sum totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION);
        final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP);
        taxDetail.setCytdColl(totalCollections);
        final BigDecimal lastYearCollection = getCollectionBetweenDates(collectionDashBoardRequest,
                lastYearFromDate, lastYearToDate, fieldName, serviceDetails, isWard);
        taxDetail.setLytdColl(lastYearCollection);
        BigDecimal variation;
        if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0)
            variation = CollectionConstants.BIGDECIMAL_100;
        else
            variation = totalCollections.subtract(lastYearCollection)
                    .multiply(CollectionConstants.BIGDECIMAL_100)
                    .divide(lastYearCollection, 1, BigDecimal.ROUND_HALF_UP);
        taxDetail.setLyVar(variation);
        taxPayers.add(taxDetail);
    }
    timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken for setting values in returnUlbWiseAggregationResults() is : " + timeTaken
                + MILLISECS);
    return returnTopResults(taxPayers, size, order);
}

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

private static boolean calculateTransactionPriceDifferenceLogic(MaterialTransaction materialTransaction)
        throws OBException {
    boolean costAdjCreated = false;

    // With Standard Algorithm, no cost adjustment is needed
    if (StringUtils.equals(materialTransaction.getCostingAlgorithm().getJavaClassName(),
            "org.openbravo.costing.StandardAlgorithm")) {
        return false;
    }//from w w w  . j  a va 2  s  . c  o  m

    if (materialTransaction.isCostPermanent()) {
        // Permanently adjusted transaction costs are not checked for price differences.
        return false;
    }
    Currency trxCurrency = materialTransaction.getCurrency();
    Organization trxOrg = materialTransaction.getOrganization();
    Date trxDate = materialTransaction.getMovementDate();
    int costCurPrecission = trxCurrency.getCostingPrecision().intValue();
    ShipmentInOutLine receiptLine = materialTransaction.getGoodsShipmentLine();
    if (receiptLine == null
            || !isValidPriceAdjTrx(receiptLine.getMaterialMgmtMaterialTransactionList().get(0))) {
        // We can only adjust cost of receipt lines.
        return false;
    }

    BigDecimal receiptQty = receiptLine.getMovementQuantity();
    boolean isNegativeReceipt = receiptQty.signum() == -1;
    if (isNegativeReceipt) {
        // If the receipt is negative convert the quantity to positive.
        receiptQty = receiptQty.negate();
    }

    Date costAdjDateAcct = null;
    BigDecimal invoiceAmt = BigDecimal.ZERO;

    // Calculate current transaction unit cost including existing adjustments.
    BigDecimal currentTrxUnitCost = CostAdjustmentUtils.getTrxCost(materialTransaction, true, trxCurrency);

    // Calculate expected transaction unit cost based on current invoice amounts and purchase price.
    BigDecimal expectedCost = BigDecimal.ZERO;
    BigDecimal invoiceQty = BigDecimal.ZERO;
    for (ReceiptInvoiceMatch matchInv : receiptLine.getProcurementReceiptInvoiceMatchList()) {
        Invoice invoice = matchInv.getInvoiceLine().getInvoice();
        if (invoice.getDocumentStatus().equals("VO")) {
            // Skip voided invoices.
            continue;
        }
        if (!invoice.isProcessed()) {
            // Skip not processed invoices.
            continue;
        }
        if (isNegativeReceipt) {
            // If the receipt is negative negate the invoiced quantities.
            invoiceQty = invoiceQty.add(matchInv.getQuantity().negate());
        } else {
            invoiceQty = invoiceQty.add(matchInv.getQuantity());
        }
        invoiceAmt = matchInv.getQuantity().multiply(matchInv.getInvoiceLine().getUnitPrice());

        invoiceAmt = FinancialUtils.getConvertedAmount(invoiceAmt, invoice.getCurrency(), trxCurrency, trxDate,
                trxOrg, FinancialUtils.PRECISION_STANDARD, invoice.getCurrencyConversionRateDocList());
        expectedCost = expectedCost.add(invoiceAmt);

        Date invoiceDate = invoice.getInvoiceDate();
        if (costAdjDateAcct == null || costAdjDateAcct.before(invoiceDate)) {
            costAdjDateAcct = invoiceDate;
        }
    }

    BigDecimal notInvoicedQty = receiptQty.subtract(invoiceQty);
    if (notInvoicedQty.signum() > 0) {
        // Not all the receipt line is invoiced, add pending invoice quantity valued with current
        // order price if exists or original unit cost.
        BigDecimal basePrice = BigDecimal.ZERO;
        Currency baseCurrency = trxCurrency;
        if (receiptLine.getSalesOrderLine() != null) {
            basePrice = receiptLine.getSalesOrderLine().getUnitPrice();
            baseCurrency = receiptLine.getSalesOrderLine().getSalesOrder().getCurrency();
        } else {
            basePrice = materialTransaction.getTransactionCost().divide(receiptQty, costCurPrecission,
                    RoundingMode.HALF_UP);
        }
        BigDecimal baseAmt = notInvoicedQty.multiply(basePrice).setScale(costCurPrecission,
                RoundingMode.HALF_UP);
        if (!baseCurrency.getId().equals(trxCurrency.getId())) {
            baseAmt = FinancialUtils.getConvertedAmount(baseAmt, baseCurrency, trxCurrency, trxDate, trxOrg,
                    FinancialUtils.PRECISION_STANDARD);
        }
        expectedCost = expectedCost.add(baseAmt);
    }
    // if the sum of trx costs with flag "isInvoiceCorrection" is distinct that the amount cost
    // generated by Match Invoice then New Cost Adjustment line is created by the difference
    if (expectedCost.compareTo(currentTrxUnitCost) != 0) {
        if (costAdjDateAcct == null) {
            costAdjDateAcct = trxDate;
        }
        createCostAdjustmenHeader(trxOrg);
        CostAdjustmentLine costAdjLine = CostAdjustmentUtils.insertCostAdjustmentLine(materialTransaction,
                costAdjHeader, expectedCost.subtract(currentTrxUnitCost), Boolean.TRUE, costAdjDateAcct);
        costAdjLine.setNeedsPosting(Boolean.TRUE);
        OBDal.getInstance().save(costAdjLine);
        costAdjCreated = true;
    }

    return costAdjCreated;
}

From source file:org.key2gym.business.services.OrdersServiceBean.java

public static OrderDTO wrapOrderEntity(OrderEntity order) {

    OrderDTO orderDTO = new OrderDTO();
    orderDTO.setId(order.getId());/*from   www  .  j  a v  a  2s . c o m*/
    orderDTO.setDate(new DateMidnight(order.getDate()));
    orderDTO.setPayment(order.getPayment().setScale(2));

    /*
     * Order lines
     */
    List<OrderLineDTO> orderLineDTOs = new LinkedList<OrderLineDTO>();

    BigDecimal total = BigDecimal.ZERO.setScale(2);

    if (order.getOrderLines() != null) {
        for (OrderLine orderLine : order.getOrderLines()) {
            Item item = orderLine.getItem();
            Discount discount = orderLine.getDiscount();

            OrderLineDTO orderLineDTO = new OrderLineDTO();
            orderLineDTO.setId(orderLine.getId());
            orderLineDTO.setItemId(item.getId());
            orderLineDTO.setItemTitle(item.getTitle());
            orderLineDTO.setItemPrice(item.getPrice());
            if (discount != null) {
                orderLineDTO.setDiscountPercent(discount.getPercent());
                orderLineDTO.setDiscountTitle(discount.getTitle());
                orderLineDTO.setDiscountId(discount.getId());
            }
            orderLineDTO.setQuantity(orderLine.getQuantity());
            orderLineDTO.setTotal(orderLine.getTotal());

            total = total.add(orderLine.getTotal());

            orderLineDTOs.add(orderLineDTO);
        }
    }
    orderDTO.setOrderLines(orderLineDTOs);

    /*
     * Client
     */
    if (order.getClient() != null) {
        orderDTO.setClientId(order.getClient().getId());
        orderDTO.setClientFullName(order.getClient().getFullName());
    }

    /*
     * Attendance
     */
    if (order.getAttendance() != null) {
        orderDTO.setAttendanceId(order.getAttendance().getId());
        orderDTO.setKeyTitle(order.getAttendance().getKey().getTitle());
    }

    /*
     * Total
     */
    orderDTO.setTotal(total);

    /*
     * Due
     */
    orderDTO.setDue(total.subtract(order.getPayment()));

    /*
     * Money balance
     */
    if (order.getClient() != null) {
        orderDTO.setMoneyBalance(order.getClient().getMoneyBalance().setScale(2).underlying());
    }
    return orderDTO;
}