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.works.services.impl.ContractorBillServiceImpl.java

/**
 * The method return BigDecimal//w  w  w  .  ja v  a  2 s  .co m
 *
 * @param totalAdvancePaid , billDate, workOrderEstimate
 * @param workOrder        an instance of <code>WorkOrder</code>.
 * @return a BigDecimal value indicating total Advance pending for given Work Order Estimate as on bill date before this
 * current bill
 */
@Override
public BigDecimal calculateTotalPendingAdvance(final BigDecimal totalAdvancePaid, final Date billDate,
        final WorkOrderEstimate workOrderEstimate, final Long billId) {
    final CChartOfAccounts advanceCOA = contractorAdvanceService
            .getContractorAdvanceAccountcodeForWOE(workOrderEstimate.getId());

    BigDecimal totalPendingBalance = BigDecimal.ZERO;
    if (advanceCOA != null && totalAdvancePaid != null && totalAdvancePaid.compareTo(BigDecimal.ZERO) > 0) {
        BigDecimal totalAdvanceAdjusted = getTotalAdvanceAdjustedForWOE(billDate, workOrderEstimate.getId(),
                advanceCOA.getId(), billId);
        if (totalAdvanceAdjusted != null && totalAdvanceAdjusted.compareTo(BigDecimal.ZERO) > 0)
            totalPendingBalance = totalAdvanceAdjusted.subtract(totalAdvanceAdjusted);
        else
            totalPendingBalance = totalAdvancePaid;
    }

    return totalPendingBalance;
}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

private void calculateDependantDemand(short lowLevelCode) {
    for (MpsLine mpsLine : new ArrayList<MpsLine>(generatedMPSLines)) { // ? , ..  ? ? ?? generatedMPSLines
        if (mpsLine.getLevelCode() == lowLevelCode && MathUtils.compareToZero(mpsLine.getPlannedQty()) > 0) {
            BucketRange bucketRange = MfUtils.determineBucketRange(mps.getPlanningLevel().getId(),
                    mpsLine.getBucketOffset());
            BigDecimal PlannedQty = mpsLine.getPlannedQty(), MaxLotQty, Remainder, OddJobSize;
            PlannedQty = getMeasureConversionService().conversion(mpsLine.getMeasure(),
                    mpsLine.getPlanningItem().getCatalog().getMeasure1(),
                    mpsLine.getPlanningItem().getCatalog(), bucketRange.getBucketStart(), PlannedQty);

            Bom bom = bomService.findCurrentBOM(mpsLine.getPlanningItem().getCatalog().getId());
            if (bom == null)
                continue;

            MaxLotQty = bom.getMaxLotQty();
            if (MathUtils.compareToZero(MaxLotQty) == 0)
                MaxLotQty = PlannedQty; //Infinite maximum size
            long NumberOfMaxJobs = PlannedQty.divide(MaxLotQty).longValue();
            Remainder = PlannedQty.subtract(MaxLotQty.multiply(new BigDecimal(NumberOfMaxJobs)));
            OddJobSize = Remainder;/*from w w w  .j  a v  a2  s. c  om*/

            long CurrentRequiredDate = MfUtils.dateToTick(DateTimeUtils.incDay(bucketRange.getBucketEnd(), 1))
                    - 1000; //   ?
            mpsMaterialBreakdown(bom, mpsLine, 1,
                    MaxLotQty.multiply(new BigDecimal(NumberOfMaxJobs)).add(OddJobSize), CurrentRequiredDate);
        }
    }
}

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

