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:org.openbravo.erpCommon.ad_forms.AcctServer.java

public static BigDecimal applyRate(BigDecimal _amount, ConversionRateDoc conversionRateDoc, boolean multiply) {
    BigDecimal amount = _amount;
    if (multiply) {
        return amount.multiply(conversionRateDoc.getRate());
    } else {//from w  ww  .ja  va 2 s  . c  o  m
        return amount.divide(conversionRateDoc.getRate(), 6, BigDecimal.ROUND_HALF_EVEN);
    }
}

From source file:it.av.es.service.impl.OrderServiceHibernate.java

/**
 * {@inheritDoc}/*  w  w  w.  j  a va  2s  .  c  om*/
 */
@Override
public Order calculatesCostsAndDiscount(Order o) {
    //ArrayList<ProductOrdered> newList = new ArrayList<ProductOrdered>(o.getProductsOrdered().size());
    for (ProductOrdered p : o.getProductsOrdered()) {
        BigDecimal amount = new BigDecimal(0);
        Currency currency;
        int percentDiscount = 0;
        List<Price> prices = p.getProduct().getPrices();
        //calculates  the price and apply discount 

        // per il cacolo somma tutti i prodotti dello stesso tipo
        int productAllOrder = o.getTotalProductforGivenProduct(p.getProduct());
        // se il prodoptto appartiene ad una famigliam considera anche i prodotti di quella famiglia
        if (p.getProduct().getProductFamily() != null) {
            productAllOrder = o.getTotalProductforGivenProductFamily(p.getProduct().getProductFamily());
        }

        for (Price price : prices) {
            if (productAllOrder >= price.getFromNumber() && productAllOrder <= price.getToNumber()) {
                amount = price.getAmount();
                currency = price.getCurrency();
                percentDiscount = price.getPercentDiscount();
            }
        }
        if (amount == BigDecimal.ZERO) {
            throw new EasySendException("Price not available");
        }
        p.setAmount(amount.multiply(BigDecimal.valueOf(p.getNumber())));
        //apply discount if applicable
        if (o.getPaymentTypeP().getDiscount() > 0) {
            BigDecimal discount = ((p.getAmount().divide(BigDecimal.valueOf(100)))
                    .multiply(BigDecimal.valueOf(o.getPaymentTypeP().getDiscount())));
            p.setAmount(p.getAmount().subtract(discount));
            percentDiscount = percentDiscount + o.getPaymentTypeP().getDiscount();
        }
        p.setDiscount(percentDiscount);

        //add the productOrdered to the order
        //            o.getProductsOrdered().add(p);
        //apply Discounts If Applicable
        //applyDiscountIfApplicable(order);
        //apply FreeShippingCost If Applicable

    }
    //o.setProductsOrdered(newList);
    //applyFreeShippingCostIfApplicable(o);
    return o;
}

From source file:fr.hoteia.qalingo.core.web.mvc.factory.impl.ViewBeanFactoryImpl.java

/**
 * @throws Exception//w  ww  .j  a  v  a2s  .  com
 * 
 */
