List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.totschnig.myexpenses.task.CsvImportTask.java
@Override protected Result doInBackground(Void... params) { int totalImported = 0, totalDiscarded = 0, totalFailed = 0; Account a;/* w w w . j av a 2s . c o m*/ if (accountId == 0) { a = new Account(); a.currency = mCurrency; a.label = MyApplication.getInstance().getString(R.string.pref_import_title, "CSV"); a.type = mAccountType; a.save(); accountId = a.getId(); } else { a = Account.getInstanceFromDb(accountId); } int columnIndexAmount = findColumnIndex(R.string.amount); int columnIndexExpense = findColumnIndex(R.string.expense); int columnIndexIncome = findColumnIndex(R.string.income); int columnIndexDate = findColumnIndex(R.string.date); int columnIndexPayee = findColumnIndex(R.string.payer_or_payee); int columnIndexNotes = findColumnIndex(R.string.comment); int columnIndexCategory = findColumnIndex(R.string.category); int columnIndexSubcategory = findColumnIndex(R.string.subcategory); int columnIndexMethod = findColumnIndex(R.string.method); int columnIndexStatus = findColumnIndex(R.string.status); int columnIndexNumber = findColumnIndex(R.string.reference_number); int columnIndexSplit = findColumnIndex(R.string.split_transaction); boolean isSplitParent = false, isSplitPart = false; Transaction t; Long splitParent = null; for (int i = 0; i < data.size(); i++) { long transferAccountId = -1; if (discardedRows.get(i, false)) { totalDiscarded++; } else { CSVRecord record = data.get(i); BigDecimal amount; String categoryInfo = null; if (columnIndexSplit != -1) { if (isSplitParent) { isSplitPart = saveGetFromRecord(record, columnIndexSplit) .equals(SplitTransaction.CSV_PART_INDICATOR); isSplitParent = false; } else { isSplitParent = saveGetFromRecord(record, columnIndexSplit) .equals(SplitTransaction.CSV_INDICATOR); } } try { if (columnIndexAmount != -1) { amount = QifUtils.parseMoney(saveGetFromRecord(record, columnIndexAmount), mCurrency); } else { BigDecimal income = columnIndexIncome != -1 ? QifUtils.parseMoney(saveGetFromRecord(record, columnIndexIncome), mCurrency).abs() : new BigDecimal(0); BigDecimal expense = columnIndexExpense != -1 ? QifUtils.parseMoney(saveGetFromRecord(record, columnIndexExpense), mCurrency) .abs() : new BigDecimal(0); amount = income.subtract(expense); } } catch (IllegalArgumentException e) { return new Result(false, "Amounts in data exceed storage limit"); } Money m = new Money(a.currency, amount); if (!isSplitParent && columnIndexCategory != -1) { String category = saveGetFromRecord(record, columnIndexCategory); if (!category.equals("")) { String subCategory = columnIndexSubcategory != -1 ? saveGetFromRecord(record, columnIndexSubcategory) : ""; if (category.equals(MyApplication.getInstance().getString(R.string.transfer)) && !subCategory.equals("") && QifUtils.isTransferCategory(subCategory)) { transferAccountId = Account.findAny(subCategory.substring(1, subCategory.length() - 1)); } else if (QifUtils.isTransferCategory(category)) { transferAccountId = Account.findAny(category.substring(1, category.length() - 1)); } if (transferAccountId == -1) { categoryInfo = category; if (!subCategory.equals("")) { categoryInfo += ":" + subCategory; } } } } if (isSplitPart) { if (transferAccountId != -1) { t = SplitPartTransfer.getNewInstance(accountId, m.getAmountMinor(), splitParent); t.transfer_account = transferAccountId; } else { t = new SplitPartCategory(accountId, m.getAmountMinor(), splitParent); } } else { if (isSplitParent) { t = new SplitTransaction(accountId, m); } else { if (transferAccountId != -1) { t = new Transfer(accountId, m); t.transfer_account = transferAccountId; } else { t = new Transaction(accountId, m); } } } if (!TextUtils.isEmpty(categoryInfo)) { new CategoryInfo(categoryInfo).insert(categoryToId); t.setCatId(categoryToId.get(categoryInfo)); } if (columnIndexDate != -1) { t.setDate(QifUtils.parseDate(saveGetFromRecord(record, columnIndexDate), dateFormat)); } if (columnIndexPayee != -1) { String payee = saveGetFromRecord(record, columnIndexPayee); if (!payee.equals("")) { long id = Payee.extractPayeeId(payee, payeeToId); if (id != -1) { payeeToId.put(payee, id); t.payeeId = id; } } } if (columnIndexNotes != -1) { t.comment = saveGetFromRecord(record, columnIndexNotes); } if (columnIndexMethod != -1) { String method = saveGetFromRecord(record, columnIndexMethod); if (!method.equals("")) { for (PaymentMethod.PreDefined preDefined : PaymentMethod.PreDefined.values()) { if (preDefined.getLocalizedLabel().equals(method)) { method = preDefined.name(); break; } } long methodId = PaymentMethod.find(method); if (methodId != -1) { t.methodId = methodId; } } } if (columnIndexStatus != -1) { t.crStatus = Transaction.CrStatus.fromQifName(saveGetFromRecord(record, columnIndexStatus)); } if (columnIndexNumber != -1) { t.referenceNumber = saveGetFromRecord(record, columnIndexNumber); } if (t.save() != null) { if (isSplitParent) { splitParent = t.getId(); } if (!isSplitPart) { totalImported++; } } else { totalFailed++; } if (totalImported % 10 == 0) { publishProgress(totalImported); } } } return new Result(true, 0, Integer.valueOf(totalImported), Integer.valueOf(totalFailed), Integer.valueOf(totalDiscarded), a.label); }
From source file:org.libreplan.business.qualityforms.entities.QualityForm.java
private void updatePercentageByItems() { if (qualityFormItems.size() > 0) { BigDecimal percentageTotal = new BigDecimal(100).setScale(2); BigDecimal numItems = new BigDecimal(qualityFormItems.size()).setScale(2); BigDecimal percentageByItem = percentageTotal.divide(numItems, 2, BigDecimal.ROUND_DOWN); for (QualityFormItem item : qualityFormItems) { item.setPercentage(percentageByItem); }//ww w . j a v a 2 s . c o m // Calculate the division remainder BigDecimal sumByItems = (percentageByItem.multiply(numItems)).setScale(2); BigDecimal remainder = (percentageTotal.subtract(sumByItems)).setScale(2); QualityFormItem lastItem = qualityFormItems.get(qualityFormItems.size() - 1); BigDecimal lastPercentage = (lastItem.getPercentage().add(remainder)).setScale(2); lastItem.setPercentage(lastPercentage); } }
From source file:nl.strohalm.cyclos.services.transactions.LoanServiceImpl.java
private Transfer doRepay(final RepayLoanDTO params) { BigDecimal amount = params.getAmount(); // Check if the amount is valid if (amount.compareTo(paymentService.getMinimumPayment()) < 0) { throw new ValidationException("amount", "loan.amount", new InvalidError()); }// ww w . j av a 2 s . c o m // Get the loan payment to repay Calendar date = params.getDate(); if (date == null) { date = Calendar.getInstance(); params.setDate(date); } final LoanRepaymentAmountsDTO amountsDTO = getLoanPaymentAmount(params); final LoanPayment payment = amountsDTO.getLoanPayment(); if (payment == null) { throw new UnexpectedEntityException(); } // Validate the amount final BigDecimal remainingAmount = amountsDTO.getRemainingAmountAtDate(); final BigDecimal diff = remainingAmount.subtract(amount); final MutableBoolean totallyRepaid = new MutableBoolean(); // If the amount is on an acceptable delta, set the transfer value = parcel value if (diff.abs().floatValue() < PRECISION_DELTA) { amount = remainingAmount; totallyRepaid.setValue(true); } else if (diff.compareTo(BigDecimal.ZERO) < 0 || !params.getLoan().getTransfer().getType().getLoan().getType().allowsPartialRepayments()) { throw new ValidationException("amount", "loan.amount", new InvalidError()); } final LocalSettings localSettings = settingsService.getLocalSettings(); Loan loan = fetchService.fetch(params.getLoan(), Loan.Relationships.PAYMENTS, RelationshipHelper .nested(Loan.Relationships.TRANSFER, Payment.Relationships.TO, MemberAccount.Relationships.MEMBER), Loan.Relationships.TO_MEMBERS); // Build the transfers for repayment final List<TransferDTO> transfers = handlersByType.get(loan.getParameters().getType()) .buildTransfersForRepayment(params, amountsDTO); Transfer root = null; BigDecimal totalAmount = BigDecimal.ZERO; for (final TransferDTO dto : transfers) { if (dto.getAmount().floatValue() < PRECISION_DELTA) { // If the root amount is zero, it means that the parent transfer should be the last transfer for this loan payment final TransferQuery tq = new TransferQuery(); tq.setLoanPayment(payment); tq.setReverseOrder(true); tq.setUniqueResult(); final List<Transfer> paymentTransfers = paymentService.search(tq); if (paymentTransfers.isEmpty()) { throw new IllegalStateException( "The root transfer has amount 0 and there is no other transfers for this payment"); } root = paymentTransfers.iterator().next(); } else { totalAmount = totalAmount.add(dto.getAmount()); dto.setParent(root); dto.setLoanPayment(payment); final Transfer transfer = (Transfer) paymentService.insertWithoutNotification(dto); if (root == null) { // The first will be the root. All others are it's children root = transfer; } } } // Update the loan payment final BigDecimal totalRepaid = localSettings.round(payment.getRepaidAmount().add(totalAmount)); payment.setRepaidAmount(totalRepaid); if (totallyRepaid.booleanValue()) { // Mark the payment as repaid, if is the case payment.setStatus(LoanPayment.Status.REPAID); payment.setRepaymentDate(params.getDate()); } payment.setTransfers(null); // Avoid 2 representations of the transfers collection. It's inverse="true", no problem setting null loanPaymentDao.update(payment); // Return the generated root transfer return root; }
From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java
/** * Method is executed on update trigger for the amount field in the debit * and credit table inside the transaction form. * * @param _parameter Parameter as passed from the eFaps API * @return list for update trigger// w w w . j a va 2 s .com * @throws EFapsException on error */ public Return update4Amount(final Parameter _parameter) throws EFapsException { final Return retVal = new Return(); try { final String postfix = getProperty(_parameter, "TypePostfix"); final String[] amounts = _parameter.getParameterValues("amount_" + postfix); final String[] rates = _parameter.getParameterValues("rate_" + postfix); final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX); final int pos = getSelectedRow(_parameter); final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8); final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter(); final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(amounts[pos]); BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(rates[pos]); final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]); if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) { rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP); } final List<Map<String, String>> list = new ArrayList<>(); final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter); final BigDecimal sum = getSum4UI(_parameter, postfix, null, null); final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit"; final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null); final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol(); final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " " + new Period().getCurrency(periodInstance).getSymbol(); final Map<String, String> map = new HashMap<>(); map.put("sum" + postfix, sumStr); map.put("amountRate_" + postfix, formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP))); map.put("sumTotal", sumStr2); list.add(map); retVal.put(ReturnValues.VALUES, list); } catch (final ParseException e) { throw new EFapsException(Transaction_Base.class, "update4Amount.ParseException", e); } return retVal; }
From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java
/** * Method is executed on update trigger for the rate field in the debit * and credit table inside the transaction form. * * @param _parameter Parameter as passed from the eFaps API * @return list for update trigger//from w ww . j av a 2 s .c om * @throws EFapsException on error */ public Return update4Rate(final Parameter _parameter) throws EFapsException { final Return retVal = new Return(); try { final String postfix = getProperty(_parameter, "TypePostfix"); final String[] amounts = _parameter.getParameterValues("amount_" + postfix); final String[] rates = _parameter.getParameterValues("rate_" + postfix); final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX); final int pos = getSelectedRow(_parameter); final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8); final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter(); final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(amounts[pos]); BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ONE : (BigDecimal) rateFormater.parse(rates[pos]); final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]); if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) { rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP); } final List<Map<String, String>> list = new ArrayList<>(); final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter); final BigDecimal sum = getSum4UI(_parameter, postfix, null, null); final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit"; final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null); final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol(); final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " " + new Period().getCurrency(periodInstance).getSymbol(); final Map<String, String> map = new HashMap<>(); map.put("sum" + postfix, sumStr); map.put("amountRate_" + postfix, formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP))); map.put("sumTotal", sumStr2); list.add(map); retVal.put(ReturnValues.VALUES, list); } catch (final ParseException e) { throw new EFapsException(Transaction_Base.class, "update4Rate.ParseException", e); } return retVal; }
From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java
/** * Executed on update event of the currency field. * @param _parameter parameter as passed from the eFaps API * @return list of maps as needed by the update event * @throws EFapsException on error// ww w . j a va2 s.c om */ public Return update4Currency(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); try { final String postfix = getProperty(_parameter, "TypePostfix"); final String[] currIds = _parameter.getParameterValues("rateCurrencyLink_" + postfix); final String[] amounts = _parameter.getParameterValues("amount_" + postfix); final int pos = getSelectedRow(_parameter); final ExchangeConfig exConf = getExchangeConfig(_parameter, null); final DateTime date; switch (exConf) { case DOCDATEPURCHASE: case DOCDATESALE: final Instance docInst = Instance.get(_parameter.getParameterValues("docLink_" + postfix)[pos]); if (InstanceUtils.isValid(docInst)) { final PrintQuery print = CachedPrintQuery.get4Request(docInst); print.addAttribute(CIERP.DocumentAbstract.Date); print.execute(); date = print.getAttribute(CIERP.DocumentAbstract.Date); } else { final String dateStr = _parameter.getParameterValue("date_eFapsDate"); date = DateUtil.getDateFromParameter(dateStr); } break; case TRANSDATESALE: case TRANSDATEPURCHASE: default: final String dateStr = _parameter.getParameterValue("date_eFapsDate"); date = DateUtil.getDateFromParameter(dateStr); break; } final boolean sale = ExchangeConfig.TRANSDATESALE.equals(exConf) || ExchangeConfig.DOCDATESALE.equals(exConf); final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter); final RateInfo rate = evaluateRate(_parameter, periodInstance, date, Instance.get(CIERP.Currency.getType(), currIds[pos])); final DecimalFormat rateFormater = sale ? rate.getFormatter().getFrmt4SaleRateUI() : rate.getFormatter().getFrmt4RateUI(); final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter(); final BigDecimal amountRate = amounts[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(amounts[pos]); final BigDecimal sum = getSum4UI(_parameter, postfix, pos, rate); final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit"; final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null); final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol(); final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " " + new Period().getCurrency(periodInstance).getSymbol(); final List<Map<String, String>> list = new ArrayList<>(); final Map<String, String> map = new HashMap<>(); map.put("rate_" + postfix, sale ? rate.getSaleRateUIFrmt() : rate.getRateUIFrmt()); map.put("rate_" + postfix + RateUI.INVERTEDSUFFIX, "" + rate.isInvert()); map.put("sum" + postfix, sumStr); map.put("amountRate_" + postfix, formater.format(amountRate.setScale(12) .divide(sale ? rate.getSaleRate() : rate.getRate(), BigDecimal.ROUND_HALF_UP))); map.put("sumTotal", sumStr2); list.add(map); ret.put(ReturnValues.VALUES, list); } catch (final ParseException e) { throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e); } return ret; }
From source file:org.egov.works.contractorbill.service.ContractorBillRegisterService.java
public void validateRefundAmount(final ContractorBillRegister contractorBillRegister, final BindingResult resultBinder) { int index = 0; for (final EgBilldetails egBillDetail : contractorBillRegister.getRefundBillDetails()) { if (egBillDetail.getGlcodeid() != null && egBillDetail.getDebitamount() == null) resultBinder.rejectValue("refundBillDetails[" + index + "].debitamount", "error.refundamount.required"); if (egBillDetail.getDebitamount() != null && egBillDetail.getGlcodeid() == null) resultBinder.rejectValue("refundBillDetails[" + index + "].glcodeid", "error.refundaccountcode.required"); if (egBillDetail.getGlcodeid() != null && egBillDetail.getDebitamount() != null) { final CChartOfAccounts coa = chartOfAccountsHibernateDAO .findById(egBillDetail.getGlcodeid().longValue(), false); final String amounts = getTotalDebitAndCreditAmountByAccountCode( contractorBillRegister.getWorkOrderEstimate().getId(), new BigDecimal(coa.getId()), contractorBillRegister.getId() != null ? contractorBillRegister.getId() : -1); if (!org.apache.commons.lang.StringUtils.isBlank(amounts)) { final String[] creditDebitAmounts = amounts.split(","); BigDecimal withheldAmount = BigDecimal.ZERO; BigDecimal refundedAmount = BigDecimal.ZERO; if (!creditDebitAmounts[0].equals("0")) withheldAmount = new BigDecimal(creditDebitAmounts[0]); if (!creditDebitAmounts[1].equals("0")) refundedAmount = new BigDecimal(creditDebitAmounts[1]); if (withheldAmount.equals("0")) resultBinder.reject("error.contractorBill.nowithheldtorefund", new String[] { coa.getGlcode() }, null); else { final BigDecimal validRefundAmount = egBillDetail.getDebitamount().add(refundedAmount); final BigDecimal diffAmount = validRefundAmount.subtract(withheldAmount); if (validRefundAmount.compareTo(new BigDecimal(creditDebitAmounts[0])) == 1 && !contractorBillRegister.getWorkOrderEstimate().getEstimate() .getLineEstimateDetails().getLineEstimate().isSpillOverFlag()) resultBinder.reject("error.contractorBill.validate.refundAmount", new String[] { coa.getGlcode(), diffAmount.toString() }, null); }/*from w w w . j a va2 s.c o m*/ } } index++; } }
From source file:org.ofbiz.accounting.thirdparty.paypal.PayPalServices.java
public static Map<String, Object> doExpressCheckout(DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); GenericValue userLogin = (GenericValue) context.get("userLogin"); GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId")); GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null); GenericValue payPalPaymentMethod = null; try {/* www . j a va 2 s . c om*/ payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod"); payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod"); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoExpressCheckoutPayment"); encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken")); encoder.add("PAYMENTACTION", "Order"); encoder.add("PAYERID", payPalPaymentMethod.getString("payerId")); // set the amount encoder.add("AMT", processAmount.setScale(2).toPlainString()); encoder.add("CURRENCYCODE", orh.getCurrency()); BigDecimal grandTotal = orh.getOrderGrandTotal(); BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal subTotal = processAmount.subtract(shippingTotal).subtract(taxTotal).setScale(2, BigDecimal.ROUND_HALF_UP); encoder.add("ITEMAMT", subTotal.setScale(2).toPlainString()); encoder.add("SHIPPINGAMT", shippingTotal.toPlainString()); encoder.add("TAXAMT", taxTotal.toPlainString()); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalPaymentSetting, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError("An error occurred while communicating with PayPal"); } Map<String, String> errorMessages = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errorMessages)) { if (errorMessages.containsKey("10417")) { // "The transaction cannot complete successfully, Instruct the customer to use an alternative payment method" // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_"); if (retry) { context.put("_RETRY_", false); return PayPalServices.doExpressCheckout(dctx, context); } } return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values())); } Map<String, Object> inMap = FastMap.newInstance(); inMap.put("userLogin", userLogin); inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId")); inMap.put("transactionId", decoder.get("TRANSACTIONID")); Map<String, Object> outMap = null; try { outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(outMap)) { Debug.logError(ServiceUtil.getErrorMessage(outMap), module); return outMap; } return ServiceUtil.returnSuccess(); }
From source file:org.fede.calculator.service.InvestmentServiceImpl.java
private DetailedInvestmentReportDTO investmentReport(String currency, Predicate<Investment> filter, boolean includeTotal) { if (!MAP.containsKey(currency)) { throw new IllegalArgumentException("Currency " + currency + " does not have a known inflation index."); }/*from w w w .ja v a2s. c om*/ final List<Investment> investments = this.investmentSeries.stream() .flatMap(fileName -> SeriesReader.read(fileName, TYPE_REFERENCE).stream()) .collect(Collectors.toList()); final Inflation inflation = MAP.get(currency); final YearMonth until = inflation.getTo(); final Date untilDate = until.asToDate(); MoneyAmount initialAmount = new MoneyAmount(ZERO, currency); MoneyAmount currentAmount = new MoneyAmount(ZERO, currency); final List<InvestmentReportDTO> report = new ArrayList<>(); // final String header = "item.getType().name()\t" // + "item.getInitialDate()\t" // + "itemUntilDate\t" // + "currency\t" // + "initialAmount(item, currency).getAmount()\t" // + "finalAmount\t" // + "realAmountInvested"; // // System.out.println(header); for (Investment item : investments) { if (filter.test(item)) { final Date itemUntilDate = item.getOut() == null ? untilDate : item.getOut().getDate(); final YearMonth itemUntilYearMonth = new YearMonth(itemUntilDate); if (includeTotal) { YearMonth start = new YearMonth(item.getInitialDate()); initialAmount = initialAmount .add(inflation.adjust(initialAmount(item, currency), start.getYear(), start.getMonth(), itemUntilYearMonth.getYear(), itemUntilYearMonth.getMonth())); currentAmount = currentAmount.add(finalAmount(item, currency, itemUntilDate)); } BigDecimal finalAmount = finalAmount(item, currency, itemUntilDate).getAmount(); MoneyAmount investedAmount = initialAmount(item, currency); BigDecimal realAmount = realAmount(investedAmount, currency, item.getInitialDate(), itemUntilDate); report.add(new InvestmentReportDTO(item.getType().name(), item.getInitialDate(), itemUntilDate, currency, initialAmount(item, currency).getAmount(), finalAmount, inflation(currency, item.getInitialDate(), itemUntilDate), item.getInvestment().getCurrency(), finalAmount.subtract(realAmount).setScale(2, ROUNDING_MODE), realAmount)); //String msg = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}"; //System.out.println(MessageFormat.format(msg, item.getType().name(), // item.getInitialDate(), // itemUntilDate, // currency, // initialAmount(item, currency).getAmount(), // finalAmount, realAmount)); } } Collections.sort(report, (InvestmentReportDTO o1, InvestmentReportDTO o2) -> o1.getFrom().compareTo(o2.getFrom())); return new DetailedInvestmentReportDTO(includeTotal ? new InvestmentDTO(currency, initialAmount.getAmount(), currentAmount.getAmount(), untilDate) : null, report); }
From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java
/** * Method for recalculate and return string. * * @param _parameter Parameter as passed from the eFaps API. * @param _docInst Instance of the document selected. * @return String./*from ww w .j av a 2 s .co m*/ * @throws EFapsException on error. */ protected String getRecalculateInfo(final Parameter _parameter, final Instance _docInst) throws EFapsException { final StringBuilder html = new StringBuilder(); final PrintQuery print = new PrintQuery(_docInst); print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal, CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId, CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name); print.execute(); final BigDecimal rateCross = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.RateCrossTotal); final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal); final String nameDoc = print.<String>getAttribute(CISales.DocumentSumAbstract.Name); final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(), print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId)); final Instance currentInst = Instance.get(CIERP.Currency.getType(), print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId)); final CurrencyInst tarCurr = new CurrencyInst(targetCurrInst); final CurrencyInst curr = new CurrencyInst(currentInst); final PriceUtil priceUtil = new PriceUtil(); final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst); final BigDecimal rate = rates[2]; final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP); final BigDecimal gainloss = newCrossTotal.subtract(crossTotal); final Map<String, String[]> map = validateInfo(_parameter, gainloss); final String[] accs = map.get("accs"); final String[] check = map.get("check"); html.append("<table>").append("<tr>").append("<td>").append(DBProperties.getProperty("Sales_Invoice.Label")) .append("</td>").append("<td colspan=\"2\">").append(nameDoc).append("</td>").append("</tr>") .append("<td>").append(DBProperties.getProperty("Sales_DocumentAbstract/RateCrossTotal.Label")) .append("</td>").append("<td>").append(rateCross).append(" ").append(tarCurr.getSymbol()) .append("</td>").append("<td>").append(crossTotal).append(" ").append(curr.getSymbol()) .append("</td>").append("</tr>").append("<tr>").append("<td>") .append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.newTotal.Label")) .append("</td>").append("<td colspan=\"2\" align=\"right\">").append(newCrossTotal).append(" ") .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>"); if (gainloss.compareTo(BigDecimal.ZERO) == -1) { html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.loss.Label")); } else { html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.gain.Label")); } html.append("</td>").append("<td colspan=\"2\" align=\"right\">").append(gainloss.abs()).append(" ") .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>") .append(DBProperties.getProperty("Accounting_TransactionPositionDebit.Label")).append("</td>") .append("<td colspan=\"2\" align=\"right\">"); if (checkAccounts(accs, 0, check).length() > 0) { html.append(checkAccounts(accs, 0, check)); } else { html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label")); } html.append("</td>").append("</tr>").append("<tr>").append("<td>") .append(DBProperties.getProperty("Accounting_TransactionPositionCredit.Label")).append("</td>") .append("<td colspan=\"2\" align=\"right\">"); if (checkAccounts(accs, 1, check).length() > 0) { html.append(checkAccounts(accs, 1, check)); } else { html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label")); } html.append("</td>").append("</tr>").append("</table>"); return html.toString(); }