/**
 * Returns Top Ten with ULB wise grouping and total amount aggregation
 *
 * @param collectionDetailsRequest//from   w  ww.  j  a v  a2  s  .co m
 * @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.apache.fineract.portfolio.servicecharge.service.ServiceChargeJournalDetailsReadPlatformServiceImpl.java

private BigDecimal calculateTotalAmountForJournalEntriesOfGivenListOfGLs(List<GLAccountData> glAccountData) {
    BigDecimal finalAmount = new BigDecimal(0);

    if (glAccountData != null && !glAccountData.isEmpty()) {
        for (GLAccountData glAccount : glAccountData) {
            // Start from 0 entries and get all entries by passing limit=-1
            final SearchParameters searchParameters = SearchParameters.forJournalEntries(null, 0, -1, null,
                    null, null, null);/*from  w w  w  .j  a v  a2s .com*/
            final JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(
                    false, false);

            final Date fromDateParam = QuarterDateRange.getCurrentQuarter().getFromDateForCurrentYear();
            final Date toDateParam = QuarterDateRange.getCurrentQuarter().getToDateForCurrentYear();

            Page<JournalEntryData> journalEntryDataPage = journalEntryReadPlatformService.retrieveAll(
                    searchParameters, glAccount.getId(), true, fromDateParam, toDateParam, StringUtils.EMPTY, 0,
                    associationParametersData);
            for (JournalEntryData journalData : journalEntryDataPage.getPageItems()) {
                JournalEntryType entryType = JournalEntryType
                        .fromInt(journalData.getEntryType().getId().intValue());
                switch (entryType) {
                case DEBIT:
                    finalAmount = finalAmount.add(journalData.getAmount());
                    break;
                case CREDIT:
                    finalAmount = finalAmount.subtract(journalData.getAmount());
                    break;
                }
            }
        } // End of for-loop
    } // End of outer if-condition
    return finalAmount;
}

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