public CartViewBean buildCartViewBean(final RequestData requestData, final Cart cart) throws Exception {
    final MarketArea marketArea = requestData.getMarketArea();
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();

    final CartViewBean cartViewBean = new CartViewBean();

    cartViewBean.setCartDetailsUrl(urlService.generateUrl(FoUrls.CART_DETAILS, requestData));
    cartViewBean.setCartAuthUrl(urlService.generateUrl(FoUrls.CART_AUTH, requestData));
    cartViewBean.setCartDeliveryAndOrderDetailsUrl(urlService.generateUrl(FoUrls.CART_DELIVERY, requestData));
    cartViewBean.setCartOrderPaymentUrl(urlService.generateUrl(FoUrls.CART_ORDER_PAYMENT, requestData));
    cartViewBean
            .setCartOrderConfirmationUrl(urlService.generateUrl(FoUrls.CART_ORDER_CONFIRMATION, requestData));

    cartViewBean.setAddNewAddressUrl(urlService.generateUrl(FoUrls.PERSONAL_ADD_ADDRESS, requestData));

    // ITEMS PART
    List<CartItemViewBean> cartItemViewBeans = new ArrayList<CartItemViewBean>();
    Set<CartItem> cartItems = cart.getCartItems();
    for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
        final CartItem cartItem = (CartItem) iterator.next();
        cartItemViewBeans.add(buildCartItemViewBean(requestData, cartItem));
    }
    cartViewBean.setCartItems(cartItemViewBeans);

    // SUB PART : Subtotal
    final String currencyCode = marketArea.getCurrency().getCode();
    final NumberFormat formatter = requestUtil.getCartItemPriceNumberFormat(requestData, currencyCode);
    BigDecimal cartItemsTotal = new BigDecimal("0");
    BigDecimal cartShippingTotal = new BigDecimal("0");
    BigDecimal cartFeesTotal = new BigDecimal("0");
    BigDecimal carTotal = new BigDecimal("0");
    for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
        final CartItem cartItem = (CartItem) iterator.next();
        if (cartItem.getPrice() != null) {
            cartItemsTotal = cartItemsTotal.add(cartItem.getPrice());
        }
    }

    // SUB PART : Shippings
    final List<CartShippingViewBean> cartShippingViewBeans = new ArrayList<CartShippingViewBean>();
    final Set<Shipping> shippings = cart.getShippings();
    if (shippings != null) {
        for (Iterator<Shipping> iterator = shippings.iterator(); iterator.hasNext();) {
            final Shipping shipping = (Shipping) iterator.next();
            final CartShippingViewBean cartShippingViewBean = new CartShippingViewBean();
            if (shipping.getPrice() != null) {
                cartShippingTotal = cartShippingTotal.add(shipping.getPrice());
                cartShippingViewBean.setCartShippingTotal(formatter.format(shipping.getPrice()));
            }
            Object[] params = { shipping.getName() };
            cartShippingViewBean.setCartShippingTotalLabel(getSpecificMessage(ScopeWebMessage.COMMON,
                    "shoppingcart.amount.shippings", params, locale));
            cartShippingViewBeans.add(cartShippingViewBean);
        }
        cartViewBean.setCartShippings(cartShippingViewBeans);
    }

    // SUB PART : Taxes
    final List<CartTaxViewBean> cartTaxViewBeans = new ArrayList<CartTaxViewBean>();
    final Set<Tax> taxes = cart.getTaxes();
    if (taxes != null) {
        for (Iterator<Tax> iterator = taxes.iterator(); iterator.hasNext();) {
            final Tax tax = (Tax) iterator.next();
            final CartTaxViewBean cartTaxViewBean = new CartTaxViewBean();
            BigDecimal taxesCalc = cartItemsTotal;
            taxesCalc = taxesCalc.multiply(tax.getPercent());
            taxesCalc = taxesCalc.divide(new BigDecimal("100"));
            cartFeesTotal = cartFeesTotal.add(taxesCalc);
            Object[] params = { tax.getName() };
            cartTaxViewBean.setCartTaxTotal(formatter.format(taxesCalc));
            cartTaxViewBean.setCartTaxTotalLabel(
                    getSpecificMessage(ScopeWebMessage.COMMON, "shoppingcart.amount.taxes", params, locale));
            cartTaxViewBeans.add(cartTaxViewBean);
        }
        cartViewBean.setCartTaxes(cartTaxViewBeans);
    }
    carTotal = carTotal.add(cartItemsTotal);
    carTotal = carTotal.add(cartShippingTotal);
    carTotal = carTotal.add(cartFeesTotal);
    cartViewBean.setCartItemsTotal(formatter.format(cartItemsTotal));
    cartViewBean.setCartShippingTotal(formatter.format(cartShippingTotal));
    cartViewBean.setCartFeesTotal(formatter.format(cartFeesTotal));
    cartViewBean.setCartTotal(formatter.format(carTotal));

    return cartViewBean;
}

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

/**
 * calculates values for a list of accounting lines based on an amount taking discount into account
 *
 * @param sourceAccountingLines//  w ww . j  av a  2  s .c o m
 * @param totalAmount
 * @param discountAmount
 */
