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.dao.budget.BudgetDetailsHibernateDAO.java

@Deprecated
@Transactional//from  ww w.  j  a v a 2  s  .  c  o  m
private BudgetUsage getBudgetUsageDetails(final Long financialyearid, final Integer moduleid,
        final String referencenumber, final Integer departmentid, final Long functionid,
        final Integer functionaryid, final Integer schemeid, final Integer subschemeid,
        final Integer boundaryid, final List<Long> budgetheadid, final Integer fundid, final double amount,
        final boolean consumeOrRelease, final String appropriationnumber) {
    try {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("financialyearid==" + financialyearid + ",moduleid==" + moduleid + ",referencenumber=="
                    + referencenumber + ",departmentid==" + departmentid + ",functionid==" + functionid
                    + ",functionaryid==" + functionaryid + ",schemeid==" + schemeid + ",subschemeid=="
                    + subschemeid + ",boundaryid==" + boundaryid + ",budgetheadid==" + budgetheadid
                    + ",amount==" + amount);

        validateMandatoryParameters(moduleid, referencenumber);
        BigDecimal amtavailable = getPlanningBudgetAvailable(financialyearid, departmentid, functionid,
                functionaryid, schemeid, subschemeid, boundaryid, budgetheadid, fundid);

        if (consumeOrRelease)
            amtavailable = amtavailable.subtract(BigDecimal.valueOf(amount));
        else
            amtavailable = amtavailable.add(BigDecimal.valueOf(amount));
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("budget available after consuming/releasing=" + amtavailable);
        if (BudgetControlType.BudgetCheckOption.MANDATORY.toString()
                .equals(budgetCheckConfigService.getConfigValue())) {
            if (amtavailable.compareTo(BigDecimal.ZERO) < 0)
                return null;
        }

        // need to update budget details
        final String query = prepareQuery(departmentid, functionid, functionaryid, schemeid, subschemeid,
                boundaryid, fundid);
        final Query q = persistenceService.getSession().createQuery(
                " from BudgetDetail bd where  bd.budget.financialYear.id=:finYearId  and  bd.budget.isbere=:type and bd.budgetGroup.id in (:bgId)"
                        + query);
        if (budgetService.hasApprovedReForYear(financialyearid))
            q.setParameter("type", "RE");
        else
            q.setParameter("type", "BE");
        q.setParameter("finYearId", financialyearid);
        q.setParameterList("bgId", budgetheadid);
        final List<BudgetDetail> bdList = q.list();

        if (bdList == null || bdList.size() == 0) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(
                        "IN consumeEncumbranceBudget()-getDetail() - No budget detail item defined for RE or BE for this combination!!");
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("financial year id - " + financialyearid.toString() + " Budget Group -  "
                        + budgetheadid.toString() + " Query - " + query);
            throw new ValidationException(EMPTY_STRING, "Budgetary Check Failed");
        }
        final BudgetDetail bd = bdList.get(0);
        bd.setBudgetAvailable(amtavailable);
        budgetDetailService.update(bd);

        final BudgetUsage budgetUsage = new BudgetUsage();
        budgetUsage.setFinancialYearId(financialyearid.intValue());
        budgetUsage.setModuleId(moduleid);
        budgetUsage.setReferenceNumber(referencenumber);
        budgetUsage.setBudgetDetail(bd);
        budgetUsage.setAppropriationnumber(appropriationnumber);
        if (consumeOrRelease) {
            budgetUsage.setConsumedAmount(amount);
            budgetUsage.setReleasedAmount(0.0);
        } else {
            budgetUsage.setConsumedAmount(0.0);
            budgetUsage.setReleasedAmount(amount);
        }
        budgetUsage.setCreatedby(ApplicationThreadLocals.getUserId().intValue());
        budgetUsageService.create(budgetUsage);
        return budgetUsage;

    } catch (final ValidationException v) {
        throw v;
    } catch (final Exception e) {
        LOGGER.error("Exception in consumeEncumbranceBudget API()=" + e.getMessage());
        throw new ValidationException(EMPTY_STRING, e.getMessage());
    }
}