@Override
protected void getRelatedTransactionsByAlgorithm() {
    // Search all transactions after the date of the adjusted line and recalculate the costs of them
    // to adjust differences
    MaterialTransaction basetrx = getTransaction();
    // Transactions of closing inventories are managed by generic CostAdjustmentProcess adjusting
    // the cost of the related opening inventory.
    if (basetrx.getPhysicalInventoryLine() != null
            && basetrx.getPhysicalInventoryLine().getRelatedInventory() != null) {
        return;//from  w w w.  ja  v  a2s . c o  m
    }
    BigDecimal signMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
    Date trxDate = basetrx.getTransactionProcessDate();

    BigDecimal adjustmentBalance = BigDecimal.ZERO;
    BigDecimal unitCostAdjustmentBalance = BigDecimal.ZERO;
    // Initialize adjustment balance looping through all cost adjustment lines of current
    // transaction.
    log.debug("Initialize adjustment balance");
    CostAdjustmentLine baseCAL = getCostAdjLine();
    for (CostAdjustmentLine costAdjLine : getTrxAdjustmentLines(basetrx)) {
        if (costAdjLine.isSource() && !costAdjLine.isRelatedTransactionAdjusted()
                && !costAdjLine.getId().equals(strCostAdjLineId)) {
            searchRelatedTransactionCosts(costAdjLine);
        }

        costAdjLine.setRelatedTransactionAdjusted(Boolean.TRUE);
        if (!costAdjLine.getId().equals(strCostAdjLineId)) {
            costAdjLine.setParentCostAdjustmentLine(baseCAL);
        }
        OBDal.getInstance().save(costAdjLine);
        // If the cost adjustment line has Transaction Costs those adjustment amount are included
        // in the Current Value Amount and not in the Adjustment Balance
        if (!costAdjLine.getTransactionCostList().isEmpty()) {
            continue;
        }
        BigDecimal adjustmentAmt = costAdjLine.getAdjustmentAmount();
        if (!strCostCurrencyId.equals(costAdjLine.getCurrency().getId())) {
            adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, costAdjLine.getCurrency(),
                    getCostCurrency(), costAdjLine.getAccountingDate(), getCostOrg(),
                    FinancialUtils.PRECISION_STANDARD);
        }
        adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(signMultiplier));
        if (costAdjLine.isUnitCost()) {
            unitCostAdjustmentBalance = unitCostAdjustmentBalance.add(adjustmentAmt);
        }
    }

    // Initialize current stock qty and value amt.
    BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed);
    BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed, getCostCurrency());
    log.debug(
            "Adjustment balance: " + adjustmentBalance.toPlainString() + ", current stock {}, current value {}",
            currentStock.toPlainString(), currentValueAmt.toPlainString());

    // Initialize current unit cost including the cost adjustments.
    Costing costing = AverageAlgorithm.getProductCost(trxDate, basetrx.getProduct(), getCostDimensions(),
            getCostOrg());
    if (costing == null) {
        throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: "
                + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(trxDate));
    }
    BigDecimal cost = null;
    // If current stock is zero the cost is not modified until a related transaction that modifies
    // the stock is found.
    if (currentStock.signum() != 0) {
        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                RoundingMode.HALF_UP);
    }
    log.debug("Starting average cost {}", cost == null ? "not cost" : cost.toPlainString());
    if (cost != null && (AverageAlgorithm.modifiesAverage(trxType) || !baseCAL.isBackdatedTrx())) {
        BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(basetrx, true, getCostCurrency());
        BigDecimal trxPrice = null;
        if (basetrx.getMovementQuantity().signum() == 0) {
            trxPrice = BigDecimal.ZERO;
        } else {
            trxPrice = trxUnitCost.add(unitCostAdjustmentBalance).divide(basetrx.getMovementQuantity().abs(),
                    costCurPrecission, RoundingMode.HALF_UP);
        }
        if (checkNegativeStockCorrection && currentStock.compareTo(basetrx.getMovementQuantity()) < 0
                && cost.compareTo(trxPrice) != 0 && !baseCAL.isNegativeStockCorrection()
                && AverageAlgorithm.modifiesAverage(trxType)) {
            // stock was negative and cost different than trx price then Negative Stock Correction
            // is added
            BigDecimal trxSignMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
            BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                    .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                    .subtract(adjustmentBalance);
            adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
            // If there is a difference insert a cost adjustment line.
            CostAdjustmentLine newCAL = insertCostAdjustmentLine(basetrx, negCorrAmt, null);
            newCAL.setNegativeStockCorrection(Boolean.TRUE);
            newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
            newCAL.setUnitCost(Boolean.FALSE);
            OBDal.getInstance().save(newCAL);
            cost = trxPrice;
            log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                    cost.toPlainString());
        }
        if (basetrx.getMaterialMgmtCostingList().size() == 0) {
            Date newDate = new Date();
            Date dateTo = costing.getEndingDate();
            costing.setEndingDate(newDate);
            OBDal.getInstance().save(costing);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(basetrx);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(basetrx.getMovementQuantity());
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
            OBDal.getInstance().flush();
        } else {
            Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0);

            if (curCosting.getCost().compareTo(cost) != 0
                    || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                curCosting.setPermanent(Boolean.FALSE);
                OBDal.getInstance().save(curCosting);
                OBDal.getInstance().flush();
                // Update existing costing
                if (curCosting.getCost().compareTo(cost) != 0) {
                    if (curCosting.getOriginalCost() == null) {
                        curCosting.setOriginalCost(curCosting.getCost());
                    }
                    curCosting.setCost(cost);
                    curCosting.setPrice(trxPrice);
                }
                curCosting.setTotalMovementQuantity(currentStock);
                curCosting.setPermanent(Boolean.TRUE);
                OBDal.getInstance().flush();
                OBDal.getInstance().save(curCosting);
            }
        }
    }

    // Modify isManufacturingProduct flag in case it has changed at some point.
    isManufacturingProduct = ((String) DalUtil.getId(costing.getOrganization())).equals("0");

    ScrollableResults trxs = getRelatedTransactions();
    String strCurrentCurId = strCostCurrencyId;
    try {
        while (trxs.next()) {
            MaterialTransaction trx = (MaterialTransaction) trxs.get()[0];
            log.debug("Process related transaction {}", trx.getIdentifier());
            BigDecimal trxSignMultiplier = new BigDecimal(trx.getMovementQuantity().signum());
            BigDecimal trxAdjAmt = BigDecimal.ZERO;
            BigDecimal trxUnitCostAdjAmt = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(bdCostingId) && !isBackdatedTransaction(trx)) {
                // If there is a backdated source adjustment pending modify the dates of its m_costing.
                updateBDCostingTimeRange(trx);
                // This update is done only on the first related transaction.
                bdCostingId = "";
            }

            if (!strCurrentCurId.equals(trx.getCurrency().getId())) {
                Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                Organization costOrg = getCostOrg();

                currentValueAmt = FinancialUtils.getConvertedAmount(currentValueAmt, curCurrency,
                        trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_STANDARD);
                if (cost != null) {
                    cost = FinancialUtils.getConvertedAmount(cost, curCurrency, trx.getCurrency(),
                            trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_COSTING);
                }

                strCurrentCurId = trx.getCurrency().getId();
            }

            List<CostAdjustmentLine> existingAdjLines = getTrxAdjustmentLines(trx);
            for (CostAdjustmentLine existingCAL : existingAdjLines) {
                if (existingCAL.isSource() && !existingCAL.isRelatedTransactionAdjusted()) {
                    searchRelatedTransactionCosts(existingCAL);
                }
                if (existingCAL.getTransactionCostList().isEmpty()
                        && !existingCAL.isRelatedTransactionAdjusted()) {
                    BigDecimal adjustmentAmt = existingCAL.getAdjustmentAmount();
                    if (!strCurrentCurId.equals(existingCAL.getCurrency().getId())) {
                        Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                        adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt,
                                existingCAL.getCurrency(), curCurrency, existingCAL.getAccountingDate(),
                                getCostOrg(), FinancialUtils.PRECISION_STANDARD);
                    }
                    trxAdjAmt = trxAdjAmt.add(adjustmentAmt);
                    adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(trxSignMultiplier));
                    if (existingCAL.isUnitCost()) {
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(adjustmentAmt);
                    }
                }

                existingCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                existingCAL.setParentCostAdjustmentLine((CostAdjustmentLine) OBDal.getInstance()
                        .getProxy(CostAdjustmentLine.ENTITY_NAME, strCostAdjLineId));

                OBDal.getInstance().save(existingCAL);
            }
            log.debug("Current trx adj amount of existing CALs {}", trxAdjAmt.toPlainString());

            BigDecimal trxCost = CostAdjustmentUtils.getTrxCost(trx, false,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            currentValueAmt = currentValueAmt.add(trxCost.multiply(trxSignMultiplier));
            currentStock = currentStock.add(trx.getMovementQuantity());
            log.debug("Updated current stock {} and, current value {}", currentStock.toPlainString(),
                    currentValueAmt.toPlainString());

            TrxType currentTrxType = TrxType.getTrxType(trx);

            if (AverageAlgorithm.modifiesAverage(currentTrxType)) {
                // Recalculate average, if current stock is zero the average is not modified
                if (currentStock.signum() != 0) {
                    cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                            RoundingMode.HALF_UP);
                }
                if (cost == null) {
                    continue;
                }
                log.debug("New average cost: {}", cost.toPlainString());
                Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                BigDecimal trxPrice = null;
                if (trx.getMovementQuantity().signum() == 0) {
                    trxPrice = BigDecimal.ZERO;
                } else {
                    trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                            costCurPrecission, RoundingMode.HALF_UP);
                }

                if (checkNegativeStockCorrection && currentStock.compareTo(trx.getMovementQuantity()) < 0
                        && cost.compareTo(trxPrice) != 0) {
                    // stock was negative and cost different than trx price then Negative Stock Correction
                    // is added
                    BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                            .subtract(adjustmentBalance);
                    adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
                    trxAdjAmt = trxAdjAmt.add(negCorrAmt.multiply(trxSignMultiplier));
                    // If there is a difference insert a cost adjustment line.
                    CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, negCorrAmt, null);
                    newCAL.setNegativeStockCorrection(Boolean.TRUE);
                    newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                    newCAL.setUnitCost(Boolean.FALSE);
                    OBDal.getInstance().save(newCAL);
                    cost = trxPrice;
                    log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                            cost.toPlainString());
                }

                if (curCosting.getCost().compareTo(cost) == 0 && StringUtils.isEmpty(bdCostingId)
                        && curCosting.getTotalMovementQuantity().compareTo(currentStock) == 0) {
                    // new cost hasn't changed and total movement qty is equal to current stock, following
                    // transactions will have the same cost, so no more
                    // related transactions are needed to include.
                    // If bdCosting is not empty it is needed to loop through the next related transaction
                    // to set the new time ringe of the costing.
                    log.debug("New cost matches existing cost. Adjustment finished.");
                    return;
                } else {
                    // Update existing costing
                    curCosting.setPermanent(Boolean.FALSE);
                    OBDal.getInstance().save(curCosting);
                    OBDal.getInstance().flush();
                    if (curCosting.getCost().compareTo(cost) != 0) {
                        if (curCosting.getOriginalCost() == null) {
                            curCosting.setOriginalCost(curCosting.getCost());
                        }
                        curCosting.setPrice(trxPrice);
                        curCosting.setCost(cost);
                    }
                    curCosting.setTotalMovementQuantity(currentStock);
                    curCosting.setPermanent(Boolean.TRUE);
                    OBDal.getInstance().save(curCosting);
                }
            } else if (cost != null && !isVoidedTrx(trx, currentTrxType)) {
                if (!trx.isCostPermanent()) {
                    // Check current trx unit cost matches new expected cost
                    BigDecimal expectedCost = cost.multiply(trx.getMovementQuantity().abs())
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP);
                    BigDecimal unitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                            OBDal.getInstance().get(Currency.class, strCurrentCurId));
                    unitCost = unitCost.add(trxAdjAmt);
                    log.debug("Is adjustment needed? Expected {} vs Current {}", expectedCost.toPlainString(),
                            unitCost.toPlainString());
                    if (expectedCost.compareTo(unitCost) != 0) {
                        trxAdjAmt = trxAdjAmt.add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(expectedCost.subtract(unitCost));
                        adjustmentBalance = adjustmentBalance
                                .add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        // If there is a difference insert a cost adjustment line.
                        CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx,
                                expectedCost.subtract(unitCost), null);
                        newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                        OBDal.getInstance().save(newCAL);
                        log.debug("Adjustment added. Amount {}.",
                                expectedCost.subtract(unitCost).toPlainString());
                    }
                }
                if (trx.getMaterialMgmtCostingList().size() != 0) {
                    Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                    if (currentStock.signum() != 0) {
                        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                                RoundingMode.HALF_UP);
                    }
                    BigDecimal trxPrice = null;
                    if (trx.getMovementQuantity().signum() == 0) {
                        trxPrice = BigDecimal.ZERO;
                    } else {
                        trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                                costCurPrecission, RoundingMode.HALF_UP);
                    }
                    if (curCosting.getCost().compareTo(cost) != 0
                            || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                        curCosting.setPermanent(Boolean.FALSE);
                        OBDal.getInstance().save(curCosting);
                        OBDal.getInstance().flush();
                        if (curCosting.getCost().compareTo(cost) != 0) {
                            if (curCosting.getOriginalCost() == null) {
                                curCosting.setOriginalCost(curCosting.getCost());
                            }
                            curCosting.setPrice(trxPrice);
                            curCosting.setCost(cost);
                        }
                        curCosting.setTotalMovementQuantity(currentStock);
                        curCosting.setPermanent(Boolean.TRUE);
                        OBDal.getInstance().save(curCosting);
                    }
                }
            }

            OBDal.getInstance().flush();
            OBDal.getInstance().getSession().clear();
        }
    } finally {
        trxs.close();
    }

    if (getCostingRule().getEndingDate() == null && cost != null) {
        // This is the current costing rule. Check if current average cost needs to be updated.
        Costing currentCosting = AverageAlgorithm.getProductCost(new Date(), basetrx.getProduct(),
                getCostDimensions(), getCostOrg());
        if (currentCosting == null) {
            throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName()
                    + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: "
                    + OBDateUtils.formatDate(new Date()));
        }
        if (currentCosting.getCost().compareTo(cost) != 0) {
            basetrx = getTransaction();
            Date newDate = new Date();
            Date dateTo = currentCosting.getEndingDate();
            currentCosting.setEndingDate(newDate);
            OBDal.getInstance().save(currentCosting);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCurrentCurId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(null);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(null);
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
        }
    }
}