@Override
public <T extends PurApAccountingLine> void updateAccountAmountsWithTotal(List<T> sourceAccountingLines,
        KualiDecimal totalAmount, KualiDecimal discountAmount) {

    // if we have a discount, then we need to base the amounts on the discount, but the percent on the total
    boolean noDiscount = true;
    if ((discountAmount != null) && KualiDecimal.ZERO.compareTo(discountAmount) != 0) {
        noDiscount = false;
    }

    if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) {

        KualiDecimal accountTotal = KualiDecimal.ZERO;
        BigDecimal accountTotalPercent = BigDecimal.ZERO;
        T lastAccount = null;

        for (T account : sourceAccountingLines) {
            if (ObjectUtils.isNotNull(account.getAccountLinePercent())
                    || ObjectUtils.isNotNull(account.getAmount())) {
                if (ObjectUtils.isNotNull(account.getAmount())
                        && account.getAmount().isGreaterThan(KualiDecimal.ZERO)) {
                    KualiDecimal amt = account.getAmount();
                    KualiDecimal calculatedPercent = new KualiDecimal(
                            amt.multiply(new KualiDecimal(100)).divide(totalAmount).toString());
                    account.setAccountLinePercent(
                            calculatedPercent.bigDecimalValue().setScale(BIG_DECIMAL_SCALE));
                }

                if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                    BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString())
                            .divide(new BigDecimal(100));
                    if (noDiscount) {
                        if (ObjectUtils.isNull(account.getAmount()) || account.getAmount().isZero()) {
                            account.setAmount(
                                    new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString()))
                                            .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
                        }
                    } else {
                        account.setAmount(
                                new KualiDecimal(pct.multiply(new BigDecimal(discountAmount.toString()))
                                        .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
                    }
                }
            }

            if (ObjectUtils.isNotNull(account.getAmount())) {
                accountTotal = accountTotal.add(account.getAmount());
            }
            if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
            }

            lastAccount = account;
        }

        // put excess on last account
        if (lastAccount != null) {
            KualiDecimal difference = new KualiDecimal(0);
            if (noDiscount) {
                difference = totalAmount.subtract(accountTotal);
            } else {
                difference = discountAmount.subtract(accountTotal);
            }
            if (ObjectUtils.isNotNull(lastAccount.getAmount())) {
                lastAccount.setAmount(lastAccount.getAmount().add(difference));
            }

            BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent)
                    .setScale(BIG_DECIMAL_SCALE);
            if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) {
                lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
            }
        }
    } else {
        // zero out if extended price is zero
        for (T account : sourceAccountingLines) {
            account.setAmount(KualiDecimal.ZERO);
        }
    }
}

From source file:fr.hoteia.qalingo.core.web.mvc.factory.impl.ViewBeanFactoryImpl.java

/**
  * /*from  www. j  a  v a 2  s  . co m*/
  */
