List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.kuali.ole.module.purap.document.service.impl.InvoiceServiceImpl.java
/** * Generates a PurAP accounting line and adds to the specified tax item. * * @param taxItem The specified tax item the accounting line will be associated with. * @param taxableAmount The amount to which tax is computed against. * @return A fully populated PurApAccountingLine instance for the specified tax item. *//* w w w . ja v a 2s .c o m*/ protected PurApAccountingLine addTaxAccountingLine(PurApItem taxItem, BigDecimal taxableAmount) { InvoiceDocument prqs = taxItem.getPurapDocument(); PurApAccountingLine taxLine = null; try { taxLine = (PurApAccountingLine) taxItem.getAccountingLineClass().newInstance(); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Unable to access sourceAccountingLineClass", e); } catch (InstantiationException e) { throw new IllegalArgumentException("Unable to instantiate sourceAccountingLineClass", e); } // tax item type indicators boolean isFederalTax = ItemTypeCodes.ITEM_TYPE_FEDERAL_TAX_CODE.equals(taxItem.getItemTypeCode()); boolean isFederalGross = ItemTypeCodes.ITEM_TYPE_FEDERAL_GROSS_CODE.equals(taxItem.getItemTypeCode()); boolean isStateTax = ItemTypeCodes.ITEM_TYPE_STATE_TAX_CODE.equals(taxItem.getItemTypeCode()); boolean isStateGross = ItemTypeCodes.ITEM_TYPE_STATE_GROSS_CODE.equals(taxItem.getItemTypeCode()); boolean isFederal = isFederalTax || isFederalGross; // true for federal tax/gross; false for state tax/gross boolean isGross = isFederalGross || isStateGross; // true for federal/state gross, false for federal/state tax // obtain accounting line info according to tax item type code String taxChart = null; String taxAccount = null; String taxObjectCode = null; if (isGross) { // for gross up tax items, use prqs's first item's first accounting line, which shall exist at this point AccountingLine line1 = prqs.getFirstAccount(); taxChart = line1.getChartOfAccountsCode(); taxAccount = line1.getAccountNumber(); taxObjectCode = line1.getFinancialObjectCode(); } else if (isFederalTax) { // for federal tax item, get chart, account, object code info from parameters taxChart = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE, OLEConstants.InvoiceDocument.CMPNT_CD, NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX); taxAccount = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE, OLEConstants.InvoiceDocument.CMPNT_CD, NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX); taxObjectCode = parameterService.getSubParameterValueAsString(InvoiceDocument.class, NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX, prqs.getTaxClassificationCode()); if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount) || StringUtils.isBlank(taxObjectCode)) { LOG.error("Unable to retrieve federal tax parameters."); throw new RuntimeException("Unable to retrieve federal tax parameters."); } } else if (isStateTax) { // for state tax item, get chart, account, object code info from parameters taxChart = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE, OLEConstants.InvoiceDocument.CMPNT_CD, NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX); taxAccount = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE, OLEConstants.InvoiceDocument.CMPNT_CD, NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX); taxObjectCode = parameterService.getSubParameterValueAsString(InvoiceDocument.class, NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX, prqs.getTaxClassificationCode()); if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount) || StringUtils.isBlank(taxObjectCode)) { LOG.error("Unable to retrieve state tax parameters."); throw new RuntimeException("Unable to retrieve state tax parameters."); } } // calculate tax amount according to gross up indicator and federal/state tax type /* * The formula of tax and gross up amount are as follows: if (not gross up) gross not existing taxFederal/State = - amount * * rateFederal/State otherwise gross up grossFederal/State = amount * rateFederal/State / (1 - rateFederal - rateState) tax * = - gross */ // pick federal/state tax rate BigDecimal taxPercentFederal = prqs.getTaxFederalPercent(); BigDecimal taxPercentState = prqs.getTaxStatePercent(); BigDecimal taxPercent = isFederal ? taxPercentFederal : taxPercentState; // divider value according to gross up or not BigDecimal taxDivider = new BigDecimal(100); if (prqs.getTaxGrossUpIndicator()) { taxDivider = taxDivider.subtract(taxPercentFederal.add(taxPercentState)); } // tax = amount * rate / divider BigDecimal taxAmount = taxableAmount.multiply(taxPercent); taxAmount = taxAmount.divide(taxDivider, 5, BigDecimal.ROUND_HALF_UP); // tax is always negative, since it reduces the total amount; while gross up is always the positive of tax if (!isGross) { taxAmount = taxAmount.negate(); } // populate necessary accounting line fields taxLine.setDocumentNumber(prqs.getDocumentNumber()); taxLine.setSequenceNumber(prqs.getNextSourceLineNumber()); taxLine.setChartOfAccountsCode(taxChart); taxLine.setAccountNumber(taxAccount); taxLine.setFinancialObjectCode(taxObjectCode); taxLine.setAmount(new KualiDecimal(taxAmount)); // add the accounting line to the item taxLine.setItemIdentifier(taxItem.getItemIdentifier()); taxLine.setPurapItem(taxItem); taxItem.getSourceAccountingLines().add(taxLine); return taxLine; }
From source file:com.dp2345.entity.Cart.java
/** * ?// w w w. jav a 2 s . co m * * @return */ @Transient public BigDecimal getDiscount() { BigDecimal originalPrice = new BigDecimal(0); BigDecimal currentPrice = new BigDecimal(0); for (Promotion promotion : getPromotions()) { if (promotion != null) { int promotionQuantity = getQuantity(promotion); BigDecimal originalPromotionPrice = getTempPrice(promotion); BigDecimal currentPromotionPrice = promotion.calculatePrice(promotionQuantity, originalPromotionPrice); originalPrice = originalPrice.add(originalPromotionPrice); currentPrice = currentPrice.add(currentPromotionPrice); Set<CartItem> cartItems = getCartItems(promotion); for (CartItem cartItem : cartItems) { if (cartItem != null && cartItem.getTempPrice() != null) { BigDecimal tempPrice; if (originalPromotionPrice.compareTo(new BigDecimal(0)) > 0) { tempPrice = currentPromotionPrice.divide(originalPromotionPrice, 50, RoundingMode.DOWN) .multiply(cartItem.getTempPrice()); } else { tempPrice = new BigDecimal(0); } cartItem.setTempPrice( tempPrice.compareTo(new BigDecimal(0)) > 0 ? tempPrice : new BigDecimal(0)); } } } } if (getCartItems() != null) { for (CartItem cartItem : getCartItems()) { if (cartItem != null) { cartItem.setTempPrice(null); } } } Setting setting = SettingUtils.get(); BigDecimal discount = setting.setScale(originalPrice.subtract(currentPrice)); return discount.compareTo(new BigDecimal(0)) > 0 ? discount : new BigDecimal(0); }
From source file:org.kuali.kfs.module.purap.document.service.impl.PaymentRequestServiceImpl.java
/** * Generates a PurAP accounting line and adds to the specified tax item. * * @param taxItem The specified tax item the accounting line will be associated with. * @param taxableAmount The amount to which tax is computed against. * @return A fully populated PurApAccountingLine instance for the specified tax item. *///from www. j a v a 2s .c om protected PurApAccountingLine addTaxAccountingLine(PurApItem taxItem, BigDecimal taxableAmount) { PaymentRequestDocument preq = taxItem.getPurapDocument(); PurApAccountingLine taxLine = null; try { taxLine = (PurApAccountingLine) taxItem.getAccountingLineClass().newInstance(); } catch (IllegalAccessException e) { throw new InfrastructureException("Unable to access sourceAccountingLineClass", e); } catch (InstantiationException e) { throw new InfrastructureException("Unable to instantiate sourceAccountingLineClass", e); } // tax item type indicators boolean isFederalTax = ItemTypeCodes.ITEM_TYPE_FEDERAL_TAX_CODE.equals(taxItem.getItemTypeCode()); boolean isFederalGross = ItemTypeCodes.ITEM_TYPE_FEDERAL_GROSS_CODE.equals(taxItem.getItemTypeCode()); boolean isStateTax = ItemTypeCodes.ITEM_TYPE_STATE_TAX_CODE.equals(taxItem.getItemTypeCode()); boolean isStateGross = ItemTypeCodes.ITEM_TYPE_STATE_GROSS_CODE.equals(taxItem.getItemTypeCode()); boolean isFederal = isFederalTax || isFederalGross; // true for federal tax/gross; false for state tax/gross boolean isGross = isFederalGross || isStateGross; // true for federal/state gross, false for federal/state tax // obtain accounting line info according to tax item type code String taxChart = null; String taxAccount = null; String taxObjectCode = null; if (isGross) { // for gross up tax items, use preq's first item's first accounting line, which shall exist at this point AccountingLine line1 = preq.getFirstAccount(); taxChart = line1.getChartOfAccountsCode(); taxAccount = line1.getAccountNumber(); taxObjectCode = line1.getFinancialObjectCode(); } else if (isFederalTax) { // for federal tax item, get chart, account, object code info from parameters taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class, NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX); taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class, NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX); taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class, NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX, preq.getTaxClassificationCode()); if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount) || StringUtils.isBlank(taxObjectCode)) { LOG.error("Unable to retrieve federal tax parameters."); throw new RuntimeException("Unable to retrieve federal tax parameters."); } } else if (isStateTax) { // for state tax item, get chart, account, object code info from parameters taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class, NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX); taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class, NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX); taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class, NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX, preq.getTaxClassificationCode()); if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount) || StringUtils.isBlank(taxObjectCode)) { LOG.error("Unable to retrieve state tax parameters."); throw new RuntimeException("Unable to retrieve state tax parameters."); } } // calculate tax amount according to gross up indicator and federal/state tax type /* * The formula of tax and gross up amount are as follows: if (not gross up) gross not existing taxFederal/State = - amount * * rateFederal/State otherwise gross up grossFederal/State = amount * rateFederal/State / (1 - rateFederal - rateState) tax * = - gross */ // pick federal/state tax rate BigDecimal taxPercentFederal = preq.getTaxFederalPercent(); BigDecimal taxPercentState = preq.getTaxStatePercent(); BigDecimal taxPercent = isFederal ? taxPercentFederal : taxPercentState; // divider value according to gross up or not BigDecimal taxDivider = new BigDecimal(100); if (preq.getTaxGrossUpIndicator()) { taxDivider = taxDivider.subtract(taxPercentFederal.add(taxPercentState)); } // tax = amount * rate / divider BigDecimal taxAmount = taxableAmount.multiply(taxPercent); taxAmount = taxAmount.divide(taxDivider, 5, BigDecimal.ROUND_HALF_UP); // tax is always negative, since it reduces the total amount; while gross up is always the positive of tax if (!isGross) { taxAmount = taxAmount.negate(); } // populate necessary accounting line fields taxLine.setDocumentNumber(preq.getDocumentNumber()); taxLine.setSequenceNumber(preq.getNextSourceLineNumber()); taxLine.setChartOfAccountsCode(taxChart); taxLine.setAccountNumber(taxAccount); taxLine.setFinancialObjectCode(taxObjectCode); taxLine.setAmount(new KualiDecimal(taxAmount)); // add the accounting line to the item taxLine.setItemIdentifier(taxItem.getItemIdentifier()); taxLine.setPurapItem(taxItem); taxItem.getSourceAccountingLines().add(taxLine); return taxLine; }
From source file:org.openbravo.advpaymentmngt.actionHandler.AddPaymentActionHandler.java
private void addCredit(FIN_Payment payment, JSONObject jsonparams, BigDecimal differenceAmount, String strDifferenceAction) throws JSONException { // Credit to Use Grid JSONObject creditToUseGrid = jsonparams.getJSONObject("credit_to_use"); JSONArray selectedCreditLines = creditToUseGrid.getJSONArray("_selection"); BigDecimal remainingRefundAmt = differenceAmount; String strSelectedCreditLinesIds = null; if (selectedCreditLines.length() > 0) { strSelectedCreditLinesIds = getSelectedCreditLinesIds(selectedCreditLines); List<FIN_Payment> selectedCreditPayment = FIN_Utility.getOBObjectList(FIN_Payment.class, strSelectedCreditLinesIds); HashMap<String, BigDecimal> selectedCreditPaymentAmounts = getSelectedCreditLinesAndAmount( selectedCreditLines, selectedCreditPayment); for (final FIN_Payment creditPayment : selectedCreditPayment) { BusinessPartner businessPartner = creditPayment.getBusinessPartner(); if (businessPartner == null) { throw new OBException(OBMessageUtils.messageBD("APRM_CreditWithoutBPartner")); }//www .j a v a 2 s .c o m String currency = null; if (businessPartner.getCurrency() == null) { currency = creditPayment.getCurrency().getId(); businessPartner.setCurrency(creditPayment.getCurrency()); } else { currency = businessPartner.getCurrency().getId(); } if (!creditPayment.getCurrency().getId().equals(currency)) { throw new OBException(String.format(OBMessageUtils.messageBD("APRM_CreditCurrency"), businessPartner.getCurrency().getISOCode())); } BigDecimal usedCreditAmt = selectedCreditPaymentAmounts.get(creditPayment.getId()); if (strDifferenceAction.equals("refund")) { if (remainingRefundAmt.compareTo(usedCreditAmt) > 0) { remainingRefundAmt = remainingRefundAmt.subtract(usedCreditAmt); usedCreditAmt = BigDecimal.ZERO; } else { usedCreditAmt = usedCreditAmt.subtract(remainingRefundAmt); remainingRefundAmt = BigDecimal.ZERO; } } final StringBuffer description = new StringBuffer(); if (creditPayment.getDescription() != null && !creditPayment.getDescription().equals("")) { description.append(creditPayment.getDescription()).append("\n"); } description.append( String.format(OBMessageUtils.messageBD("APRM_CreditUsedPayment"), payment.getDocumentNo())); String truncateDescription = (description.length() > 255) ? description.substring(0, 251).concat("...").toString() : description.toString(); creditPayment.setDescription(truncateDescription); // Set Used Credit = Amount + Previous used credit introduced by the user creditPayment.setUsedCredit(usedCreditAmt.add(creditPayment.getUsedCredit())); if (usedCreditAmt.compareTo(BigDecimal.ZERO) > 0) { FIN_PaymentProcess.linkCreditPayment(payment, usedCreditAmt, creditPayment); } OBDal.getInstance().save(creditPayment); } } }
From source file:org.kuali.ole.select.document.OlePaymentRequestDocument.java
@Override public void processAfterRetrieve() { super.processAfterRetrieve(); try {//from w ww. j a v a2 s . co m LOG.debug("###########inside OlePaymentRequestDocument processAfterRetrieve###########"); if (this.getVendorAliasName() == null) { populateVendorAliasName(); } if (this.getPaymentMethodId() != null) { OlePaymentMethod olePaymentMethod = SpringContext.getBean(BusinessObjectService.class) .findBySinglePrimaryKey(OlePaymentMethod.class, this.getPaymentMethodId()); this.setPaymentMethod(olePaymentMethod); } List<BigDecimal> newUnitPriceList = new ArrayList<BigDecimal>(); BigDecimal newUnitPrice = new BigDecimal(0); BigDecimal hundred = new BigDecimal(100); List<OlePaymentRequestItem> item = this.getItems(); for (int i = 0; item.size() > i; i++) { OlePaymentRequestItem items = (OlePaymentRequestItem) this.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { if (items.getItemDiscount() == null) { items.setItemDiscount(KualiDecimal.ZERO); } if (items.getItemListPrice() == null) { items.setItemListPrice(KualiDecimal.ZERO); } if (items.getItemDiscountType() != null && items.getItemDiscountType() .equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) { newUnitPrice = (hundred.subtract(items.getItemDiscount().bigDecimalValue())).divide(hundred) .multiply(items.getItemListPrice().bigDecimalValue()); } else { newUnitPrice = items.getItemListPrice().bigDecimalValue() .subtract(items.getItemDiscount().bigDecimalValue()); } items.setItemSurcharge( items.getItemUnitPrice().subtract(newUnitPrice).setScale(4, RoundingMode.HALF_UP)); } } if (this.getVendorDetail().getCurrencyType() != null) { if (this.getVendorDetail().getCurrencyType().getCurrencyType() .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { currencyTypeIndicator = true; } else { currencyTypeIndicator = false; } } OleInvoiceDocument oleInvoiceDocument = SpringContext.getBean(BusinessObjectService.class) .findBySinglePrimaryKey(OleInvoiceDocument.class, this.getInvoiceIdentifier()); if (oleInvoiceDocument.getInvoiceCurrencyTypeId() != null && oleInvoiceDocument.getForeignVendorInvoiceAmount() != null && oleInvoiceDocument.getInvoiceCurrencyExchangeRate() != null) { this.setForeignVendorInvoiceAmount(this.getVendorInvoiceAmount().bigDecimalValue() .multiply(new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate()))); } else { if (this.getVendorDetail() != null && (!currencyTypeIndicator)) { Long currencyTypeId = this.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId); List<OleExchangeRate> exchangeRateList = (List) getBusinessObjectService().findMatchingOrderBy( OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); for (OlePaymentRequestItem items : item) { iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate())); this.setForeignVendorInvoiceAmount(this.getVendorInvoiceAmount().bigDecimalValue() .multiply(tempOleExchangeRate.getExchangeRate())); } } } } String itemDescription = ""; for (OlePaymentRequestItem singleItem : item) { if (LOG.isDebugEnabled()) { LOG.debug("Title id while retriving ------>" + singleItem.getItemTitleId()); } if (singleItem.getItemTitleId() != null) { LOG.debug("###########inside processAfterRetrieve ole requisition item###########"); Bib bib = new BibMarc(); DocstoreClientLocator docstoreClientLocator = new DocstoreClientLocator(); if (singleItem.getItemTitleId() != null && singleItem.getItemTitleId() != "") { bib = docstoreClientLocator.getDocstoreClient().retrieveBib(singleItem.getItemTitleId()); singleItem.setBibUUID(bib.getId()); singleItem .setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(singleItem.getItemTitleId())); } if (singleItem.getItemUnitPrice() != null) { singleItem.setItemUnitPrice( singleItem.getItemUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP)); } itemDescription = ((bib.getTitle() != null && !bib.getTitle().isEmpty()) ? bib.getTitle().trim() + ", " : "") + ((bib.getAuthor() != null && !bib.getAuthor().isEmpty()) ? bib.getAuthor().trim() + ", " : "") + ((bib.getPublisher() != null && !bib.getPublisher().isEmpty()) ? bib.getPublisher().trim() + ", " : "") + ((bib.getIsbn() != null && !bib.getIsbn().isEmpty()) ? bib.getIsbn().trim() + ", " : ""); if (itemDescription != null && !(itemDescription.equals(""))) { itemDescription = itemDescription.lastIndexOf(",") < 0 ? itemDescription : itemDescription.substring(0, itemDescription.lastIndexOf(",")); StringEscapeUtils stringEscapeUtils = new StringEscapeUtils(); itemDescription = stringEscapeUtils.unescapeXml(itemDescription); singleItem.setItemDescription(itemDescription); } HashMap<String, String> queryMap = new HashMap<String, String>(); if (singleItem.getPoItemIdentifier() != null) { queryMap.put(OLEConstants.PO_ITEM_ID, singleItem.getPoItemIdentifier().toString()); OleInvoiceItem oleInvoiceItem = getBusinessObjectService() .findByPrimaryKey(OleInvoiceItem.class, queryMap); if (oleInvoiceItem != null && oleInvoiceItem.getPoItemIdentifier() != null) { queryMap.clear(); queryMap.put(OLEConstants.OleCopy.PO_ITM_ID, oleInvoiceItem.getPoItemIdentifier().toString()); List<OLELinkPurapDonor> oleLinkPurapDonorList = (List<OLELinkPurapDonor>) getBusinessObjectService() .findMatching(OLELinkPurapDonor.class, queryMap); if (oleLinkPurapDonorList != null) { singleItem.setOleDonors(oleLinkPurapDonorList); } } } } for (OLEPaidCopy olePaidCopy : singleItem.getPaidCopies()) { if (olePaidCopy.getPaymentRequestItemId() == null && olePaidCopy.getPaymentRequestIdentifier() == null) { olePaidCopy.setPaymentRequestItemId(singleItem.getItemIdentifier()); olePaidCopy.setPaymentRequestIdentifier(this.getPurapDocumentIdentifier()); getBusinessObjectService().save(olePaidCopy); } } } if (this.getProrateBy() != null) { this.setProrateQty(this.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)); this.setProrateManual(this.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)); this.setProrateDollar(this.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)); this.setNoProrate(this.getProrateBy().equals(OLEConstants.NO_PRORATE)); } } catch (Exception e) { LOG.error("Exception during processAfterRetrieve() in OlePaymentRequestDocument", e); throw new RuntimeException(e); } }
From source file:com.zuora.api.UsageAdjInvoiceRegenerator.java
protected UsageAdjInvoiceRegenerator() throws Exception { //MAX_ITEMS_PER_CALL = AppParamManager.MAX_ZOBJECTS_PER_BATCH; // Initialize the API Client. zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME, AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION); zApiClient.login();// ww w .j a v a2 s . c om //Logger.print("logged in"); /* threadDataArray = new ThreadData[AppParamManager.MAX_WORKING_THREADS]; for (int i = 0; i < AppParamManager.MAX_WORKING_THREADS; i++) { threadDataArray[i] = new ThreadData(i); } */ //int indexOfThreadDataArray = 0; int itemsCollectionIndex = 0; String savedRPId = ""; String savedAccountId = ""; String savedInvoiceId = ""; String savedPRPCId = ""; Calendar savedServiceEndDt = null; Calendar savedInvoiceDt = null; Calendar savedTargetDt = null; String savedBaseUOM = null; String savedOverUOM = null; String basePRPCId = null; List<Usage> deleteUOMs = null; boolean skipDelete = false; /* String InvoiceNumberDisplay = ""; BufferedWriter writer = new BufferedWriter( new FileWriter("C:\\Temp\\output"+output+".txt")); */ //Logger.print("thread initiated, max objects: "+AppParamManager.MAX_ZOBJECTS_PER_BATCH+" Total number of Line Items: "+eInvoiceItemAll.size()); //String rpcQuery1 = "SELECT Price, base_quantity__c from RatePlanCharge where ProductRatePlanChargeId = '"; String rpcQuery1 = "SELECT Price from RatePlanCharge where ProductRatePlanChargeId = '"; String rpcQuery2 = "' and RatePlanId = '"; //String rpcQuery3 = "' and Base_Quantity__c <> '0'"; String rpcQuery3 = "'"; String finalquery = ""; BigDecimal result = BigDecimal.ZERO; BigDecimal amountTotal = BigDecimal.ZERO; BigDecimal baseAmount = BigDecimal.ZERO; BigDecimal savedQuantity = BigDecimal.ZERO; InvoiceItemEntity baseEntity = null; InvoiceItemEntity overageEntity = null; //Logger.print("Before loop."); for (InvoiceItemEntity eInvoiceItem : eUsageItemsValid) { Logger.print("in loop0" + eInvoiceItem.getRPId()); if (!eInvoiceItem.getRPId().equals(savedRPId)) { if (itemsCollectionIndex != 0) { Logger.print("in if 1"); if (!skipDelete) { /* //add base usage baseEntity = new InvoiceItemEntity(); baseEntity.setAccountId(savedAccountId); finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3; results = zApiClient.getBaseQuantity(finalquery); baseEntity.setQuantity(results[0]); baseAmount = results[1]; baseEntity.setUOM(savedBaseUOM); baseEntity.setServiceEnddt(savedServiceEndDt); //Logger.print("setting invoice id base: "+savedInvoiceId); baseEntity.setInvoiceId(savedInvoiceId); baseEntity.setTargetDate(savedTargetDt); baseEntity.setInvoicedate(savedInvoiceDt); newUsageCollection.add(baseEntity); */ //add overage usage BigDecimal overageQnty = amountTotal.subtract(baseAmount); if (overageQnty.compareTo(BigDecimal.ZERO) > 0) { overageEntity = new InvoiceItemEntity(); overageEntity.setAccountId(savedAccountId); Logger.print("setting invoice id over: " + savedInvoiceId); overageEntity.setInvoiceId(savedInvoiceId); overageEntity.setQuantity(overageQnty); overageEntity.setUOM(savedOverUOM); overageEntity.setServiceEnddt(savedServiceEndDt); overageEntity.setTargetDate(savedTargetDt); overageEntity.setInvoicedate(savedInvoiceDt); Logger.print("added to collection, overage: " + overageEntity.getQuantity()); newUsageCollection.add(overageEntity); } } skipDelete = false; amountTotal = BigDecimal.ZERO; baseAmount = BigDecimal.ZERO; } savedRPId = eInvoiceItem.getRPId(); savedPRPCId = eInvoiceItem.getPRPCId(); savedAccountId = eInvoiceItem.getAccountId(); if (!eInvoiceItem.getInvoiceId().equals(savedInvoiceId)) { Logger.print("getting usage for invoice: " + eInvoiceItem.getInvoiceId()); deleteUOMs = zApiClient.getUsageForDelete( "select id, uom from usage where invoiceid = '" + eInvoiceItem.getInvoiceId() + "'"); savedInvoiceId = eInvoiceItem.getInvoiceId(); } savedInvoiceDt = eInvoiceItem.getInvoicedate(); savedTargetDt = eInvoiceItem.getTargetDate(); savedServiceEndDt = eInvoiceItem.getServiceEnddt(); if (eInvoiceItem.getFeeFlag().equals("B")) { savedBaseUOM = eInvoiceItem.getUOM(); basePRPCId = eInvoiceItem.getPRPCId(); } if (eInvoiceItem.getFeeFlag().equals("O")) { savedOverUOM = eInvoiceItem.getUOM(); } savedBaseUOM = null; savedOverUOM = null; savedQuantity = BigDecimal.ZERO; } Logger.print("In loop1"); savedRPId = eInvoiceItem.getRPId(); //Logger.print("In loop2"); savedPRPCId = eInvoiceItem.getPRPCId(); //Logger.print("In loop3"); savedAccountId = eInvoiceItem.getAccountId(); //Logger.print("In loop4"); savedInvoiceDt = eInvoiceItem.getInvoicedate(); //Logger.print("In loop6"); savedTargetDt = eInvoiceItem.getTargetDate(); //Logger.print("In loop7"); savedServiceEndDt = eInvoiceItem.getServiceEnddt(); //Logger.print("In loop8"); if (eInvoiceItem.getFeeFlag().equals("B")) { Logger.print("setting base UOM"); basePRPCId = eInvoiceItem.getPRPCId(); //add base usage finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3; result = zApiClient.getBaseQuantity(finalquery); Logger.print("setting base UOM"); Logger.print( "curr line quantity: " + eInvoiceItem.getQuantity() + " base quantity: " + savedQuantity); if (result.compareTo(BigDecimal.ZERO) > 0 && eInvoiceItem.getQuantity().compareTo(savedQuantity) < 0) { //Logger.print("setting invoice id base1: "); savedBaseUOM = eInvoiceItem.getUOM(); //Logger.print("setting invoice id base2: "); baseEntity = new InvoiceItemEntity(); baseEntity.setAccountId(savedAccountId); //Logger.print("setting invoice id base3: "); //result baseEntity.setQuantity(savedQuantity); baseAmount = savedQuantity.multiply(result); baseEntity.setUOM(savedBaseUOM); baseEntity.setServiceEnddt(savedServiceEndDt); Logger.print("setting invoice id base: " + savedInvoiceId); baseEntity.setInvoiceId(savedInvoiceId); baseEntity.setTargetDate(savedTargetDt); baseEntity.setInvoicedate(savedInvoiceDt); newUsageCollection.add(baseEntity); } } if (eInvoiceItem.getLicenseFlag().equals("True")) { savedQuantity = eInvoiceItem.getQuantity(); Logger.print("within license flag, quantity set to :" + savedQuantity); } if (eInvoiceItem.getFeeFlag().equals("O")) { Logger.print("setting over UOM"); savedOverUOM = eInvoiceItem.getUOM(); } if (eInvoiceItem.getFeeFlag().equals("") && eInvoiceItem.getLicenseFlag().equals("")) { Logger.print("setting usage " + savedBaseUOM); if (savedBaseUOM == null) { skipDelete = true; } else { Logger.print("setting usage1"); amountTotal = amountTotal.add(eInvoiceItem.getAmount()); Logger.print("setting usage2: " + eInvoiceItem.getInvoiceId() + " saved: " + savedInvoiceId); if (!eInvoiceItem.getInvoiceId().equals(savedInvoiceId)) { Logger.print("setting usage3"); deleteUOMs = zApiClient.getUsageForDelete("select id, uom from usage where invoiceid = '" + eInvoiceItem.getInvoiceId() + "'"); Logger.print("deleted list: " + deleteUOMs.size()); savedInvoiceId = eInvoiceItem.getInvoiceId(); } Logger.print("before usage loop" + deleteUOMs.size()); if (deleteUOMs.size() >= 1 && deleteUOMs.get(0).getUOM() != null) { for (Usage usage : deleteUOMs) { Logger.print("in loop, usage UOM: " + usage.getUOM() + " invoice UOM: " + eInvoiceItem.getUOM()); if (usage.getUOM().equals(eInvoiceItem.getUOM())) { deleteList.add(usage.getId()); Logger.print("added to delete list: " + usage.getUOM()); break; } } } } } itemsCollectionIndex++; Logger.print("done setting usage"); } if (!skipDelete) { /* //add base usage baseEntity = new InvoiceItemEntity(); baseEntity.setAccountId(savedAccountId); Logger.print("after loop1"); finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3; results = zApiClient.getBaseQuantity(finalquery); baseEntity.setQuantity(results[0]); baseAmount = results[1]; Logger.print("after loop2"); baseEntity.setUOM(savedBaseUOM); baseEntity.setServiceEnddt(savedServiceEndDt); Logger.print("setting invoice id base: "+savedInvoiceId); baseEntity.setInvoiceId(savedInvoiceId); baseEntity.setTargetDate(savedTargetDt); baseEntity.setInvoicedate(savedInvoiceDt); newUsageCollection.add(baseEntity); Logger.print("after loop3"); //add overage usage */ BigDecimal overageQnty = amountTotal.subtract(baseAmount); if (overageQnty.compareTo(BigDecimal.ZERO) > 0) { overageEntity = new InvoiceItemEntity(); overageEntity.setAccountId(savedAccountId); Logger.print("after loop3.1"); //Logger.print("setting invoice id over: "+savedInvoiceId); overageEntity.setInvoiceId(savedInvoiceId); //Logger.print("after loop3.2"); //Logger.print("after loop3.3"); overageEntity.setQuantity(overageQnty); //Logger.print("after loop4"); overageEntity.setUOM(savedOverUOM); //Logger.print("after loop4.1"); overageEntity.setServiceEnddt(savedServiceEndDt); //Logger.print("after loop4.2"); overageEntity.setTargetDate(savedTargetDt); //Logger.print("after loop4.3"); overageEntity.setInvoicedate(savedInvoiceDt); //Logger.print("after loop4.4"); Logger.print("added to collection, overage: " + overageEntity.getQuantity()); newUsageCollection.add(overageEntity); //Logger.print("after loop5"); } skipDelete = false; } amountTotal = BigDecimal.ZERO; baseAmount = BigDecimal.ZERO; //writer.close(); }
From source file:com.esd.cs.audit.AuditsController.java
/** * ??/*from ww w . jav a 2 s . c om*/ * * @param calculateModel * @return */ @RequestMapping(value = "/calculate", method = RequestMethod.POST) @ResponseBody public CalculateModel calculateModel(CalculateModel calculateModel) { logger.debug(calculateModel.toString()); Integer companyId = calculateModel.getCompanyId(); String year = calculateModel.getYear(); AuditParameter auditParameter = auditParameterService.getByYear(year); // ? Integer zaiZhiYuanGongZongShu = calculateModel.getZaiZhiYuanGongZongShu(); if (zaiZhiYuanGongZongShu == null) { zaiZhiYuanGongZongShu = 0; } // BigDecimal putScale = auditParameter.getPutScale(); // // =????* BigDecimal yingAnPaiCanJiRen = putScale.multiply(new BigDecimal(zaiZhiYuanGongZongShu)).setScale(2, BigDecimal.ROUND_HALF_UP); calculateModel.setYingAnPaiCanJiRen(yingAnPaiCanJiRen);// // ======================================================================================== // Integer yiLuRuCanJiRen = calculateModel.getYiLuRuCanJiRen(); // ??? List<WorkerCalculator> list = auditParameterService.getSpecialSetting(year); for (WorkerCalculator workerCalculator : list) { Integer per = workerCalculator.getPer().intValue(); Integer type = workerCalculator.getType(); Integer lvl = workerCalculator.getLvl(); Integer num = auditParameterService.getSpecialCount(companyId, year, type, lvl); logger.debug("type:{},lvl:{},per:{}", type, lvl, per); yiLuRuCanJiRen = ((yiLuRuCanJiRen - num) + (num * per)); } // Integer yuDingCanJiRen = calculateModel.getYuDingCanJiRen(); // Integer yiAnPaiCanJiRen = yiLuRuCanJiRen + yuDingCanJiRen; calculateModel.setYiAnPaiCanJiRen(yiAnPaiCanJiRen);// ; // ========================================================================================= // ?? BigDecimal averageSalary = auditParameter.getAverageSalary(); // ? // ??*() BigDecimal yingJiaoJinE = averageSalary .multiply(yingAnPaiCanJiRen.subtract(new BigDecimal(yiAnPaiCanJiRen))); if (yingJiaoJinE.signum() == 1) {// 0 calculateModel.setYingJiaoJinE(yingJiaoJinE); } else { yingJiaoJinE = Constants.ZERO; calculateModel.setYingJiaoJinE(yingJiaoJinE); } // ?? BigDecimal jianJiaoJinE = calculateModel.getJianJiaoJinE(); // ?=?-?? BigDecimal shiJiaoJinE = yingJiaoJinE.subtract(jianJiaoJinE); // ? --------? // ============================================================? List<AccountModel> qianJiaoMingXi = new ArrayList<AccountModel>(); BigDecimal qianJiao = getSectionPaid(year, companyId, qianJiaoMingXi); calculateModel.setQianJiaoMingXi(qianJiaoMingXi); // ============================================================ List<AccountModel> weiShenMingXi = new ArrayList<AccountModel>(); BigDecimal weiShen = getUnAudits(year, companyId, new BigDecimal(zaiZhiYuanGongZongShu), weiShenMingXi); calculateModel.setWeiShenMingXi(weiShenMingXi); // ============================================================= List<AccountModel> weiJiaoMingXi = new ArrayList<AccountModel>(); BigDecimal weiJiao = getUnpaid(year, companyId, weiJiaoMingXi); calculateModel.setWeiJiaoMingXi(weiJiaoMingXi); // ==================================================================? logger.debug("qianJiao:{} weiShen:{} weiJiao{}", qianJiao, weiShen, weiJiao); // ? =++ BigDecimal shangNianDuWeiJiaoBaoZhangJin = qianJiao.add(weiShen).add(weiJiao); calculateModel.setShangNianDuWeiJiaoBaoZhangJin(shangNianDuWeiJiaoBaoZhangJin); // ===================================================================================================== // ?=?-??+?+? BigDecimal real_yingJiaoJinE = shiJiaoJinE.add(shangNianDuWeiJiaoBaoZhangJin); // BigDecimal real_yingJiaoJinE = shiJiaoJinE; calculateModel.setShiJiaoJinE(real_yingJiaoJinE);// ? // ============================================================================================ // Date date = auditParameter.getAuditDelayDate(); // BigDecimal zhiNaJinBiLi = auditParameter.getAuditDelayRate(); // int zhiNanJinTianshu = CalendarUtil.getDaySub(date, new Date()); if (zhiNanJinTianshu < 0) { zhiNanJinTianshu = 0; } calculateModel.setZhiNaJinTianShu(zhiNanJinTianshu);// // BigDecimal zhiNaJin = real_yingJiaoJinE.multiply(zhiNaJinBiLi).multiply(new BigDecimal(zhiNanJinTianshu)); // ?? Boolean mian = calculateModel.getMianZhiNaJin(); if (mian) { zhiNaJin = new BigDecimal(0.00); } calculateModel.setZhiNaJin(zhiNaJin);// // =============================================================================================== // ?=?+ BigDecimal shiJiaoZongJinE = real_yingJiaoJinE.add(zhiNaJin); Boolean mianJiao = calculateModel.getMianJiao();// ??? if (mianJiao) { shiJiaoZongJinE = new BigDecimal(0.00); } calculateModel.setShiJiaoZongJinE(shiJiaoZongJinE); return calculateModel; }
From source file:org.egov.ptis.domain.service.report.ReportService.java
/** * This method gives the defaulters information * @param propertyViewList//from www . j av a 2s . com * @return list */ @ReadOnly public List<DefaultersInfo> getDefaultersInformation(final Query query, final String noofyrs, final Integer limit) { final List<DefaultersInfo> defaultersList = new ArrayList<>(); final List<DefaultersInfo> defaultersListForYrs = new ArrayList<>(); DefaultersInfo defaultersInfo; BigDecimal totalDue; BigDecimal currPenalty; BigDecimal currPenaltyColl; int count = 1; int reqyr = 0; final List<PropertyMaterlizeView> propertyViewList = query.list(); for (final PropertyMaterlizeView propView : propertyViewList) { if (isCountInLimit(limit, count)) break; defaultersInfo = getInstDmdInfo(propView); defaultersInfo.setSlNo(count); defaultersInfo.setAssessmentNo(propView.getPropertyId()); defaultersInfo.setOwnerName(getOwerName(propView)); defaultersInfo.setWardName(propView.getWard().getName()); defaultersInfo.setHouseNo(propView.getHouseNo()); defaultersInfo.setLocality(getLocality(propView)); defaultersInfo.setMobileNumber(getMobileNo(propView)); defaultersInfo.setArrearsDue(propView.getAggrArrDmd().subtract(propView.getAggrArrColl())); defaultersInfo.setCurrentDue(propView.getAggrCurrFirstHalfDmd().add(propView.getAggrCurrSecondHalfDmd()) .subtract(propView.getAggrCurrFirstHalfColl().add(propView.getAggrCurrSecondHalfColl()))); defaultersInfo.setAggrArrearPenalyDue(getAggArrPenaltyDue(propView)); currPenalty = getAggCurrFirstHalfPenalty(propView).add(getAggCurrSecHalfPenalty(propView)); currPenaltyColl = getAggCurrFirstHalfPenColl(propView).add(getAggCurrSecHalfPenColl(propView)); defaultersInfo.setAggrCurrPenalyDue(currPenalty.subtract(currPenaltyColl)); totalDue = defaultersInfo.getArrearsDue().add(defaultersInfo.getCurrentDue()) .add(defaultersInfo.getAggrArrearPenalyDue()).add(defaultersInfo.getAggrCurrPenalyDue()); defaultersInfo.setTotalDue(totalDue); int yrs = 0; if (isNotMoreThanFiveYrs(noofyrs)) { reqyr = Integer.parseInt(noofyrs.substring(0, 1)); yrs = propertyTaxUtil.getNoOfYears(defaultersInfo.getMinDate(), defaultersInfo.getMaxDate()); } if (isNotMoreThanFiveYrs(noofyrs) && reqyr >= yrs) { defaultersListForYrs.add(defaultersInfo); count++; } else if (noofyrs == null || noofyrs != null && ABOVE_FIVE_YEARS.equalsIgnoreCase(noofyrs)) { defaultersList.add(defaultersInfo); count++; } } return defaultersListForYrs.isEmpty() ? defaultersList : defaultersListForYrs; }
From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java
private ArrayList<HashMap<String, String>> calculateAccDefPlan(Period startingPeriod, int periodNumber, BigDecimal amount, String strCurrencyId) { Period period = startingPeriod; Date date = period.getEndingDate(); ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>(); int i = 1;// ww w . j a v a 2s .c o m BigDecimal total = BigDecimal.ZERO; int stdPrecision = 0; OBContext.setAdminMode(true); try { stdPrecision = OBDal.getInstance().get(Currency.class, this.C_Currency_ID).getStandardPrecision() .intValue(); } finally { OBContext.restorePreviousMode(); } BigDecimal periodAmount = amount .divide(new BigDecimal(periodNumber), new MathContext(32, RoundingMode.HALF_UP)) .setScale(stdPrecision, BigDecimal.ROUND_HALF_UP); while (i <= periodNumber) { if (!OBDateUtils.formatDate(date).equals(DateAcct)) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("date", OBDateUtils.formatDate(date)); hm.put("amount", i == periodNumber ? amount.subtract(total).toString() : periodAmount.toString()); plan.add(hm); } try { AcctServerData[] data = AcctServerData.periodOpen(connectionProvider, AD_Client_ID, DocumentType, AD_Org_ID, OBDateUtils.formatDate(period.getEndingDate())); if ("".equals(data[0].period)) { setStatus(STATUS_PeriodClosed); throw new OBException("@PeriodNotAvailable@"); } } catch (ServletException e) { log4j.warn("DocInvoice - Error checking period open.", e); e.printStackTrace(); } if (i < periodNumber) { period = AccDefUtility.getNextPeriod(period); date = period.getEndingDate(); } total = total.add(periodAmount); i++; } return plan; }
From source file:org.impotch.calcul.impot.cantonal.ge.pp.avant2010.BaremePrestationCapital2009Test.java
private void test(int revenu, String tauxEnPourcent) { RecepteurMultipleImpot recepteur = recepteur("IBR", "RIBR", "CAR", "RCAR", "ADR", "COR"); FournisseurAssiettePeriodique fournisseur = this.creerAssiettes(2009, revenu); producteur2009.produireImpot(situationCelibataire, fournisseur, recepteur); BigDecimal valeurImpot = getValeur(recepteur, "TOTAL"); // On prend les bornes Sup et Inf BigDecimal borneSup = valeurImpot.add(deltaSurMontantImpotCalcule); BigDecimal borneInf = valeurImpot.subtract(deltaSurMontantImpotCalcule); BigDecimal tauxCalculeSup = borneSup.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5, BigDecimal.ROUND_HALF_UP); BigDecimal tauxCalculeInf = borneInf.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5, BigDecimal.ROUND_HALF_UP); BigDecimal tauxAttendu = new BigDecimal(tauxEnPourcent); assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxSup " + tauxCalculeSup, 0 >= tauxAttendu.compareTo(tauxCalculeSup)); assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxInf " + tauxCalculeInf, 0 >= tauxCalculeInf.compareTo(tauxAttendu)); }