From source file:com.autentia.tnt.bean.billing.BillBean.java

private void calcTotals(List<Bill> res) {

    BigDecimal totals = new BigDecimal(0);
    BigDecimal totalsNoTaxes = new BigDecimal(0);
    BigDecimal totalsUnpaid = new BigDecimal(0);
    for (Bill elem : res) {
        totals = totals.add(elem.getTotal());
        totalsNoTaxes = totalsNoTaxes.add(elem.getTotalNoTaxes());
        totalsUnpaid = totalsUnpaid.add(elem.getUnpaid());
    }//from  w w w.j  ava2s  . c o  m

    setTotals(totals);
    setTotalsNoTaxes(totalsNoTaxes);
    setTotalsTaxes(totals.subtract(totalsNoTaxes));
    setTotalsUnpaid(totalsUnpaid);
}

From source file:org.projectforge.fibu.datev.EmployeeSalaryExportDao.java

/**
 * Exports the filtered list as table with almost all fields.
 *///from   w  w  w. j  a v a  2s.  co m
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public byte[] export(final List<EmployeeSalaryDO> list) {
    log.info("Exporting employee salary list.");
    Validate.notEmpty(list);
    Collections.sort(list, new Comparator<EmployeeSalaryDO>() {
        public int compare(final EmployeeSalaryDO o1, final EmployeeSalaryDO o2) {
            return (o1.getEmployee().getUser().getFullname())
                    .compareTo(o2.getEmployee().getUser().getFullname());
        }
    });
    final EmployeeFilter filter = new EmployeeFilter();
    filter.setShowOnlyActiveEntries(true);
    filter.setDeleted(false);
    final List<EmployeeDO> employees = employeeDao.getList(filter);
    final List<EmployeeDO> missedEmployees = new ArrayList<EmployeeDO>();
    for (final EmployeeDO employee : employees) {
        boolean found = false;
        for (final EmployeeSalaryDO salary : list) {
            if (salary.getEmployeeId().equals(employee.getId()) == true) {
                found = true;
                break;
            }
        }
        if (found == false) {
            missedEmployees.add(employee);
        }
    }
    if (CollectionUtils.isNotEmpty(missedEmployees) == true) {
        Collections.sort(missedEmployees, new Comparator<EmployeeDO>() {
            public int compare(final EmployeeDO o1, final EmployeeDO o2) {
                return (o1.getUser().getFullname()).compareTo(o2.getUser().getFullname());
            }
        });
    }
    final ExportWorkbook xls = new ExportWorkbook();
    final ContentProvider contentProvider = new MyContentProvider(xls);
    // create a default Date format and currency column
    xls.setContentProvider(contentProvider);

    final EmployeeSalaryDO first = list.get(0);
    final int year = first.getYear();
    final int month = first.getMonth();
    final DayHolder buchungsdatum = new DayHolder();
    buchungsdatum.setDate(year, month, 1);
    final MonthHolder monthHolder = new MonthHolder(buchungsdatum.getDate());
    final BigDecimal numberOfWorkingDays = monthHolder.getNumberOfWorkingDays();
    buchungsdatum.setEndOfMonth();

    final String sheetTitle = DateHelper.formatMonth(year, month);
    final ExportSheet sheet = xls.addSheet(sheetTitle);
    sheet.createFreezePane(0, 1);

    final ExportSheet employeeSheet = xls.addSheet(PFUserContext.getLocalizedString("fibu.employee"));
    employeeSheet.setColumnWidth(0, XlsContentProvider.LENGTH_USER * 256);
    employeeSheet.setColumnWidth(1, 14 * 256);
    employeeSheet.setColumnWidth(2, 12 * 256);
    employeeSheet.setColumnWidth(3, 12 * 256);
    employeeSheet.setColumnWidth(4, 12 * 256);
    final ContentProvider provider = employeeSheet.getContentProvider();
    provider.putFormat("STUNDEN", "0.00;[Red]-0.00");
    final ExportRow employeeRow = employeeSheet.addRow();
    employeeRow.addCell(0, PFUserContext.getLocalizedString("fibu.employee"));
    employeeRow.addCell(1, PFUserContext.getLocalizedString("fibu.employee.wochenstunden"));
    employeeRow.addCell(2, PFUserContext.getLocalizedString("fibu.employee.sollstunden"));
    employeeRow.addCell(3, PFUserContext.getLocalizedString("fibu.employee.iststunden"));
    employeeRow.addCell(4, PFUserContext.getLocalizedString("fibu.common.difference"));

    // build all column names, title, widths from fixed and variable columns
    final int numCols = ExcelColumn.values().length;

    final String[] colNames = new String[numCols];
    final String[] colTitles = new String[numCols];
    final int[] colWidths = new int[numCols];

    int idx = 0;
    for (final ExcelColumn col : EnumSet.range(ExcelColumn.START, ExcelColumn.END)) {
        colNames[idx] = col.name();
        colTitles[idx] = PFUserContext.getLocalizedString(col.theTitle);
        colWidths[idx] = col.width;
        ++idx;
    }

    // column property names
    sheet.setPropertyNames(colNames);

    final ContentProvider sheetProvider = sheet.getContentProvider();
    sheetProvider.putFormat("STUNDEN", "0.00");
    sheetProvider.putFormat("BRUTTO_MIT_AG", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KORREKTUR", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("SUMME", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KOST1", "#");
    sheetProvider.putFormat("KOST2", "#");
    sheetProvider.putFormat("KONTO", "#");
    sheetProvider.putFormat("GEGENKONTO", "#");
    sheetProvider.putFormat("DATUM", "dd.MM.yyyy");
    // inform provider of column widths
    for (int ci = 0; ci < colWidths.length; ++ci) {
        sheetProvider.putColWidth(ci, colWidths[ci]);
    }

    final ExportRow headRow = sheet.addRow();
    int i = 0;
    for (final String title : colTitles) {
        headRow.addCell(i++, title);
    }

    for (final EmployeeSalaryDO salary : list) {
        final PropertyMapping mapping = new PropertyMapping();
        final PFUserDO user = userGroupCache.getUser(salary.getEmployee().getUserId());
        Validate.isTrue(year == salary.getYear());
        Validate.isTrue(month == salary.getMonth());
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        final Kost1DO kost1 = salary.getEmployee().getKost1();
        final BigDecimal bruttoMitAGAnteil = salary.getBruttoMitAgAnteil();
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        final Map<String, Kost2Row> rows = report.getKost2Rows();
        BigDecimal sum = BigDecimal.ZERO;
        int j = rows.size();
        for (final Kost2Row row : rows.values()) {
            final Kost2DO kost2 = row.getKost2();
            final MonthlyEmployeeReportEntry entry = report.getKost2Durations().get(kost2.getId());
            mapping.add(ExcelColumn.KOST1, kost1.getNummer());
            mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
            mapping.add(ExcelColumn.KOST2, kost2.getNummer());
            final BigDecimal duration = new BigDecimal(entry.getMillis() / 1000); // Seconds
            // duration = duration.divide(new BigDecimal(60 * 60 * 24), 8, RoundingMode.HALF_UP); // Fraction of day (24 hours)
            // mapping.add(ExcelColumn.STUNDEN, duration);
            mapping.add(ExcelColumn.STUNDEN, duration.divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP));
            mapping.add(ExcelColumn.BEZEICHNUNG, kost2.getToolTip());
            final BigDecimal betrag = CurrencyHelper.multiply(bruttoMitAGAnteil,
                    new BigDecimal(entry.getMillis()).divide(netDuration, 8, RoundingMode.HALF_UP));
            sum = sum.add(betrag);
            if (--j == 0) {
                final BigDecimal korrektur = bruttoMitAGAnteil.subtract(sum);
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag.add(korrektur));
                mapping.add(ExcelColumn.KORREKTUR, korrektur);
                if (NumberHelper.isEqual(sum.add(korrektur), bruttoMitAGAnteil) == true) {
                    mapping.add(ExcelColumn.SUMME, bruttoMitAGAnteil);
                } else {
                    mapping.add(ExcelColumn.SUMME, "*** " + sum + " != " + bruttoMitAGAnteil);
                }
            } else {
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag);
                mapping.add(ExcelColumn.KORREKTUR, "");
                mapping.add(ExcelColumn.SUMME, "");
            }
            mapping.add(ExcelColumn.DATUM, buchungsdatum.getCalendar()); // Last day of month
            mapping.add(ExcelColumn.KONTO, KONTO); // constant.
            mapping.add(ExcelColumn.GEGENKONTO, GEGENKONTO); // constant.
            sheet.addRow(mapping.getMapping(), 0);
        }
        addEmployeeRow(employeeSheet, salary.getEmployee(), numberOfWorkingDays, netDuration);
    }
    for (final EmployeeDO employee : missedEmployees) {
        final PFUserDO user = userGroupCache.getUser(employee.getUserId());
        final PropertyMapping mapping = new PropertyMapping();
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        mapping.add(ExcelColumn.SUMME, "***");
        mapping.add(ExcelColumn.BEZEICHNUNG, "*** FEHLT! ***");
        sheet.addRow(mapping.getMapping(), 0);
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        addEmployeeRow(employeeSheet, employee, numberOfWorkingDays, netDuration);
    }
    // sheet.setZoom(3, 4); // 75%

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        xls.write(baos);
    } catch (final IOException ex) {
        log.fatal("Exception encountered " + ex, ex);
        throw new RuntimeException(ex);
    }
    return baos.toByteArray();
}