public OrderViewBean buildOrderViewBean(final RequestData requestData, final Order order) throws Exception {
    final MarketArea marketArea = requestData.getMarketArea();
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();
    final String orderId = order.getId().toString();
    final OrderViewBean orderViewBean = new OrderViewBean();

    // ITEMS PART
    final List<OrderItemViewBean> orderItemViewBeans = new ArrayList<OrderItemViewBean>();
    final Set<OrderItem> orderItems = order.getOrderItems();
    for (Iterator<OrderItem> iterator = orderItems.iterator(); iterator.hasNext();) {
        OrderItem orderItem = (OrderItem) iterator.next();
        orderItemViewBeans.add(buildOrderItemViewBean(requestData, orderItem));
    }
    orderViewBean.setOrderItems(orderItemViewBeans);

    // SUB PART : Subtotal
    final String currencyCode = marketArea.getCurrency().getCode();
    final NumberFormat formatter = requestUtil.getCartItemPriceNumberFormat(requestData, currencyCode);
    BigDecimal orderItemsTotal = new BigDecimal("0");
    BigDecimal orderShippingTotal = new BigDecimal("0");
    BigDecimal orderFeesTotal = new BigDecimal("0");
    BigDecimal orderTotal = new BigDecimal("0");
    for (Iterator<OrderItem> iterator = orderItems.iterator(); iterator.hasNext();) {
        final OrderItem orderItem = (OrderItem) iterator.next();
        if (orderItem.getPrice() != null) {
            orderItemsTotal = orderItemsTotal.add(orderItem.getPrice());
        }
    }

    // SUB PART : Shippings
    final List<OrderShippingViewBean> orderShippingViewBeans = new ArrayList<OrderShippingViewBean>();
    final Set<OrderShipment> orderShipments = order.getOrderShipments();
    if (orderShipments != null) {
        for (Iterator<OrderShipment> iterator = orderShipments.iterator(); iterator.hasNext();) {
            final OrderShipment orderShipment = (OrderShipment) iterator.next();
            final OrderShippingViewBean orderShippingViewBean = new OrderShippingViewBean();
            if (orderShipment.getPrice() != null) {
                orderShippingTotal = orderShippingTotal.add(orderShipment.getPrice());
                orderShippingViewBean.setOrderShippingTotal(formatter.format(orderShipment.getPrice()));
            }
            Object[] params = { orderShipment.getName() };
            orderShippingViewBean.setOrderShippingTotalLabel(getSpecificMessage(ScopeWebMessage.COMMON,
                    "shoppingcart.amount.shippings", params, locale));
            orderShippingViewBeans.add(orderShippingViewBean);
        }
        orderViewBean.setOrderShippings(orderShippingViewBeans);
    }

    // SUB PART : Taxes
    final List<OrderTaxViewBean> orderTaxViewBeans = new ArrayList<OrderTaxViewBean>();
    final Set<OrderTax> orderTaxes = order.getOrderTaxes();
    if (orderTaxes != null) {
        for (Iterator<OrderTax> iterator = orderTaxes.iterator(); iterator.hasNext();) {
            final OrderTax orderTax = (OrderTax) iterator.next();
            final OrderTaxViewBean orderTaxViewBean = new OrderTaxViewBean();
            BigDecimal taxesCalc = orderItemsTotal;
            taxesCalc = taxesCalc.multiply(orderTax.getPercent());
            taxesCalc = taxesCalc.divide(new BigDecimal("100"));
            orderFeesTotal = orderFeesTotal.add(taxesCalc);
            Object[] params = { orderTax.getName() };
            orderTaxViewBean.setOrderTaxTotal(formatter.format(taxesCalc));
            orderTaxViewBean.setOrderTaxTotalLabel(
                    getSpecificMessage(ScopeWebMessage.COMMON, "shoppingcart.amount.taxes", params, locale));
            orderTaxViewBeans.add(orderTaxViewBean);
        }
        orderViewBean.setOrderTaxes(orderTaxViewBeans);
    }
    orderTotal = orderTotal.add(orderItemsTotal);
    orderTotal = orderTotal.add(orderShippingTotal);
    orderTotal = orderTotal.add(orderFeesTotal);
    orderViewBean.setOrderItemsTotal(formatter.format(orderItemsTotal));
    orderViewBean.setOrderShippingTotal(formatter.format(orderShippingTotal));
    orderViewBean.setOrderFeesTotal(formatter.format(orderFeesTotal));
    orderViewBean.setOrderTotal(formatter.format(orderTotal));

    // final Object[] params = {order.getOrderNum()};
    // orderViewBean.setConfirmationMessage(getSpecificMessage(ScopeWebMessage.COMMON,
    // "order.confirmation.message", params, locale));

    Map<String, String> urlParams = new HashMap<String, String>();
    urlParams.put(RequestConstants.REQUEST_PARAMETER_CUSTOMER_ORDER_ID, orderId.toString());

    orderViewBean
            .setOrderDetailsUrl(urlService.generateUrl(FoUrls.PERSONAL_ORDER_DETAILS, requestData, urlParams));

    return orderViewBean;
}

From source file:org.egov.works.web.actions.measurementbook.MeasurementBookAction.java

