List of usage examples for java.math BigDecimal ROUND_HALF_UP
int ROUND_HALF_UP
To view the source code for java.math BigDecimal ROUND_HALF_UP.
Click Source Link
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
/** * Provides collection and demand results * * @param collectionDetailsRequest/*from w w w.j a v a 2 s . c o m*/ * @param fromDate * @param toDate * @param indexName * @param fieldName * @param ulbCodeField * @param aggregationField * @return Map */ public Map<String, BigDecimal> getCollectionAndDemandValues( final WaterChargeDashBoardRequest collectionDetailsRequest, final Date fromDate, final Date toDate, final String indexName, final String fieldName, final String aggregationField) { BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest, indexName); if (indexName.equals(WaterTaxConstants.COLLECTION_INDEX_NAME)) boolQuery = boolQuery .filter(QueryBuilders.rangeQuery(RECEIPT_DATEINDEX) .gte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(fromDate)) .lte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false)) .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED)); final AggregationBuilder aggregation = AggregationBuilders.terms(BY_CITY).field(aggregationField).size(120) .subAggregation(AggregationBuilders.sum("total").field(fieldName)); final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName) .withQuery(boolQuery).addAggregation(aggregation).build(); final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, response -> response.getAggregations()); final StringTerms cityAggr = collAggr.get(BY_CITY); final Map<String, BigDecimal> cytdCollMap = new HashMap<>(); for (final Terms.Bucket entry : cityAggr.getBuckets()) { final Sum aggr = entry.getAggregations().get("total"); cytdCollMap.put(String.valueOf(entry.getKey()), BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)); } return cytdCollMap; }
From source file:org.egov.ptis.domain.service.transfer.PropertyTransferService.java
/** * API to calculate mutation fee/*from w w w.j a v a2s. c o m*/ * * @param partyValue * @param departmentValue * @return MutationFee */ public BigDecimal calculateMutationFee(final BigDecimal partyValue, final BigDecimal departmentValue) { BigDecimal mutationFee = BigDecimal.ZERO; BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue; if (documentValue.compareTo(BigDecimal.ZERO) > 0) { List<MutationFeeDetails> mutationFeeDetailsList = mutationFeeRepository.getMutationFee(documentValue); if (!mutationFeeDetailsList.isEmpty()) { MutationFeeDetails mutationFeeDetails = mutationFeeDetailsList.get(0); if (mutationFeeDetails != null) { if (mutationFeeDetails.getFlatAmount() != null && mutationFeeDetails.getFlatAmount().compareTo(BigDecimal.ZERO) > 0) if ("N".equalsIgnoreCase(mutationFeeDetails.getIsRecursive().toString())) mutationFee = mutationFeeDetails.getFlatAmount(); else { BigDecimal excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit()) .add(BigDecimal.ONE); BigDecimal multiplicationFactor = excessDocValue .divide(mutationFeeDetails.getRecursiveFactor(), BigDecimal.ROUND_CEILING); mutationFee = mutationFeeDetails.getFlatAmount() .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveAmount())); } if (mutationFeeDetails.getPercentage() != null && mutationFeeDetails.getPercentage().compareTo(BigDecimal.ZERO) > 0 && mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase("N")) mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage()) .divide(PropertyTaxConstants.BIGDECIMAL_100); } } } return mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP); }
From source file:com.osafe.services.OsafePayPalServices.java
public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) { GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); BigDecimal captureAmount = (BigDecimal) context.get("captureAmount"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); GenericValue authTrans = (GenericValue) context.get("authTrans"); Locale locale = (Locale) context.get("locale"); if (authTrans == null) { authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref); }// ww w.ja v a 2s.com NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoCapture"); encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum")); encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId")); encoder.add("COMPLETETYPE", "NotComplete"); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { /* return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));*/ return ServiceUtil.returnError("An unknown error occurred while contacting PayPal"); //When we will move all the hard coded error message will remove and uncomment code. } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("captureResult", false); result.put("captureRefNum", "N/A"); result.put("captureAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("captureCode", error.getKey()); result.put("captureMessage", error.getValue()); } else { result.put("captureMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("captureResult", true); result.put("captureAmount", new BigDecimal(decoder.get("AMT"))); result.put("captureRefNum", decoder.get("TRANSACTIONID")); } //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction return result; }
From source file:com.selfsoft.business.service.impl.TbBusinessBalanceServiceImpl.java
private Double calcFavourAmount(Double itemTotal, Double favourRate) { BigDecimal d = new BigDecimal("0.00"); if (null != itemTotal && null != favourRate && !favourRate.equals(1.00D)) { BigDecimal d_itemTotal = new BigDecimal(String.valueOf(itemTotal)); BigDecimal d_favourRate = new BigDecimal(String.valueOf(favourRate)); d = d_itemTotal.multiply(d_favourRate) .divide(new BigDecimal("1.00").subtract(d_favourRate), 2, BigDecimal.ROUND_HALF_UP) .setScale(2, BigDecimal.ROUND_HALF_UP); }/*from ww w .ja v a 2 s. c om*/ return d.doubleValue(); }
From source file:hjow.hgtable.util.DataUtil.java
/** * <p>2? 1 ? .</p>//from ww w. j a v a 2 s . c o m * * @param original : ?? * @param scale : ? * @return 2? 1 */ public static BigDecimal sqrt(BigDecimal original, int scale) { BigDecimal temp = new BigDecimal(String.valueOf(original)); BigDecimal results = new BigDecimal("1.0"); results.setScale(scale + 2); int loops = 0; while (true) { if (loops >= 1) { temp = new BigDecimal(String.valueOf(results)); } temp.setScale(scale + 2, BigDecimal.ROUND_FLOOR); results = original.divide(temp, scale + 2, BigDecimal.ROUND_FLOOR).add(temp) .divide(new BigDecimal("2.0"), scale + 2, BigDecimal.ROUND_FLOOR); if (temp.equals(results)) break; loops++; } return results.setScale(scale, BigDecimal.ROUND_HALF_UP); }
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
/** * Prepares month-wise collections for 3 consecutive years - from current * year/*from w ww . j av a 2 s. c o m*/ * * @param collectionDetailsRequest * @return List */ public List<WaterChargeDashBoardResponse> getMonthwiseCollectionDetails( final WaterChargeDashBoardRequest collectionDetailsRequest) { final List<WaterChargeDashBoardResponse> collTrendsList = new ArrayList<>(); WaterChargeDashBoardResponse collTrend; Date fromDate; Date toDate; Date dateForMonth; String[] dateArr; Integer month; Sum aggregateSum; final CFinancialYear financialYear = cFinancialYearService.getCurrentFinancialYear(); Date finYearStartDate = financialYear.getStartingDate(); Date finYearEndDate = financialYear.getEndingDate(); final Map<Integer, String> monthValuesMap = DateUtils.getAllMonthsWithFullNames(); String monthName; final List<Map<String, BigDecimal>> yearwiseMonthlyCollList = new ArrayList<>(); Map<String, BigDecimal> monthwiseColl; /** * For month-wise collections between the date ranges if dates are sent * in the request, consider fromDate and toDate+1 , else calculate from * current year start date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = DateUtils.startOfDay(financialYear.getStartingDate()); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } Long startTime = System.currentTimeMillis(); for (int count = 0; count <= 2; count++) { monthwiseColl = new LinkedHashMap<>(); final Aggregations collAggr = getMonthwiseCollectionsForConsecutiveYears(collectionDetailsRequest, fromDate, toDate); final Histogram dateaggs = collAggr.get(AGGR_DATE); for (final Histogram.Bucket entry : dateaggs.getBuckets()) { dateArr = entry.getKeyAsString().split("T"); dateForMonth = DateUtils.getDate(dateArr[0], DATE_FORMAT_YYYYMMDD); month = Integer.valueOf(dateArr[0].split("-", 3)[1]); monthName = monthValuesMap.get(month); aggregateSum = entry.getAggregations().get("current_total"); // If the total amount is greater than 0 and the month belongs // to respective financial year, add values to the map if (DateUtils.between(dateForMonth, finYearStartDate, finYearEndDate) && BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP) .compareTo(BigDecimal.ZERO) > 0) monthwiseColl.put(monthName, BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)); } yearwiseMonthlyCollList.add(monthwiseColl); /** * If dates are passed in request, get result for the date range, * else get results for entire financial year */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1); toDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1); } else { fromDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearStartDate, -1); toDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearEndDate, -1); } finYearStartDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearStartDate, -1); finYearEndDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearEndDate, -1); } Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug( "Time taken by getMonthwiseCollectionsForConsecutiveYears() for 3 consecutive years is (millisecs): " + timeTaken); startTime = System.currentTimeMillis(); /** * If dates are passed in request, get result for the date range, else * get results for all 12 months */ if (StringUtils.isBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isBlank(collectionDetailsRequest.getToDate())) for (final Map.Entry<Integer, String> entry : DateUtils.getAllFinancialYearMonthsWithFullNames() .entrySet()) { collTrend = new WaterChargeDashBoardResponse(); collTrend.setMonth(entry.getValue()); collTrend.setCurrentYearColl( yearwiseMonthlyCollList.get(0).get(collTrend.getMonth()) == null ? BigDecimal.ZERO : yearwiseMonthlyCollList.get(0).get(collTrend.getMonth())); collTrend.setLastYearColl( yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO : yearwiseMonthlyCollList.get(1).get(collTrend.getMonth())); collTrend.setPreviousYearColl( yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO : yearwiseMonthlyCollList.get(2).get(collTrend.getMonth())); collTrendsList.add(collTrend); } else for (final Map.Entry<String, BigDecimal> entry : yearwiseMonthlyCollList.get(0).entrySet()) { collTrend = new WaterChargeDashBoardResponse(); collTrend.setMonth(entry.getKey()); collTrend.setCurrentYearColl(entry.getValue()); collTrend.setLastYearColl( yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO : yearwiseMonthlyCollList.get(1).get(collTrend.getMonth())); collTrend.setPreviousYearColl( yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO : yearwiseMonthlyCollList.get(2).get(collTrend.getMonth())); collTrendsList.add(collTrend); } timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug( "Time taken setting values in getMonthwiseCollectionDetails() is (millisecs) : " + timeTaken); return collTrendsList; }
From source file:org.eevolution.form.VCRP.java
protected BigDecimal calculateLoad(Timestamp dateTime, MResource r, String docStatus) { MResourceType t = new MResourceType(Env.getCtx(), r.getS_ResourceType_ID(), null); MMPCOrderNode[] nodes = getMPCOrderNodes(dateTime, r); MUOM uom = new MUOM(Env.getCtx(), t.getC_UOM_ID(), null); MMPCOrder o = null;/*from w w w .j a va 2 s. com*/ BigDecimal qtyOpen; long millis = 0l; for (int i = 0; i < nodes.length; i++) { o = new MMPCOrder(Env.getCtx(), nodes[i].getMPC_Order_ID(), null); if (docStatus != null && !o.getDocStatus().equals(docStatus)) { continue; } millis += calculateMillisForDay(dateTime, nodes[i], t); } // Pre-converts to minutes, because its the lowest time unit of compiere BigDecimal scale = new BigDecimal(1000 * 60); BigDecimal minutes = new BigDecimal(millis).divide(scale, 2, BigDecimal.ROUND_HALF_UP); //return convert(minutes); return minutes; }
From source file:org.efaps.esjp.accounting.transaction.Create_Base.java
/** * Analyse positions from ui.//from w ww .j a v a 2 s .com * * @param _parameter Parameter as passed by the eFaps API * @param _transInfo the trans info * @param _postFix the post fix * @param _accountOids the account oids * @param _executeRels the execute rels * @throws EFapsException on error */ public void analysePositionsFromUI(final Parameter _parameter, final TransInfo _transInfo, final String _postFix, final String[] _accountOids, final boolean _executeRels) throws EFapsException { @SuppressWarnings("unchecked") final Map<String, String> oidMap = (Map<String, String>) _parameter.get(ParameterValues.OIDMAP4UI); final String[] rowKeys = InterfaceUtils.getRowKeys(_parameter, "amount_" + _postFix, "amount_Debit", "amount_Credit"); final String[] accountOids = _accountOids == null ? _parameter.getParameterValues("accountLink_" + _postFix) : _accountOids; final String[] amounts = _parameter.getParameterValues("amount_" + _postFix); final String[] types = _parameter.getParameterValues("type_" + _postFix); final String[] rateCurIds = _parameter.getParameterValues("rateCurrencyLink_" + _postFix); final String[] acc2accOids = _parameter.getParameterValues("acc2acc_" + _postFix); final String[] labelLinkOids = _parameter.getParameterValues("labelLink_" + _postFix); final String[] docLinkOids = _parameter.getParameterValues("docLink_" + _postFix); final String[] remarks = _parameter.getParameterValues("remark_" + _postFix); final DecimalFormat formater = NumberFormatter.get().getFormatter(); try { Instance inst = _parameter.getCallInstance(); if (!inst.getType().isKindOf(CIAccounting.Period.getType())) { inst = new Period().evaluateCurrentPeriod(_parameter); } final Instance curInstance = new Period().getCurrency(inst).getInstance(); if (amounts != null) { for (int i = 0; i < amounts.length; i++) { final Instance rateCurrInst = CurrencyInst.get(Long.parseLong(rateCurIds[i])).getInstance(); final Instance accInst = Instance.get(accountOids[i]); final Object[] rateObj = getRateObject(_parameter, "_" + _postFix, i); final RateInfo rateInfo = getRateInfo4UI(_parameter, "_" + _postFix, i); final Type type = Type.get(Long.parseLong(types[i])); final boolean isDebitTrans = type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid); final BigDecimal rateAmount = ((BigDecimal) formater.parse(amounts[i])).setScale(2, RoundingMode.HALF_UP); final BigDecimal amount = Currency .convertToCurrency(_parameter, rateAmount, rateInfo, null, curInstance) .setScale(2, RoundingMode.HALF_UP); final PositionInfo pos = new PositionInfo(); _transInfo.addPosition(pos); pos.setType(type).setAccInst(accInst).setCurrInst(curInstance).setRateCurrInst(rateCurrInst) .setRate(rateObj).setRateAmount(isDebitTrans ? rateAmount.negate() : rateAmount) .setAmount(isDebitTrans ? amount.negate() : amount).setOrder(i) .setRemark(remarks == null ? null : remarks[i]) .setInstance(Instance.get(oidMap.get(rowKeys[i]))); if (labelLinkOids != null) { final Instance labelInst = Instance.get(labelLinkOids[i]); if (labelInst.isValid()) { pos.setLabelInst(labelInst) .setLabelRelType(_postFix.equalsIgnoreCase("Debit") ? CIAccounting.TransactionPositionDebit2LabelProject.getType() : CIAccounting.TransactionPositionCredit2LabelProject.getType()); } } if (docLinkOids != null) { final Instance docInst = Instance.get(docLinkOids[i]); if (docInst.isValid()) { final DocumentInfo docInfoTmp = new DocumentInfo(docInst); if (docInfoTmp.isSumsDoc()) { pos.setDocInst(docInst) .setDocRelType(_postFix.equalsIgnoreCase("Debit") ? CIAccounting.TransactionPositionDebit2SalesDocument.getType() : CIAccounting.TransactionPositionCredit2SalesDocument.getType()); } else { pos.setDocInst(docInst) .setDocRelType(_postFix.equalsIgnoreCase("Debit") ? CIAccounting.TransactionPositionDebit2PaymentDocument.getType() : CIAccounting.TransactionPositionCredit2PaymentDocument.getType()); } } } if (_executeRels) { final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Account2AccountAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, accInst); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selAcc = SelectBuilder.get() .linkto(CIAccounting.Account2AccountAbstract.ToAccountLink).instance(); multi.addSelect(selAcc); multi.addAttribute(CIAccounting.Account2AccountAbstract.Numerator, CIAccounting.Account2AccountAbstract.Denominator, CIAccounting.Account2AccountAbstract.Config); multi.execute(); int y = 1; final int group = _transInfo.getNextGroup(); while (multi.next()) { final Instance instance = multi.getCurrentInstance(); final PositionInfo connPos = new PositionInfo(); connPos.setPosType(TransPosType.CONNECTION); final Collection<Accounting.Account2AccountConfig> configs = multi .getAttribute(CIAccounting.Account2AccountAbstract.Config); final boolean deactivatable = configs != null && configs.contains(Accounting.Account2AccountConfig.DEACTIVATABLE); final boolean confCheck = isDebitTrans && configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4DEBIT) || !isDebitTrans && configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4CREDIT); // if cannot be deactivated or selected in the UserInterface if (confCheck && (!deactivatable || acc2accOids != null && deactivatable && Arrays.asList(acc2accOids).contains(instance.getOid()))) { final BigDecimal numerator = new BigDecimal(multi .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator)); final BigDecimal denominator = new BigDecimal(multi .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator)); BigDecimal amount2 = amount.multiply(numerator).divide(denominator, BigDecimal.ROUND_HALF_UP); BigDecimal rateAmount2 = rateAmount.multiply(numerator).divide(denominator, BigDecimal.ROUND_HALF_UP); if (instance.getType().isCIType(CIAccounting.Account2AccountCosting)) { connPos.setType(type); } else if (instance.getType() .isCIType(CIAccounting.Account2AccountCostingInverse)) { if (type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid)) { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } else { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); } amount2 = amount2.negate(); } else if (instance.getType().isCIType(CIAccounting.Account2AccountCredit)) { if (isDebitTrans) { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } else { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); amount2 = amount2.negate(); rateAmount2 = rateAmount2.negate(); } } else if (instance.getType().isCIType(CIAccounting.Account2AccountDebit)) { if (isDebitTrans) { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); amount2 = amount2.negate(); rateAmount2 = rateAmount2.negate(); } else { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } } if (connPos.getType() == null) { Create_Base.LOG.error("Missing definition"); } else { connPos.setOrder(i).setConnOrder(y).setGroupId(group) .setAccInst(multi.<Instance>getSelect(selAcc)).setCurrInst(curInstance) .setRateCurrInst(rateCurrInst).setRate(rateObj).setAmount(amount2) .setRateAmount(rateAmount2); _transInfo.addPosition(connPos); } y++; } } } } } } catch (final ParseException e) { throw new EFapsException(Transaction_Base.class, "insertPositions", e); } }
From source file:org.egov.adtax.service.AdvertisementDemandService.java
private EgDemand generateNextYearDemandForAdvertisement(final Advertisement advertisement, final EgDemandReason oldencroachmentFeeReasonInstallment, final EgDemandReason oldtaxReasonInstallment, final EgDemandReason newencroachmentFeeReasonInstallment, final EgDemandReason newtaxReasonInstallment) { BigDecimal totalDemandAmount = BigDecimal.ZERO; final EgDemand demand = advertisement.getDemandId(); Boolean enchroachmentFeeAlreadyExistInDemand = false; Boolean taxFeeAlreadyExistInDemand = false; EgDemandDetails oldEncroachmentDetail = null; EgDemandDetails oldTaxDemandDetail = null; final Set<EgDemandDetails> dmadDtl = demand.getEgDemandDetails(); if (LOGGER.isInfoEnabled()) LOGGER.info("Demand Detail size" + dmadDtl.size()); for (final EgDemandDetails dmdDtl : dmadDtl) { // Assumption: tax amount is mandatory. if (dmdDtl.getEgDemandReason().getId() == oldtaxReasonInstallment.getId()) oldTaxDemandDetail = dmdDtl; if (dmdDtl.getEgDemandReason().getId() == oldencroachmentFeeReasonInstallment.getId()) oldEncroachmentDetail = dmdDtl; if (dmdDtl.getEgDemandReason().getId() == newtaxReasonInstallment.getId()) taxFeeAlreadyExistInDemand = true; if (dmdDtl.getEgDemandReason().getId() == newencroachmentFeeReasonInstallment.getId()) enchroachmentFeeAlreadyExistInDemand = true; }/*from w ww . ja va 2s . c om*/ // Copy last financial year tax and encroachment details to new // installment // if tax and encroachment fee already present in new installment, then // we are not updating. if (!enchroachmentFeeAlreadyExistInDemand && oldEncroachmentDetail != null) { demand.addEgDemandDetails(createDemandDetails(oldEncroachmentDetail.getAmount(), newencroachmentFeeReasonInstallment, BigDecimal.ZERO)); totalDemandAmount = totalDemandAmount.add(oldEncroachmentDetail.getAmount()); } if (!taxFeeAlreadyExistInDemand && oldTaxDemandDetail != null) { demand.addEgDemandDetails( createDemandDetails(oldTaxDemandDetail.getAmount(), newtaxReasonInstallment, BigDecimal.ZERO)); totalDemandAmount = totalDemandAmount.add(oldTaxDemandDetail.getAmount()); } demand.setEgInstallmentMaster(newencroachmentFeeReasonInstallment.getEgInstallmentMaster()); demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP)); return demand; }
From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java
public static Map<String, Object> doRefund(DispatchContext dctx, Map<String, Object> context) { Locale locale = (Locale) context.get("locale"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null); if (payPalConfig == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale)); }/*from ww w. jav a 2 s . c o m*/ GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); GenericValue captureTrans = PaymentGatewayServices.getCaptureTransaction(orderPaymentPreference); BigDecimal refundAmount = (BigDecimal) context.get("refundAmount"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "RefundTransaction"); encoder.add("TRANSACTIONID", captureTrans.getString("referenceNum")); encoder.add("REFUNDTYPE", "Partial"); encoder.add("CURRENCYCODE", captureTrans.getString("currencyUomId")); encoder.add("AMT", refundAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("NOTE", "Order #" + orderPaymentPreference.getString("orderId")); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil .returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("refundResult", false); result.put("refundRefNum", captureTrans.getString("referenceNum")); result.put("refundAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("refundCode", error.getKey()); result.put("refundMessage", error.getValue()); } else { result.put("refundMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("refundResult", true); result.put("refundAmount", new BigDecimal(decoder.get("GROSSREFUNDAMT"))); result.put("refundRefNum", decoder.get("REFUNDTRANSACTIONID")); } return result; }