From source file:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on an OrderTotalSummary object (products applicable,
 * shipping...), creates and set the shopping cart lines. Returns the amount
 * with tax/*from   w  ww  .ja  v a 2 s.c om*/
 * 
 * @param summary
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public OrderTotalSummary calculateTax(OrderTotalSummary summary, Collection<OrderProduct> products,
        Customer customer, int merchantId, Locale locale, String currency) throws Exception {

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

    Map productsTax = new HashMap();

    //rounding definition
    BigDecimal totalTaxAmount = new BigDecimal(0);
    //totalTaxAmount.setScale(2, BigDecimal.ROUND_DOWN);

    // check if tax is applicable and build a map
    // of tax class - product
    if (products != null) {
        Iterator prodIt = products.iterator();
        while (prodIt.hasNext()) {
            OrderProduct prod = (OrderProduct) prodIt.next();
            if (prod.getTaxClassId() > -1) {

                BigDecimal groupBeforeTaxAmount = (BigDecimal) productsTax.get(prod.getTaxClassId());

                if (groupBeforeTaxAmount == null) {
                    groupBeforeTaxAmount = new BigDecimal("0");
                }

                BigDecimal finalPrice = prod.getFinalPrice();// unit price +
                // attribute
                // * qty
                // finalPrice = finalPrice.multiply(new
                // BigDecimal(prod.getProductQuantity()));

                groupBeforeTaxAmount = groupBeforeTaxAmount.add(finalPrice);

                // getPrices
                Set prices = prod.getPrices();
                // List prices = prod.getRelatedPrices();
                if (prices != null) {
                    Iterator ppriceIter = prices.iterator();
                    while (ppriceIter.hasNext()) {
                        OrderProductPrice pprice = (OrderProductPrice) ppriceIter.next();
                        if (!pprice.isDefaultPrice()) {// related price
                            // activation...
                            // PriceModule module =
                            // (PriceModule)SpringUtil.getBean(pprice.getProductPriceModuleName());
                            // if(module.isTaxApplicable()) {//related price
                            // becomes taxeable
                            // if(pprice.isProductHasTax()) {
                            // groupBeforeTaxAmount =
                            // groupBeforeTaxAmount.add(ProductUtil.determinePrice(pprice));

                            BigDecimal ppPrice = pprice.getProductPriceAmount();
                            ppPrice = ppPrice.multiply(new BigDecimal(prod.getProductQuantity()));

                            groupBeforeTaxAmount = groupBeforeTaxAmount.add(ppPrice);
                            // }
                        }
                    }
                }

                BigDecimal credits = prod.getApplicableCreditOneTimeCharge();
                groupBeforeTaxAmount = groupBeforeTaxAmount.subtract(credits);

                productsTax.put(prod.getTaxClassId(), groupBeforeTaxAmount);

            }
        }
    }

    if (productsTax.size() == 0) {
        return summary;
    }

    // determine if tax applies on billing or shipping address

    // get shipping & tax informations
    ConfigurationRequest request = new ConfigurationRequest(merchantId);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    // tax on shipping
    if (summary.getShippingTotal() != null && summary.getShippingTotal().floatValue() > 0) {
        MerchantConfiguration shippingTaxConf = response
                .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_TAX_CLASS);
        if (shippingTaxConf != null && !StringUtils.isBlank(shippingTaxConf.getConfigurationValue())) {// tax on shipping

            long taxClass = Long.parseLong(shippingTaxConf.getConfigurationValue());
            BigDecimal groupSubTotal = (BigDecimal) productsTax.get(taxClass);
            if (groupSubTotal == null) {
                groupSubTotal = new BigDecimal("0");
                productsTax.put(taxClass, groupSubTotal);
            }
            groupSubTotal = groupSubTotal.add(summary.getShippingTotal());
            productsTax.put(taxClass, groupSubTotal);
        }
    }

    Map taxDescriptionsHolder = new TreeMap();

    Iterator taxMapIter = productsTax.keySet().iterator();
    while (taxMapIter.hasNext()) {// get each tax class

        long key = (Long) taxMapIter.next();
        // List taxClassGroup = (List)productsTax.get(key);

        int countryId = 0;

        Collection taxCollection = null;
        if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {

            if (store.getCountry() != customer.getCustomerCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                    customer.getCustomerZoneId(), key, merchantId);
            countryId = customer.getCustomerCountryId();
        } else { // BILLING

            if (store.getCountry() != customer.getCustomerBillingCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                    customer.getCustomerBillingZoneId(), key, merchantId);
            countryId = customer.getCustomerBillingCountryId();
        }

        if (taxCollection == null || taxCollection.size() == 0) {// no tax
            continue;
        }

        Map countries = RefCache.getCountriesMap();
        Country c = (Country) countries.get(countryId);

        if (c != null) {// tax adjustment rules
            TaxModule module = (TaxModule) SpringUtil.getBean(c.getCountryIsoCode2());
            if (module != null) {
                taxCollection = module.adjustTaxRate(taxCollection, store);
            }
        }

        //BigDecimal beforeTaxAmount = new BigDecimal("0");
        //beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal groupSubTotal = (BigDecimal) productsTax.get(key);

        //beforeTaxAmount = beforeTaxAmount.add(groupSubTotal);
        BigDecimal beforeTaxAmount = groupSubTotal;
        beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // iterate through tax collection and calculate tax lines
        if (taxCollection != null) {

            Iterator i = taxCollection.iterator();
            while (i.hasNext()) {

                TaxRate trv = (TaxRate) i.next();
                // double value = ((trv.getTaxRate().doubleValue() *
                // beforeTaxAmount.doubleValue())/100)+beforeTaxAmount.doubleValue();
                double trDouble = trv.getTaxRate().doubleValue();

                // if piggy back, add tax to subtotal
                BigDecimal amount = beforeTaxAmount;
                if (trv.isPiggyback()) {
                    // add previous calculated tax on top of subtotal
                    amount = amount.add(totalTaxAmount);
                }

                // commented for piggyback
                // double beforeTaxDouble = beforeTaxAmount.doubleValue();
                double beforeTaxDouble = amount.doubleValue();

                double value = ((trDouble * beforeTaxDouble) / 100);

                BigDecimal nValue = BigDecimal.valueOf(value);

                //BigDecimal nValue = new BigDecimal(value);
                nValue.setScale(2, BigDecimal.ROUND_HALF_UP);

                //nValue = nValue.add(new BigDecimal(value));

                // commented for piggyback
                // beforeTaxAmount = beforeTaxAmount.add(nValue);

                //BigDecimal bdValue = nValue;
                String am = CurrencyUtil.getAmount(nValue, store.getCurrency());

                /** this one **/
                totalTaxAmount = totalTaxAmount.add(new BigDecimal(am));

                String name = LabelUtil.getInstance().getText(locale, "label.generic.tax");

                OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder
                        .get(trv.getZoneToGeoZone().getGeoZoneId());

                if (line == null) {
                    // tax description
                    line = new OrderTotalLine();
                    Set descriptionsSet = trv.getDescriptions();
                    if (descriptionsSet != null) {
                        Iterator li = descriptionsSet.iterator();
                        while (li.hasNext()) {
                            TaxRateDescription description = (TaxRateDescription) li.next();
                            if (description.getId().getLanguageId() == LanguageUtil
                                    .getLanguageNumberCode(locale.getLanguage())) {
                                name = description.getTaxDescription();
                                break;
                            }
                        }
                    }

                    line.setText(name);
                    line.setCost(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(nValue, currency));
                    taxDescriptionsHolder.put(trv.getZoneToGeoZone().getGeoZoneId(), line);
                } else {// needs to re-use the same shopping cart line
                    BigDecimal cost = line.getCost();
                    cost = cost.add(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(cost, currency));
                }

                // now set tax on producs
                Iterator prodIt = products.iterator();
                while (prodIt.hasNext()) {
                    OrderProduct prod = (OrderProduct) prodIt.next();
                    if (prod.getTaxClassId() == key) {
                        // calculate tax for this product
                        BigDecimal price = prod.getProductPrice();
                        BigDecimal productTax = prod.getProductTax();
                        if (productTax == null) {
                            productTax = new BigDecimal("0");
                        }
                        price = price.add(productTax);
                        double pTax = ((trDouble * price.doubleValue()) / 100);

                        prod.setProductTax(new BigDecimal(pTax));

                    }
                }

            } // end while

        }

        Iterator titer = taxDescriptionsHolder.keySet().iterator();
        while (titer.hasNext()) {
            long lineKey = (Long) titer.next();
            OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder.get(lineKey);
            summary.addTaxPrice(line);
        }

    }

    summary.setTaxTotal(totalTaxAmount);

    return summary;

}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