private BigDecimal getAmountsForCurrentMB(final List<MBDetails> mbDetailsList, final double negoPerc,
        final String tenderType) {

    BigDecimal currentMBTenderedAmt = BigDecimal.ZERO;
    BigDecimal currMBAmount = BigDecimal.ZERO;
    BigDecimal tenderedMBAmount = BigDecimal.ZERO;
    BigDecimal currMBTotal = BigDecimal.ZERO;

    if (tenderType.equalsIgnoreCase(WorksConstants.PERC_TENDER)) {
        for (final MBDetails mbd : mbDetailsList)
            if (mbd.getWorkOrderActivity().getActivity().getRevisionType() == null)
                currentMBTenderedAmt = currentMBTenderedAmt.add(BigDecimal.valueOf(mbd.getAmount()));
        currMBAmount = mbHeader.getTotalMBAmount();

        // applying percentage on tendered items
        if (currentMBTenderedAmt != null)
            tenderedMBAmount = currentMBTenderedAmt
                    .add(currentMBTenderedAmt.multiply(BigDecimal.valueOf(negoPerc / 100)));
        // adding tendered amount with the non tendered items amount, to get
        // the total mb amount
        currMBTotal = tenderedMBAmount.add(currMBAmount.subtract(currentMBTenderedAmt));
    } else/*w  w w.  j  av  a 2s . c  o m*/
        currMBTotal = mbHeader.getTotalMBAmount();

    return currMBTotal.setScale(2, RoundingMode.HALF_UP);
}

From source file:org.egov.ptis.service.es.PropertyTaxElasticSearchIndexService.java

/**
 * Returns Top Ten with ULB wise grouping and total amount aggregation
 *
 * @param collectionDetailsRequest/*ww  w .  j  a  v  a 2 s. com*/
 * @param indexName
 * @param order
 * @param orderingAggregationName
 * @return
 */