From source file:org.egov.wtms.application.service.WaterConnectionDetailsService.java

public BigDecimal getTotalAmount(WaterConnectionDetails waterConnectionDetails) {
    EgDemand currentDemand = waterTaxUtils.getCurrentDemand(waterConnectionDetails).getDemand();
    BigDecimal balance = ZERO;//from  w w  w  .  j  a  v a  2 s  . c om
    if (currentDemand != null) {
        List<Object> instVsAmt = connectionDemandService.getDmdCollAmtInstallmentWise(currentDemand);
        for (Object object : instVsAmt) {
            Object[] ddObject = (Object[]) object;
            BigDecimal dmdAmt = new BigDecimal((Double) ddObject[2]);
            BigDecimal collAmt = ZERO;
            if (ddObject[2] != null)
                collAmt = new BigDecimal((Double) ddObject[3]);
            balance = balance.add(dmdAmt.subtract(collAmt)).setScale(0, HALF_UP);
        }
    }
    return balance;
}

From source file:org.egov.wtms.application.service.WaterConnectionDetailsService.java

public BigDecimal getCurrentDue(WaterConnectionDetails waterConnectionDetails) {
    EgDemand currentDemand = waterTaxUtils.getCurrentDemand(waterConnectionDetails).getDemand();
    BigDecimal balance = ZERO;//from w  w  w .  j  a  va2  s .com
    if (currentDemand != null) {
        List<Object> instVsAmt = connectionDemandService
                .getDmdCollAmtInstallmentWiseUptoCurrentInstallmemt(currentDemand, waterConnectionDetails);
        for (Object object : instVsAmt) {
            Object[] ddObject = (Object[]) object;
            BigDecimal dmdAmt = new BigDecimal((Double) ddObject[2]);
            BigDecimal collAmt = ZERO;
            if (ddObject[2] != null)
                collAmt = new BigDecimal((Double) ddObject[3]);
            balance = balance.add(dmdAmt.subtract(collAmt));
        }
    }
    return balance;
}

From source file:org.egov.wtms.application.service.WaterConnectionDetailsService.java

public BigDecimal getTotalAmountTillCurrentFinYear(WaterConnectionDetails waterConnectionDetails) {
    EgDemand currentDemand = waterTaxUtils.getCurrentDemand(waterConnectionDetails).getDemand();
    BigDecimal balance = ZERO;/*from   w w w .j a v  a 2s . c om*/
    if (currentDemand != null) {
        List<Object> instVsAmt = connectionDemandService
                .getDmdCollAmtInstallmentWiseUptoCurrentFinYear(currentDemand);
        for (Object object : instVsAmt) {
            Object[] ddObject = (Object[]) object;
            BigDecimal dmdAmt = new BigDecimal((Double) ddObject[2]);
            BigDecimal collAmt = ZERO;
            if (ddObject[2] != null)
                collAmt = new BigDecimal((Double) ddObject[3]);
            balance = balance.add(dmdAmt.subtract(collAmt));
        }
    }
    if (balance.signum() < 0)
        balance = ZERO;
    return balance;
}