private BigDecimal getDetails(final Map<String, Object> detailsMap) {
    Long financialyearid = null;/*from  w  ww. jav a  2  s . co  m*/
    Integer moduleid = null;
    String referencenumber = null;
    Integer departmentid = null;
    Long functionid = null;
    Integer functionaryid = null;
    Integer schemeid = null;
    Integer subschemeid = null;
    Integer boundaryid = null;
    List<Long> budgetheadid = null;
    Integer fundid = null;
    double amount = 0.0d;
    String appropriationnumber = null;
    Boolean consumeOrRelease = null;

    if (detailsMap.containsKey(Constants.FINANCIALYEARID))
        financialyearid = (Long) detailsMap.get(Constants.FINANCIALYEARID);
    if (detailsMap.containsKey(Constants.MODULEID))
        moduleid = (Integer) detailsMap.get(Constants.MODULEID);
    if (detailsMap.containsKey(Constants.REFERENCENUMBER))
        referencenumber = (String) detailsMap.get(Constants.REFERENCENUMBER);
    if (detailsMap.containsKey(Constants.DEPARTMENTID))
        departmentid = (Integer) detailsMap.get(Constants.DEPARTMENTID);
    if (detailsMap.containsKey(Constants.FUNCTIONID))
        functionid = (Long) detailsMap.get(Constants.FUNCTIONID);
    if (detailsMap.containsKey(Constants.FUNCTIONARYID))
        functionaryid = (Integer) detailsMap.get(Constants.FUNCTIONARYID);
    if (detailsMap.containsKey(Constants.SCHEMEID))
        schemeid = (Integer) detailsMap.get(Constants.SCHEMEID);
    if (detailsMap.containsKey(Constants.SUBSCHEMEID))
        subschemeid = (Integer) detailsMap.get(Constants.SUBSCHEMEID);
    if (detailsMap.containsKey(Constants.BOUNDARYID))
        boundaryid = (Integer) detailsMap.get(Constants.BOUNDARYID);
    if (detailsMap.containsKey(Constants.BUDGETHEAD))
        budgetheadid = (List<Long>) detailsMap.get(Constants.BUDGETHEAD);
    if (detailsMap.containsKey(Constants.FUNDID))
        fundid = (Integer) detailsMap.get(Constants.FUNDID);
    if (detailsMap.containsKey(Constants.AMOUNT))
        amount = (Double) detailsMap.get(Constants.AMOUNT);
    if (detailsMap.containsKey(Constants.APPROPRIATIONNUMBER))
        appropriationnumber = (String) detailsMap.get(Constants.APPROPRIATIONNUMBER);
    if (detailsMap.containsKey(Constants.CONSUMEORRELEASE))
        consumeOrRelease = (Boolean) detailsMap.get(Constants.CONSUMEORRELEASE);

    try {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("financialyearid==" + financialyearid + ",moduleid==" + moduleid + ",referencenumber=="
                    + referencenumber + ",departmentid==" + departmentid + ",functionid==" + functionid
                    + ",functionaryid==" + functionaryid + ",schemeid==" + schemeid + ",subschemeid=="
                    + subschemeid + ",boundaryid==" + boundaryid + ",budgetheadid==" + budgetheadid
                    + ",amount==" + amount);

        validateMandatoryParameters(moduleid, referencenumber);
        BigDecimal amtavailable = getPlanningBudgetAvailable(financialyearid, departmentid, functionid,
                functionaryid, schemeid, subschemeid, boundaryid, budgetheadid, fundid);

        if (consumeOrRelease)
            amtavailable = amtavailable.subtract(BigDecimal.valueOf(amount));
        else
            amtavailable = amtavailable.add(BigDecimal.valueOf(amount));
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("budget available after consuming/releasing=" + amtavailable);

        if (amtavailable != null && amtavailable.compareTo(BigDecimal.ZERO) >= 0) {
            // need to update budget details
            final String query = prepareQuery(departmentid, functionid, functionaryid, schemeid, subschemeid,
                    boundaryid, fundid);
            final Query q = getCurrentSession().createQuery(
                    " from BudgetDetail bd where  bd.budget.financialYear.id=:finYearId and bd.budget.isbere=:type and bd.budgetGroup.id in (:bgId)"
                            + query);
            if (budgetService.hasApprovedReForYear(financialyearid))
                q.setParameter("type", "RE");
            else
                q.setParameter("type", "BE");
            q.setParameter("finYearId", financialyearid);
            q.setParameterList("bgId", budgetheadid);
            final List<BudgetDetail> bdList = q.list();
            if (bdList == null || bdList.size() == 0) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(
                            "IN consumeEncumbranceBudget()-getDetail() - No budget detail item defined for RE or BE for this combination!!");
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("financial year id - " + financialyearid.toString() + " Budget Group -  "
                            + budgetheadid.toString() + " Query - " + query);
                throw new ValidationException(EMPTY_STRING, "Budgetary Check Failed");
            }
            final BudgetDetail bd = bdList.get(0);
            bd.setBudgetAvailable(amtavailable);
            update(bd);

            final BudgetUsage budgetUsage = new BudgetUsage();
            budgetUsage.setFinancialYearId(financialyearid.intValue());
            budgetUsage.setModuleId(moduleid);
            budgetUsage.setReferenceNumber(referencenumber);
            budgetUsage.setBudgetDetail(bd);
            budgetUsage.setAppropriationnumber(appropriationnumber);
            if (consumeOrRelease) {
                budgetUsage.setConsumedAmount(amount);
                budgetUsage.setReleasedAmount(0.0);
            } else {
                budgetUsage.setConsumedAmount(0.0);
                budgetUsage.setReleasedAmount(amount);
            }
            budgetUsage.setCreatedby(ApplicationThreadLocals.getUserId().intValue());
            budgetUsageService.create(budgetUsage);
            return BigDecimal.ONE;
        } else
            return BigDecimal.ZERO;
    } catch (final ValidationException v) {
        LOGGER.error("Exp in consumeEncumbranceBudget API()===" + v.getErrors());
        throw new ValidationException(v.getErrors());
    } catch (final Exception e) {
        LOGGER.error("Exception in consumeEncumbranceBudget API()=" + e.getMessage());
        throw new ValidationException(EMPTY_STRING, e.getMessage());
    }
}