public List<TaxPayerDetails> returnUlbWiseAggregationResults(
        final CollectionDetailsRequest collectionDetailsRequest, final String indexName, final Boolean order,
        final String orderingAggregationName, final int size, final boolean isBillCollectorWise,
        CFinancialYear currFinYear) {
    BigDecimal proportionalArrearDmd;
    BigDecimal proportionalCurrDmd;
    BigDecimal variation;
    Sum totalDemandAggregation;
    Sum totalCollectionAggregation;
    Sum arrearDmd;
    Sum currentDmd;
    Sum arrearInterestDmd;
    Sum currentInterestDmd;
    Sum arrearCollAmt;
    Sum currentCollAmt;
    Sum arrearIntColl;
    Sum currentIntColl;
    final List<TaxPayerDetails> taxPayers = new ArrayList<>();
    Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>();
    final BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest)
            .filter(QueryBuilders.matchQuery(IS_ACTIVE, true))
            .filter(QueryBuilders.matchQuery(IS_EXEMPTED, false));

    // orderingAggregationName is the aggregation name by which we have to
    // order the results
    // IN this case can be one of "totaldemand" or "total_collection" or
    // "avg_achievement"
    String groupingField;
    if (StringUtils.isNotBlank(collectionDetailsRequest.getUlbCode()) || StringUtils
            .isNotBlank(collectionDetailsRequest.getType())
            && (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_BILLCOLLECTORWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_REVENUEINSPECTORWISE
                            .equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_REVENUEOFFICERWISE
                            .equalsIgnoreCase(collectionDetailsRequest.getType())))
        groupingField = REVENUE_WARD;
    else
        groupingField = CITY_NAME;

    AggregationBuilder aggregation;
    SearchQuery searchQueryColl;
    // Apply the ordering and max results size only if the type is not
    // billcollector
    if (!isBillCollectorWise) {
        aggregation = prepareAggregationForTaxPayers(size, groupingField)
                .order(Terms.Order.aggregation(orderingAggregationName, order));
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .addAggregation(aggregation).build();
    } else {
        aggregation = prepareAggregationForTaxPayers(250, groupingField);
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .withPageable(new PageRequest(0, 250)).addAggregation(aggregation).build();
    }

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Date fromDate = DateUtils.startOfDay(currFinYear.getStartingDate());
    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);

    // Fetch ward wise Bill Collector details for ward based grouping
    if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType()))
        wardWiseBillCollectors = collectionIndexElasticSearchService
                .getWardWiseBillCollectors(collectionDetailsRequest);

    TaxPayerDetails taxDetail;
    final StringTerms totalAmountAggr = collAggr.get(BY_AGGREGATION_FIELD);
    BigDecimal lastYearCollection;
    for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) {
        taxDetail = new TaxPayerDetails();
        taxDetail.setRegionName(collectionDetailsRequest.getRegionName());
        taxDetail.setDistrictName(collectionDetailsRequest.getDistrictName());
        taxDetail.setUlbGrade(collectionDetailsRequest.getUlbGrade());
        final String fieldName = String.valueOf(entry.getKey());
        // If the grouping is based on ward, set the Bill Collector name and number
        if (groupingField.equals(REVENUE_WARD)) {
            taxDetail.setWardName(fieldName);
            if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    && !wardWiseBillCollectors.isEmpty()) {
                taxDetail.setBillCollector(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollector());
                taxDetail.setBillCollMobNo(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollectorMobileNo());
                taxDetail.setBillCollectorCode(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollectorCode());
            }
        } else
            taxDetail.setUlbName(fieldName);

        // Proportional Demand = (totalDemand/12)*noOfmonths
        final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
        totalDemandAggregation = entry.getAggregations().get(TOTALDEMAND);
        totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION);
        arrearDmd = entry.getAggregations().get(ARREAR_DMD_STR);
        currentDmd = entry.getAggregations().get(CURR_DMD);
        arrearInterestDmd = entry.getAggregations().get(ARREAR_INTEREST_DMD);
        currentInterestDmd = entry.getAggregations().get(CURR_INTEREST_DMD);
        arrearCollAmt = entry.getAggregations().get(ARREAR_COLLECTION);
        currentCollAmt = entry.getAggregations().get(ANNUAL_COLLECTION);
        arrearIntColl = entry.getAggregations().get(ARREAR_INTEREST_COLLECTION);
        currentIntColl = entry.getAggregations().get(CURRENT_INTEREST_COLLECTION);

        final BigDecimal totalDemandValue = BigDecimal.valueOf(totalDemandAggregation.getValue()).setScale(0,
                BigDecimal.ROUND_HALF_UP);
        final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP);
        final BigDecimal proportionalDemand = totalDemandValue
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        taxDetail.setTotalDmd(totalDemandValue);
        taxDetail.setCytdColl(totalCollections);
        taxDetail.setCytdDmd(proportionalDemand);
        if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0)
            taxDetail.setAchievement(totalCollections.multiply(BIGDECIMAL_100).divide(proportionalDemand, 1,
                    BigDecimal.ROUND_HALF_UP));
        taxDetail.setCytdBalDmd(proportionalDemand.subtract(totalCollections));
        if (StringUtils.isNotBlank(taxDetail.getUlbName()))
            lastYearCollection = collectionIndexElasticSearchService.getCollectionBetweenDates(
                    collectionDetailsRequest, lastYearFromDate, lastYearToDate, fieldName, null, "totalAmount");
        else
            lastYearCollection = collectionIndexElasticSearchService.getCollectionBetweenDates(
                    collectionDetailsRequest, lastYearFromDate, lastYearToDate, null, fieldName, "totalAmount");
        taxDetail.setLytdColl(lastYearCollection);
        taxDetail.setArrearColl(
                BigDecimal.valueOf(arrearCollAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentColl(
                BigDecimal.valueOf(currentCollAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setInterestColl(
                BigDecimal.valueOf(arrearIntColl.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).add(
                        BigDecimal.valueOf(currentIntColl.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        taxDetail.setArrearDemand(
                BigDecimal.valueOf(arrearDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentDemand(
                BigDecimal.valueOf(currentDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setArrearInterestDemand(
                BigDecimal.valueOf(arrearInterestDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentInterestDemand(
                BigDecimal.valueOf(currentInterestDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        proportionalArrearDmd = taxDetail.getArrearDemand()
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        proportionalCurrDmd = taxDetail.getCurrentDemand()
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        taxDetail.setProportionalArrearDemand(proportionalArrearDmd);
        taxDetail.setProportionalCurrentDemand(proportionalCurrDmd);

        // variance = ((currentYearCollection -
        // lastYearCollection)*100)/lastYearCollection

        if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0)
            variation = BIGDECIMAL_100;
        else
            variation = totalCollections.subtract(lastYearCollection).multiply(BIGDECIMAL_100)
                    .divide(lastYearCollection, 1, BigDecimal.ROUND_HALF_UP);
        taxDetail.setLyVar(variation);
        taxPayers.add(taxDetail);
    }
    // If for Bill Collector, then fetch details for all wards, else limit
    // the results size
    if (isBillCollectorWise)
        return taxPayers;
    else
        return returnTopResults(taxPayers, size, order);
}

From source file:org.egov.restapi.service.BudgetCheckService.java

public BigDecimal getAllocatedBudget(final BudgetCheck budgetCheck) {
    BigDecimal budgetAmountForYear, planningPercentForYear;
    final Scheme scheme = schemeService.findByCode(budgetCheck.getSchemeCode());
    final SubScheme subScheme = subSchemeService.findByCode(budgetCheck.getSubSchemeCode());
    final List<BudgetGroup> budgetheadid = new ArrayList<>();
    budgetheadid.add(budgetGroupService.getBudgetGroupByName(budgetCheck.getBudgetHeadName()));
    Map<String, Object> paramMap = new HashMap<String, Object>();
    // prepare paramMap
    paramMap.put(Constants.DEPTID,/*from   w  ww  . java  2 s.co  m*/
            departmentService.getDepartmentByCode(budgetCheck.getDepartmentCode()).getId());
    paramMap.put(Constants.FUNCTIONID, functionService.findByCode(budgetCheck.getFunctionCode()).getId());
    paramMap.put(Constants.FUNCTIONARYID, null);
    paramMap.put(Constants.SCHEMEID, scheme == null ? null : Integer.parseInt(scheme.getId().toString()));
    paramMap.put(Constants.SUBSCHEMEID,
            subScheme == null ? null : Integer.parseInt(subScheme.getId().toString()));
    paramMap.put(Constants.FUNDID,
            Integer.parseInt(fundService.findByCode(budgetCheck.getFundCode()).getId().toString()));
    paramMap.put(Constants.BOUNDARYID, null);
    paramMap.put("budgetheadid", budgetheadid);
    paramMap.put("financialyearid", financialYearHibernateDAO.getFinYearByDate(new Date()).getId());
    budgetAmountForYear = budgetDetailsDAO.getBudgetedAmtForYear(paramMap);

    paramMap.put(Constants.DEPTID,
            departmentService.getDepartmentByCode(budgetCheck.getDepartmentCode()).getId().intValue());
    planningPercentForYear = budgetDetailsDAO.getPlanningPercentForYear(paramMap);

    return ((budgetAmountForYear.multiply(planningPercentForYear)).divide(new BigDecimal(100))).setScale(2,
            BigDecimal.ROUND_UP);
}

From source file:org.efaps.esjp.accounting.transaction.FieldValue_Base.java

/**
 * Get the script to get the Prices for the Products.
 *
 * @param _parameter        Parameter as passed from the eFaps API
 * @param _doc              Instance of the Document the form was opened for
 * @throws EFapsException on error/*from   www.ja v  a  2s .  com*/
 */
protected void getPriceInformation(final Parameter _parameter, final DocumentInfo _doc) throws EFapsException {
    final QueryBuilder queryBldr = new QueryBuilder(CISales.PositionAbstract);
    queryBldr.addWhereAttrEqValue(CISales.PositionAbstract.DocumentAbstractLink, _doc.getInstance().getId());
    final MultiPrintQuery multi = queryBldr.getPrint();
    final SelectBuilder selTaxInst = new SelectBuilder().linkto(CISales.PositionSumAbstract.Tax).instance();
    final SelectBuilder selProdInst = new SelectBuilder().linkto(CISales.PositionAbstract.Product).instance();
    multi.addSelect(selTaxInst, selProdInst);
    multi.addAttribute(CISales.PositionSumAbstract.NetPrice, CISales.PositionSumAbstract.CrossPrice,
            CISales.PositionSumAbstract.Rate);
    multi.execute();
    final Instance period = new Period().evaluateCurrentPeriod(_parameter);
    while (multi.next()) {
        final BigDecimal net = multi.<BigDecimal>getAttribute(CISales.PositionSumAbstract.NetPrice);
        final BigDecimal cross = multi.<BigDecimal>getAttribute(CISales.PositionSumAbstract.CrossPrice);
        final Object[] ratePos = multi.<Object[]>getAttribute(CISales.PositionSumAbstract.Rate);
        final BigDecimal newRatepos = ((BigDecimal) ratePos[0]).divide((BigDecimal) ratePos[1], 12,
                BigDecimal.ROUND_HALF_UP);
        final BigDecimal taxAmount = cross.subtract(net).multiply(newRatepos);
        final BigDecimal prodAmount = net.multiply(newRatepos);
        analyzeTax(_doc, false, multi.<Instance>getSelect(selTaxInst), taxAmount);
        final RateInfo rate = evaluateRate(_parameter, period, _doc.getDate(), _doc.getRateCurrInst());
        analyzeProduct(_doc, false, multi.<Instance>getSelect(selProdInst), prodAmount, rate,
                CIAccounting.AccountIncomeStatementRevenue2ProductClass,
                CIAccounting.AccountIncomeStatementRevenue);
    }
}

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

private void calculateCosts(Organization org) {
    Currency cur = FinancialUtils.getLegalEntityCurrency(org);
    String curId = cur.getId();//from   w w  w . java2  s . c om
    Set<String> orgs = OBContext.getOBContext().getOrganizationStructureProvider(org.getClient().getId())
            .getChildTree(org.getId(), true);
    String orgId = org.getId();

    int costPrecision = cur.getCostingPrecision().intValue();
    int stdPrecision = cur.getStandardPrecision().intValue();
    CostingRuleProcess crp = new CostingRuleProcess();
    // Update cost of inventories and process starting physical inventories.
    ScrollableResults icls = getCloseInventoryLines(orgs);
    String productId = "";
    BigDecimal totalCost = BigDecimal.ZERO;
    BigDecimal totalStock = BigDecimal.ZERO;
    int i = 0;
    try {
        while (icls.next()) {
            InventoryCountLine icl = (InventoryCountLine) icls.get(0);
            if (!productId.equals(icl.getProduct().getId())) {
                productId = icl.getProduct().getId();
                HashMap<String, BigDecimal> stock = getCurrentValuedStock(productId, curId, orgs, orgId);
                totalCost = stock.get("cost");
                totalStock = stock.get("stock");
            }

            MaterialTransaction trx = crp.getInventoryLineTransaction(icl);
            trx.setTransactionProcessDate(DateUtils.addSeconds(trx.getTransactionProcessDate(), -1));
            trx.setCurrency(OBDal.getInstance().get(Currency.class, curId));

            BigDecimal trxCost = BigDecimal.ZERO;
            if (totalStock.compareTo(BigDecimal.ZERO) != 0) {
                trxCost = totalCost.multiply(trx.getMovementQuantity().abs()).divide(totalStock, stdPrecision,
                        BigDecimal.ROUND_HALF_UP);
            }
            if (trx.getMovementQuantity().compareTo(totalStock) == 0) {
                // Last transaction adjusts remaining cost amount.
                trxCost = totalCost;
            }
            trx.setTransactionCost(trxCost);
            trx.setCostCalculated(true);
            trx.setCostingStatus("CC");
            OBDal.getInstance().save(trx);
            Currency legalEntityCur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
            BigDecimal cost = BigDecimal.ZERO;
            if (BigDecimal.ZERO.compareTo(trx.getMovementQuantity()) != 0) {
                cost = trxCost.divide(trx.getMovementQuantity().abs(), costPrecision, BigDecimal.ROUND_HALF_UP);
            }
            if (!legalEntityCur.equals(cur)) {
                cost = FinancialUtils.getConvertedAmount(cost, cur, legalEntityCur, new Date(),
                        icl.getOrganization(), FinancialUtils.PRECISION_COSTING);
            }

            InventoryCountLine initICL = icl.getRelatedInventory();
            initICL.setCost(cost);
            OBDal.getInstance().save(initICL);

            totalCost = totalCost.subtract(trxCost);
            // MovementQty is already negative so add to totalStock to decrease it.
            totalStock = totalStock.add(trx.getMovementQuantity());

            if ((i % 100) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
                cur = OBDal.getInstance().get(Currency.class, curId);
            }
            i++;
        }
    } finally {
        icls.close();
    }

    OBDal.getInstance().flush();
    insertTrxCosts();

}