From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java

public String createAccDefExpenseFact(Fact fact, DocLine_Invoice line, Account prodExpAccount,
        Account prodDefExpAccount, String lineAmount, String strCurrencyId, ConnectionProvider conn) {
    BigDecimal amount = new BigDecimal(lineAmount);
    String Fact_Acct_Group_ID = SequenceIdData.getUUID();
    ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>();
    Period startingPeriod = OBDal.getInstance().get(Period.class, line.getStartingPeriodId());
    plan = calculateAccDefPlan(startingPeriod, line.getPeriodNumber(), amount, strCurrencyId);
    for (HashMap<String, String> planLine : plan) {
        DocLine planDocLine = new DocLine(DocumentType, Record_ID, line.m_TrxLine_ID);
        planDocLine.copyInfo(line);// w  w  w .  j  a  v a2  s  .c  o  m
        planDocLine.m_DateAcct = planLine.get("date");
        if (IsReversal.equals("Y")) {
            // Expense Account
            fact.createLine(planDocLine, prodExpAccount, strCurrencyId, "", planLine.get("amount"),
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            // Deferred Expense Account
            fact.createLine(planDocLine, prodDefExpAccount, strCurrencyId, planLine.get("amount"), "",
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        } else {
            // Deferred Expense Account
            fact.createLine(planDocLine, prodDefExpAccount, strCurrencyId, "", planLine.get("amount"),
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            // Expense Account
            fact.createLine(planDocLine, prodExpAccount, strCurrencyId, planLine.get("amount"), "",
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        }
        amount = amount.subtract(new BigDecimal(planLine.get("amount")));
        Fact_Acct_Group_ID = SequenceIdData.getUUID();
    }
    return amount.toString();
}

From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java

String createAccDefRevenueFact(Fact fact, DocLine_Invoice line, Account prodRevAccount,
        Account prodDefRevAccount, String lineAmount, String strCurrencyId, ConnectionProvider conn) {
    BigDecimal amount = new BigDecimal(lineAmount);
    String Fact_Acct_Group_ID = SequenceIdData.getUUID();
    ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>();
    Period startingPeriod = OBDal.getInstance().get(Period.class, line.getStartingPeriodId());
    plan = calculateAccDefPlan(startingPeriod, line.getPeriodNumber(), amount, strCurrencyId);
    for (HashMap<String, String> planLine : plan) {
        DocLine planDocLine = new DocLine(DocumentType, Record_ID, line.m_TrxLine_ID);
        planDocLine.copyInfo(line);/*from  w w  w.ja va 2s.co  m*/
        planDocLine.m_DateAcct = planLine.get("date");
        if (IsReversal.equals("Y")) {
            // Revenue Account
            fact.createLine(planDocLine, prodRevAccount, strCurrencyId, planLine.get("amount"), "",
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            // Deferred Revenue Account
            fact.createLine(planDocLine, prodDefRevAccount, strCurrencyId, "", planLine.get("amount"),
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        } else {
            // Deferred Revenue Account
            fact.createLine(planDocLine, prodDefRevAccount, strCurrencyId, planLine.get("amount"), "",
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            // Revenue Account
            fact.createLine(planDocLine, prodRevAccount, strCurrencyId, "", planLine.get("amount"),
                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        }
        amount = amount.subtract(new BigDecimal(planLine.get("amount")));
        Fact_Acct_Group_ID = SequenceIdData.getUUID();
    }

    return amount.toString();
}

From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java

public List<WaterChargeDashBoardResponse> getResponseTableDataForBillCollector(
        final WaterChargeDashBoardRequest collectionDetailsRequest) {

    final Map<String, WaterChargeDashBoardResponse> wardReceiptDetails = new HashMap<>();
    final Map<String, List<WaterChargeDashBoardResponse>> billCollectorWiseMap = new LinkedHashMap<>();

    final List<WaterChargeDashBoardResponse> billCollectorWiseTableData = new ArrayList<>();

    for (final WaterChargeDashBoardResponse tableData : getResponseTableData(collectionDetailsRequest))
        wardReceiptDetails.put(tableData.getWardName(), tableData);

    final List<BillCollectorIndex> billCollectorsList = getBillCollectorDetails(collectionDetailsRequest);

    for (final BillCollectorIndex billCollIndex : billCollectorsList) {
        final List<WaterChargeDashBoardResponse> collDetails = new ArrayList<>();
        if (wardReceiptDetails.get(billCollIndex.getRevenueWard()) != null
                && StringUtils.isNotBlank(billCollIndex.getRevenueWard()))
            if (billCollectorWiseMap.isEmpty() || !billCollectorWiseMap.isEmpty()
                    && !billCollectorWiseMap.containsKey(billCollIndex.getBillCollector())) {
                collDetails.add(wardReceiptDetails.get(billCollIndex.getRevenueWard()));
                billCollectorWiseMap.put(billCollIndex.getBillCollector(), collDetails);
            } else
                billCollectorWiseMap.get(billCollIndex.getBillCollector())
                        .add(wardReceiptDetails.get(billCollIndex.getRevenueWard()));
    }/*from   w  w  w. j  a v  a  2  s .  c  om*/
    for (final Entry<String, List<WaterChargeDashBoardResponse>> entry : billCollectorWiseMap.entrySet()) {
        final WaterChargeDashBoardResponse collTableData = new WaterChargeDashBoardResponse();
        BigDecimal currDayColl = BigDecimal.ZERO;
        BigDecimal cytdColl = BigDecimal.ZERO;
        BigDecimal lytdColl = BigDecimal.ZERO;
        BigDecimal cytdDmd = BigDecimal.ZERO;
        BigDecimal performance = BigDecimal.ZERO;
        BigDecimal totalDmd = BigDecimal.ZERO;
        BigDecimal variance = BigDecimal.ZERO;

        for (final WaterChargeDashBoardResponse tableData : entry.getValue()) {
            currDayColl = currDayColl
                    .add(tableData.getTodayColl() == null ? BigDecimal.ZERO : tableData.getTodayColl());
            cytdColl = cytdColl.add(tableData.getCurrentYearTillDateColl() == null ? BigDecimal.ZERO
                    : tableData.getCurrentYearTillDateColl());
            cytdDmd = cytdDmd.add(tableData.getCurrentYearTillDateDmd() == null ? BigDecimal.ZERO
                    : tableData.getCurrentYearTillDateDmd());
            totalDmd = totalDmd
                    .add(tableData.getTotalDmd() == null ? BigDecimal.ZERO : tableData.getTotalDmd());
            lytdColl = lytdColl.add(tableData.getLastYearTillDateColl() == null ? BigDecimal.ZERO
                    : tableData.getLastYearTillDateColl());
        }
        collTableData.setBillCollector(entry.getKey());
        collTableData.setTodayColl(currDayColl);
        collTableData.setCurrentYearTillDateColl(cytdColl);
        collTableData.setCurrentYearTillDateDmd(cytdDmd);
        collTableData.setCurrentYearTillDateBalDmd(cytdDmd.subtract(cytdColl));
        collTableData.setTotalDmd(totalDmd);
        collTableData.setLastYearTillDateColl(lytdColl);
        if (cytdDmd != BigDecimal.valueOf(0)) {
            performance = collTableData.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100)
                    .divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP);
            collTableData.setPerformance(performance);
        }
        if (collTableData.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0)
            variance = WaterTaxConstants.BIGDECIMAL_100;
        else
            variance = collTableData.getCurrentYearTillDateColl()
                    .subtract(collTableData.getLastYearTillDateColl())
                    .multiply(WaterTaxConstants.BIGDECIMAL_100)
                    .divide(collTableData.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP);
        collTableData.setLastYearVar(variance);
        billCollectorWiseTableData.add(collTableData);
    }
    return billCollectorWiseTableData;

}

From source file:org.egov.works.web.actions.reports.WorkProgressRegisterAction.java

public Map<String, Object> getPaymentDetail(final Set<MBHeader> mbHeaders) {
    BigDecimal totalBillAmount = BigDecimal.ZERO;
    BigDecimal totalReleasedAmt = BigDecimal.ZERO;
    BigDecimal totalOutstandingAmt = BigDecimal.ZERO;
    BigDecimal totalNetPayableAmt = BigDecimal.ZERO;
    final HashMap<String, Object> result = new HashMap<String, Object>();
    final List<PaymentDetail> paymentDetailList = new LinkedList<PaymentDetail>();
    for (final MBHeader mbHeader : mbHeaders) {
        final PaymentDetail paymentDetail = new PaymentDetail();
        final EgBillregister egBillRegister = mbHeader.getEgBillregister();
        BigDecimal netPayableAmt = BigDecimal.ZERO;

        if (egBillRegister != null)
            if (egBillRegister.getStatus() != null
                    && egBillRegister.getStatus().getCode().equalsIgnoreCase("APPROVED")) {
                paymentDetail.setBillAmount(egBillRegister.getBillamount());
                paymentDetail.setBillDate(DateUtils.getFormattedDate(egBillRegister.getBilldate(), dateFormat));
                paymentDetail.setBillNumber(egBillRegister.getBillnumber());
                paymentDetail.setBillType(egBillRegister.getBilltype());
                if (egBillRegister.getEgBillregistermis().getVoucherHeader() != null
                        && egBillRegister.getEgBillregistermis().getVoucherHeader().getVoucherNumber() != null
                        && !egBillRegister.getEgBillregistermis().getVoucherHeader().getVoucherNumber()
                                .equals("")
                        && egBillRegister.getEgBillregistermis().getVoucherHeader().getStatus() != null
                        && egBillRegister.getEgBillregistermis().getVoucherHeader().getStatus() == 0) {

                    paymentDetail.setCjvNo(
                            egBillRegister.getEgBillregistermis().getVoucherHeader().getVoucherNumber());
                    logger.debug("Bill Number : " + egBillRegister.getBillnumber() + " --- CJVNo : "
                            + egBillRegister.getEgBillregistermis().getVoucherHeader().getVoucherNumber());
                }/*from  w ww .ja  v  a 2 s . c o m*/
                try {
                    paymentDetail.setReleasedAmount(egovCommon.getPaymentAmount(egBillRegister.getId()));
                    netPayableAmt = contractorBillService
                            .getNetPayableAmountForGlCodeId(egBillRegister.getId());
                } catch (final ApplicationException egovExp) {
                    logger.error("Error: Getting payment for a contractor bill", egovExp);
                    paymentDetail.setReleasedAmount(BigDecimal.ZERO);
                }

                paymentDetail.setOutstandingAmount(netPayableAmt.subtract(paymentDetail.getReleasedAmount()));
                totalNetPayableAmt = totalNetPayableAmt.add(netPayableAmt);
                totalBillAmount = totalBillAmount.add(paymentDetail.getBillAmount());
                totalReleasedAmt = totalReleasedAmt.add(paymentDetail.getReleasedAmount());
                if (egBillRegister.getBilltype()
                        .equalsIgnoreCase((String) contractorBillService.getBillType().get(1))
                        && egBillRegister.getEgBillregistermis().getVoucherHeader() != null
                        && egBillRegister.getEgBillregistermis().getVoucherHeader().getVoucherNumber() != null
                        && !egBillRegister.getEgBillregistermis().getVoucherHeader().getVoucherNumber()
                                .equals("")
                        && egBillRegister.getEgBillregistermis().getVoucherHeader().getStatus() != null
                        && egBillRegister.getEgBillregistermis().getVoucherHeader().getStatus() == 0)
                    result.put("isFinalBillCreated", Boolean.TRUE);
                else
                    result.put("isFinalBillCreated", Boolean.FALSE);
                paymentDetailList.add(paymentDetail);
            }
    }

    totalOutstandingAmt = totalNetPayableAmt.subtract(totalReleasedAmt);
    result.put("paymentDetails", paymentDetailList);
    result.put("totalBillAmt", totalBillAmount);
    result.put("totalReleasedAmt", totalReleasedAmt);
    result.put("totalOutstandingAmt", totalOutstandingAmt);

    return result;
}

From source file:com.turborep.turbotracker.sales.service.Salesserviceimpl.java

@Override
public Prmaster getInventoryAllocatedDetailsservice(int cuSOid, int prmasterid) {
    Session aSession = null;/*from w w w . j  a  v  a2  s. c  o m*/
    Integer sPrWarehouseID = 0;
    BigDecimal inventoryAllocated = new BigDecimal(0);
    BigDecimal inventory1 = new BigDecimal(0);
    BigDecimal inventory2 = new BigDecimal(0);
    String sQuery, sQuery1 = null;
    Prmaster objprmaster = new Prmaster();
    try {
        aSession = itsSessionFactory.openSession();
        sQuery = "SELECT prFromWarehouseID FROM cuSO cuso WHERE cuSOID = " + cuSOid;
        Query query = aSession.createSQLQuery(sQuery);
        if (query.list().size() > 0)
            sPrWarehouseID = (Integer) query.list().get(0);

        sQuery1 = "SELECT inventory.InventoryAllocated,inventory.InventoryOnHand,inventory.prWarehouseInventoryID,prMaster.IsInventory FROM prWarehouseInventory inventory left join prMaster on(prMaster.prMasterID=inventory.prMasterID) WHERE inventory.prMasterID = "
                + prmasterid + " AND prWarehouseID = " + sPrWarehouseID;
        query = aSession.createSQLQuery(sQuery1);
        if (query.list().size() > 0) {
            Object[] object = (Object[]) query.list().get(0);
            inventory1 = (BigDecimal) object[0];

            inventory2 = (BigDecimal) object[1];

            inventoryAllocated = (inventory2 == null
                    ? new BigDecimal("0.0000")
                            .subtract(inventory1 == null ? new BigDecimal("0.0000") : inventory1)
                    : inventory2.subtract(inventory1 == null ? new BigDecimal("0.0000") : inventory1));
            objprmaster.setInventoryAllocated(inventoryAllocated);
            objprmaster.setIsInventory((Byte) object[3]);
            System.out.println("-=================================================>" + inventoryAllocated);
        }
    } catch (Exception e) {
        itsLogger.error(e.getMessage(), e);
    } finally {
        aSession.flush();
        aSession.close();
        sQuery1 = null;
        sQuery = null;
    }
    return objprmaster;
}

From source file:org.egov.collection.web.actions.receipts.ReceiptAction.java

/**
 * This method is invoked when user creates a receipt.
 *
 * @return/*from   w  ww. j  a v a 2  s  .  c o  m*/
 */
@ValidationErrorPage(value = "new")
@Action(value = "/receipts/receipt-save")
public String save() {
    String returnValue;
    if (instrumentTypeCashOrCard != null
            && instrumentTypeCashOrCard.equals(CollectionConstants.INSTRUMENTTYPE_ONLINE)) {
        if (callbackForApportioning && !overrideAccountHeads)
            apportionBillAmount();
        ServiceDetails paymentService;
        paymentService = (ServiceDetails) getPersistenceService().findByNamedQuery(
                CollectionConstants.QUERY_SERVICE_BY_CODE, CollectionConstants.SERVICECODE_SBIMOPS);
        if (null != paymentService)
            setPaymentRequest(collectionService.populateAndPersistReceipts(paymentService, receiptHeader,
                    receiptDetailList, instrHeaderOnline.getInstrumentAmount(),
                    CollectionConstants.COLLECTION_TYPE_COUNTER));
        return REDIRECT;
    } else {
        List<InstrumentHeader> receiptInstrList = new ArrayList<>(0);
        LOGGER.info("Receipt creation process is started !!!!!!");
        ReceiptHeader rhForValidation = null;
        final long startTimeMillis = System.currentTimeMillis();
        if (manualReceiptNumber != null && manualReceiptDate != null) {
            final CFinancialYear financialYear = collectionsUtil.getFinancialYearforDate(manualReceiptDate);
            rhForValidation = receiptHeaderService.findByNamedQuery(
                    CollectionConstants.QUERY_RECEIPT_BY_SERVICE_MANUALRECEIPTNO_AND_DATE, manualReceiptNumber,
                    receiptHeader.getService().getCode(), financialYear.getStartingDate(),
                    financialYear.getEndingDate(), CollectionConstants.RECEIPT_STATUS_CODE_CANCELLED);
        }

        if (rhForValidation == null) {
            // For interday cancellation
            if (oldReceiptId != null) {
                final ReceiptHeader receiptHeaderToBeCancelled = receiptHeaderService.findById(oldReceiptId,
                        false);

                receiptHeaderToBeCancelled.setStatus(
                        statusDAO.getStatusByModuleAndCode(CollectionConstants.MODULE_NAME_RECEIPTHEADER,
                                CollectionConstants.RECEIPT_STATUS_CODE_CANCELLED));
                receiptHeaderToBeCancelled.setReasonForCancellation(reasonForCancellation);
                // set isReconciled to false before calling update to
                // billing system for
                // cancel receipt
                receiptHeaderToBeCancelled.setIsReconciled(false);
                receiptHeader.setLocation(receiptHeaderToBeCancelled.getLocation());
                receiptHeaderService.persist(receiptHeaderToBeCancelled);
                if (receiptHeaderToBeCancelled.getReceipttype() == CollectionConstants.RECEIPT_TYPE_BILL) {
                    populateReceiptModelWithExistingReceiptInfo(receiptHeaderToBeCancelled);
                    LOGGER.info("Receipt Cancelled with Receipt Number(recreateNewReceiptOnCancellation): "
                            + receiptHeaderToBeCancelled.getReceiptnumber() + "; Consumer Code: "
                            + receiptHeaderToBeCancelled.getConsumerCode());
                }
            }

            if ("misc".equalsIgnoreCase(billSource)) {
                createMisc();
                if (!setMiscReceiptDetails())
                    returnValue = NEW;
            } else {
                if (callbackForApportioning && !overrideAccountHeads)
                    apportionBillAmount();
                if (receiptDetailList == null || receiptDetailList.isEmpty())
                    throw new ApplicationRuntimeException(
                            "Receipt could not be created as the apportioned receipt detail list is empty");
                else {
                    BigDecimal totalCreditAmount = BigDecimal.ZERO;
                    for (final ReceiptDetail receiptDetail : receiptDetailList)
                        totalCreditAmount = totalCreditAmount.add(receiptDetail.getCramount());
                    if (totalCreditAmount.intValue() == 0)
                        throw new ApplicationRuntimeException("Apportioning Failed at the Billing System: "
                                + receiptHeader.getService().getCode() + ", for bill number: "
                                + receiptHeader.getReferencenumber());
                    else
                        receiptHeader.setReceiptDetails(new HashSet(receiptDetailList));
                }
            }
            int noOfNewlyCreatedReceipts = 0;
            boolean setInstrument = true;

            // only newly created receipts need to be initialised with the
            // data.
            // The cancelled receipt can be excluded from this processing.
            if (receiptHeader.getStatus() == null) {
                noOfNewlyCreatedReceipts++;
                // Set created by Date as this required to generate receipt
                // number before persist
                if (manualReceiptDate == null)
                    receiptHeader.setReceiptdate(new Date());
                else {
                    // If the receipt has been manually created, the receipt
                    // date is same as the date of manual creation.
                    // set Createdby, in MySavelistner if createdBy is null
                    // it set both createdBy and createdDate with
                    // currentDate.
                    // Thus overridding the manualReceiptDate set above
                    // receiptHeader.setCreatedBy(collectionsUtil.getLoggedInUser());
                    receiptHeader.setManualreceiptdate(manualReceiptDate);
                    receiptHeader.setReceiptdate(manualReceiptDate);
                    receiptHeader.setVoucherDate(manualReceiptDate);
                }
                if (StringUtils.isNotBlank(manualReceiptNumber))
                    receiptHeader.setManualreceiptnumber(manualReceiptNumber);
                if (isBillSourcemisc()) {
                    receiptHeader.setReceipttype(CollectionConstants.RECEIPT_TYPE_ADHOC);
                    receiptHeader.setVoucherDate(voucherDate);
                    receiptHeader.setReceiptdate(voucherDate);
                    receiptHeader.setVoucherNum(voucherNum);
                    receiptHeader.setIsReconciled(Boolean.TRUE);
                    receiptHeader.setManualreceiptdate(manualReceiptDate);
                    receiptHeader.setPayeeName(StringEscapeUtils.unescapeHtml(paidBy));

                } else {
                    receiptHeader.setReceipttype(CollectionConstants.RECEIPT_TYPE_BILL);
                    receiptHeader.setIsModifiable(Boolean.TRUE);
                    receiptHeader.setIsReconciled(Boolean.FALSE);
                }
                // serviceType =
                // receiptHeader.getService().getServiceType();
                receiptHeader.setCollectiontype(CollectionConstants.COLLECTION_TYPE_COUNTER);
                // Bank Collection Operator location is not captured.
                if (!collectionsUtil.isBankCollectionOperator(receiptCreatedByCounterOperator)
                        && receiptHeader.getLocation() == null)
                    receiptHeader.setLocation(collectionsUtil.getLocationOfUser(getSession()));
                receiptHeader.setStatus(
                        collectionsUtil.getStatusForModuleAndCode(CollectionConstants.MODULE_NAME_RECEIPTHEADER,
                                CollectionConstants.RECEIPT_STATUS_CODE_TO_BE_SUBMITTED));
                receiptHeader.setPaidBy(StringEscapeUtils.unescapeHtml(paidBy));
                receiptHeader.setSource(Source.SYSTEM.toString());

                // If this is a new receipt in lieu of cancelling old
                // receipt, update
                // old receipt id to the reference collection header id
                // field of this new receipt.
                if (getOldReceiptId() != null)
                    receiptHeader.setReceiptHeader(receiptHeaderService.findById(getOldReceiptId(), false));
                if (setInstrument) {
                    receiptInstrList = populateInstrumentDetails();
                    setInstrument = false;
                }

                receiptHeader.setReceiptInstrument(new HashSet(receiptInstrList));

                BigDecimal debitAmount = BigDecimal.ZERO;

                for (final ReceiptDetail creditChangeReceiptDetail : receiptDetailList)
                    for (final ReceiptDetail receiptDetail : receiptHeader.getReceiptDetails())
                        if (creditChangeReceiptDetail.getReceiptHeader().getReferencenumber()
                                .equals(receiptDetail.getReceiptHeader().getReferencenumber())
                                && receiptDetail.getOrdernumber()
                                        .equals(creditChangeReceiptDetail.getOrdernumber())) {

                            receiptDetail.setCramount(creditChangeReceiptDetail.getCramount());
                            receiptDetail.setDramount(creditChangeReceiptDetail.getDramount());
                            // calculate sum of creditamounts as a debit
                            // value to create a
                            // debit account head and add to receipt details
                            debitAmount = debitAmount.add(creditChangeReceiptDetail.getCramount());
                            debitAmount = debitAmount.subtract(creditChangeReceiptDetail.getDramount());
                        }

                if (chequeInstrumenttotal != null && chequeInstrumenttotal.compareTo(BigDecimal.ZERO) != 0)
                    receiptHeader.setTotalAmount(chequeInstrumenttotal);

                if (cashOrCardInstrumenttotal != null
                        && cashOrCardInstrumenttotal.compareTo(BigDecimal.ZERO) != 0)
                    receiptHeader.setTotalAmount(cashOrCardInstrumenttotal);
                DebitAccountHeadDetailsService debitAccountHeadService = (DebitAccountHeadDetailsService) beanProvider
                        .getBean(collectionsUtil.getBeanNameForDebitAccountHead());
                if (isBillSourcemisc())
                    receiptHeader.addReceiptDetail(debitAccountHeadService.addDebitAccountHeadDetails(
                            totalDebitAmount, receiptHeader, chequeInstrumenttotal, cashOrCardInstrumenttotal,
                            instrumentTypeCashOrCard));
                else
                    receiptHeader.addReceiptDetail(debitAccountHeadService.addDebitAccountHeadDetails(
                            debitAmount, receiptHeader, chequeInstrumenttotal, cashOrCardInstrumenttotal,
                            instrumentTypeCashOrCard));

            }
            // }// end of looping through receipt headers
            // }// end of looping through model receipt payee list

            LOGGER.info("Call back for apportioning is completed");
            // billing system
            receiptHeaderService.populateAndPersistReceipts(receiptHeader, receiptInstrList);

            // populate all receipt header ids except the cancelled receipt
            // (in effect the newly created receipts)
            selectedReceipts = new Long[noOfNewlyCreatedReceipts];
            int i = 0;
            if (!receiptHeader.getId().equals(oldReceiptId)) {
                selectedReceipts[i] = receiptHeader.getId();
                i++;
            }

            final long elapsedTimeMillis = System.currentTimeMillis() - startTimeMillis;
            LOGGER.info("$$$$$$ Receipt Persisted with Receipt Number: " + receiptHeader.getReceiptnumber()
                    + (receiptHeader.getConsumerCode() != null
                            ? " and consumer code: " + receiptHeader.getConsumerCode()
                            : "")
                    + "; Time taken(ms) = " + elapsedTimeMillis);
            // Do not invoke print receipt in case of bulk upload.
            if (!receiptBulkUpload)
                returnValue = printReceipts();
            else
                returnValue = SUCCESS;
        } else {
            if (rhForValidation.getService().getCode().equals(CollectionConstants.SERVICECODE_PROPERTYTAX))
                addActionError("Entered Manual receipt number already exists for the index number"
                        + rhForValidation.getConsumerCode()
                        + ".Please enter a valid manual receipt number and create the receipt.");
            else
                addActionError("Receipt already exists for the service ");
            returnValue = NEW;
        }
    }
    return returnValue;
}

From source file:org.egov.egf.expensebill.service.ExpenseBillService.java

private Map<String, Object> getBudgetDetails(EgBillregister egBillregister, EgBilldetails billDetail,
        Map<String, Object> budgetDataMap, Map<String, Object> paramMap) {

    Map<String, Object> budgetApprDetailsMap = new HashMap<>();
    BigDecimal currentBillAmount;
    BigDecimal soFarAppropriated;
    BigDecimal actualAmount;

    if (egBillregister.getEgBillregistermis().getVoucherHeader() != null) {
        budgetDataMap.put(Constants.ASONDATE,
                egBillregister.getEgBillregistermis().getVoucherHeader().getVoucherDate());
    } else {/*  w w w  .  ja va 2 s .co m*/
        budgetDataMap.put(Constants.ASONDATE, egBillregister.getBilldate());
    }
    CFinancialYear financialYearById = egBillregister.getEgBillregistermis().getFinancialyear();

    budgetDataMap.put(Constants.FUNCTIONID, billDetail.getFunctionid().longValue());
    budgetDataMap.put("fromdate", financialYearById.getStartingDate());
    budgetDataMap.put("glcode", billDetail.getChartOfAccounts().getGlcode());
    budgetDataMap.put("glcodeid", billDetail.getChartOfAccounts().getId());
    List<BudgetGroup> budgetHeadByGlcode = budgetDetailsHibernateDAO
            .getBudgetHeadByGlcode(billDetail.getChartOfAccounts());
    budgetDataMap.put("budgetheadid", budgetHeadByGlcode);
    budgetDataMap.put("isReport", "true");
    BigDecimal budgetedAmtForYear = budgetDetailsHibernateDAO.getBudgetedAmtForYear(budgetDataMap);
    paramMap.put("budgetedAmtForYear", budgetedAmtForYear);
    if (LOG.isDebugEnabled())
        LOG.debug("budgetedAmtForYear .......... " + budgetedAmtForYear);

    budgetDataMap.put("budgetApprNumber", egBillregister.getEgBillregistermis().getBudgetaryAppnumber());

    if (LOG.isDebugEnabled())
        LOG.debug("Getting actuals .............................");
    BigDecimal actualAmtFromVoucher = budgetDetailsHibernateDAO
            .getActualBudgetUtilizedForBudgetaryCheck(budgetDataMap);
    if (LOG.isDebugEnabled())
        LOG.debug("actualAmtFromVoucher .............................. " + actualAmtFromVoucher);
    budgetDataMap.put(Constants.ASONDATE, egBillregister.getBilldate());
    BigDecimal actualAmtFromBill = budgetDetailsHibernateDAO.getBillAmountForBudgetCheck(budgetDataMap);
    if (LOG.isDebugEnabled())
        LOG.debug("actualAmtFromBill .............................. " + actualAmtFromBill);

    actualAmount = actualAmtFromVoucher != null ? actualAmtFromVoucher : BigDecimal.ZERO;
    actualAmount = actualAmtFromBill != null ? actualAmount.add(actualAmtFromBill) : actualAmount;
    if (LOG.isDebugEnabled())
        LOG.debug("actualAmount ...actualAmtFromVoucher+actualAmtFromBill........ " + actualAmount);

    if (billDetail.getDebitamount() != null && billDetail.getDebitamount().compareTo(BigDecimal.ZERO) != 0) {
        actualAmount = actualAmount.subtract(billDetail.getDebitamount());
        currentBillAmount = billDetail.getDebitamount();

    } else {
        actualAmount = actualAmount.subtract(billDetail.getCreditamount());
        currentBillAmount = billDetail.getCreditamount();
    }
    if (LOG.isDebugEnabled())
        LOG.debug("actualAmount ...actualAmount-billamount........ " + actualAmount);
    BigDecimal balance = budgetedAmtForYear;

    balance = balance.subtract(actualAmount);
    soFarAppropriated = actualAmount;
    if (LOG.isDebugEnabled())
        LOG.debug("soFarAppropriated ...actualAmount==soFarAppropriated........ " + soFarAppropriated);
    if (LOG.isDebugEnabled())
        LOG.debug("balance ...budgetedAmtForYear-actualAmount........ " + balance);
    BigDecimal cumilativeIncludingCurrentBill = soFarAppropriated.add(currentBillAmount);
    BigDecimal currentBalanceAvailable = balance.subtract(currentBillAmount);
    budgetApprDetailsMap.put("allocatedBudgetForYear", budgetedAmtForYear);
    budgetApprDetailsMap.put("actualAmount", soFarAppropriated);
    budgetApprDetailsMap.put("balance", balance);
    budgetApprDetailsMap.put("expenseIncurredIncludingCurrentBill", cumilativeIncludingCurrentBill);
    budgetApprDetailsMap.put("currentBalanceAvailable", currentBalanceAvailable);
    budgetApprDetailsMap.put("accountCode", billDetail.getChartOfAccounts().getGlcode());

    return budgetApprDetailsMap;

}