List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java
@Override public Map<Integer, BigDecimal> findMainBedragen(List<? extends Bedragen> bedragen, String Month) { SimpleDateFormat dt = new SimpleDateFormat("MM/yyyy"); Map<GroepenSrvPojo, BigDecimal> mainBedragenPerGroup = new HashMap<GroepenSrvPojo, BigDecimal>(); for (Bedragen bedrag : bedragen) { if (dt.format(bedrag.getDatum()).equals(Month)) { GroepenSrvPojo mainGroup = new GroepenSrvPojo(GroepenSrvImpl.getHoofdGroep(bedrag.getGroep())); if (mainBedragenPerGroup.containsKey(mainGroup)) { BigDecimal ammount = mainBedragenPerGroup.get(mainGroup); if (bedrag.getGroep().getNegatief().equals(1)) { ammount = ammount.add(bedrag.getBedrag()); } else { ammount = ammount.subtract(bedrag.getBedrag()); }//from ww w . ja va 2 s.co m mainBedragenPerGroup.put(mainGroup, ammount); } else { if (bedrag.getGroep().getNegatief().equals(1)) { mainBedragenPerGroup.put(mainGroup, bedrag.getBedrag()); } else { mainBedragenPerGroup.put(mainGroup, bedrag.getBedrag().multiply(new BigDecimal(-1))); } } } } BigDecimal average = new BigDecimal(0); for (Map.Entry bedrag : mainBedragenPerGroup.entrySet()) { average = average.add((BigDecimal) bedrag.getValue()); } average = average.divide(new BigDecimal(mainBedragenPerGroup.size()), 2, RoundingMode.HALF_UP); Map<Integer, BigDecimal> result = new HashMap<Integer, BigDecimal>(); result.put(0, average); for (Map.Entry bedrag : mainBedragenPerGroup.entrySet()) { result.put(((GroepenSrvPojo) bedrag.getKey()).getPk_id(), (BigDecimal) bedrag.getValue()); } return result; }
From source file:org.cirdles.calamari.algorithms.TukeyBiweight.java
public static ValueModel calculateTukeyBiweightMean(String name, double tuningConstant, double[] values) { // guarantee termination BigDecimal epsilon = BigDecimal.ONE.movePointLeft(10); int iterationMax = 100; int iterationCounter = 0; int n = values.length; // initial mean is median BigDecimal mean = new BigDecimal(calculateMedian(values)); // initial sigma is median absolute deviation from mean = median (MAD) double deviations[] = new double[n]; for (int i = 0; i < values.length; i++) { deviations[i] = StrictMath.abs(values[i] - mean.doubleValue()); }/*from w w w. j av a 2 s.c om*/ BigDecimal sigma = new BigDecimal(calculateMedian(deviations)).max(BigDecimal.valueOf(SQUID_TINY_VALUE)); BigDecimal previousMean; BigDecimal previousSigma; do { iterationCounter++; previousMean = mean; previousSigma = sigma; // init to zeroes BigDecimal[] deltas = new BigDecimal[n]; BigDecimal[] u = new BigDecimal[n]; BigDecimal sa = BigDecimal.ZERO; BigDecimal sb = BigDecimal.ZERO; BigDecimal sc = BigDecimal.ZERO; BigDecimal tee = new BigDecimal(tuningConstant).multiply(sigma); for (int i = 0; i < n; i++) { deltas[i] = new BigDecimal(values[i]).subtract(mean); if (tee.compareTo(deltas[i].abs()) > 0) { deltas[i] = new BigDecimal(values[i]).subtract(mean); u[i] = deltas[i].divide(tee, MathContext.DECIMAL128); BigDecimal uSquared = u[i].multiply(u[i]); sa = sa.add(deltas[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)).pow(2)); sb = sb.add(BigDecimal.ONE.subtract(uSquared) .multiply(BigDecimal.ONE.subtract(new BigDecimal(5.0).multiply(uSquared)))); sc = sc.add(u[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2))); } } sigma = bigDecimalSqrtBabylonian(sa.multiply(new BigDecimal(n))).divide(sb.abs(), MathContext.DECIMAL128); sigma = sigma.max(BigDecimal.valueOf(SQUID_TINY_VALUE)); mean = previousMean.add(tee.multiply(sc).divide(sb, MathContext.DECIMAL128)); } // both tests against epsilon must pass OR iterations top out // april 2016 Simon B discovered we need 101 iterations possible, hence the "<=" below while (((sigma.subtract(previousSigma).abs().divide(sigma, MathContext.DECIMAL128).compareTo(epsilon) > 0)// || mean.subtract(previousMean).abs().divide(mean, MathContext.DECIMAL128).compareTo(epsilon) > 0)// && (iterationCounter <= iterationMax)); return new ValueModel(name, mean, "ABS", sigma); }
From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java
/** * Method to recalculate rate./*from w ww . ja va2 s . co m*/ * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return recalculateRate(final Parameter _parameter) throws EFapsException { final Instance docInst = Instance.get(_parameter.getParameterValue("docInst")); 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 DateTime dateDoc = print.<DateTime>getAttribute(CISales.DocumentSumAbstract.Date); 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"); if (checkAccounts(accs, 0, check).length() > 0 && checkAccounts(accs, 1, check).length() > 0) { if (gainloss.compareTo(BigDecimal.ZERO) != 0) { if (!tarCurr.equals(curr)) { final String[] accOids = map.get("accountOids"); final Insert insert = new Insert(CIAccounting.Transaction); final StringBuilder description = new StringBuilder(); final DateTimeFormatter formater = DateTimeFormat.mediumDate(); final String dateStr = dateDoc.withChronology(Context.getThreadContext().getChronology()) .toString(formater.withLocale(Context.getThreadContext().getLocale())); description .append(DBProperties .getProperty("Accounting_TransactionRecalculateForm.TxnRecalculate.Label")) .append(" ").append(nameDoc).append(" ").append(dateStr); insert.add(CIAccounting.Transaction.Description, description); insert.add(CIAccounting.Transaction.Date, _parameter.getParameterValue("date")); insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId()); insert.add(CIAccounting.Transaction.Status, Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId()); insert.execute(); final Instance instance = insert.getInstance(); new Create().connectDocs2Transaction(_parameter, instance, docInst); final Insert insert2 = new Insert(CIAccounting.TransactionPositionCredit); insert2.add(CIAccounting.TransactionPositionCredit.TransactionLink, instance.getId()); insert2.add(CIAccounting.TransactionPositionCredit.AccountLink, Instance.get(accOids[1]).getId()); insert2.add(CIAccounting.TransactionPositionCredit.CurrencyLink, curr.getInstance().getId()); insert2.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink, curr.getInstance().getId()); insert2.add(CIAccounting.TransactionPositionCredit.Rate, new Object[] { 1, 1 }); insert2.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs()); insert2.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs()); insert2.execute(); final Insert insert3 = new Insert(CIAccounting.TransactionPositionDebit); insert3.add(CIAccounting.TransactionPositionDebit.TransactionLink, instance.getId()); insert3.add(CIAccounting.TransactionPositionDebit.AccountLink, Instance.get(accOids[0]).getId()); insert3.add(CIAccounting.TransactionPositionDebit.CurrencyLink, curr.getInstance().getId()); insert3.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, curr.getInstance().getId()); insert3.add(CIAccounting.TransactionPositionDebit.Rate, new Object[] { 1, 1 }); insert3.add(CIAccounting.TransactionPositionDebit.RateAmount, gainloss.abs().negate()); insert3.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate()); insert3.execute(); _parameter.put(ParameterValues.INSTANCE, docInst); new Accounting4DocSum().recalculateRate(_parameter); } } } return new Return(); }
From source file:com.aan.girsang.server.service.impl.TransaksiServiceImpl.java
private void simpanHutang() { List<Supplier> suppliers = supplierDao.semua(); for (Supplier s : suppliers) { List<Pembelian> pembelians = pembelianDao.cariSupplier(s); List<PelunasanHutang> hutangs = pelunasanHutangDao.cariSupplier(s); BigDecimal hutangPembelian = new BigDecimal(0); BigDecimal pembayaranHutang = new BigDecimal(0); for (int i = 0; i < pembelians.size(); i++) { Pembelian p = pembelians.get(i); hutangPembelian = hutangPembelian.add(p.getDaftarKredit().getSisaKredit()); }/* ww w .ja va 2 s. c o m*/ for (int i = 0; i < hutangs.size(); i++) { PelunasanHutang pH = hutangs.get(i); pembayaranHutang = pembayaranHutang.add(pH.getJlhBayar()); } s.setSaldoHutang(hutangPembelian.subtract(pembayaranHutang)); supplierDao.simpan(s); } }
From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java
/** * Calculate delivery amount according to shipment sla cost and items in particular delivery. * * @param order order//from ww w . ja v a 2 s .com * @param delivery delivery * @param payment payment */ private void fillPaymentAmount(final CustomerOrder order, final CustomerOrderDelivery delivery, final Payment payment) { BigDecimal rez = BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE); PaymentLine shipmentLine = null; for (PaymentLine paymentLine : payment.getOrderItems()) { if (paymentLine.isShipment()) { shipmentLine = paymentLine; } else { // unit price already includes item level promotions rez = rez.add(paymentLine.getQuantity().multiply(paymentLine.getUnitPrice()) .setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP)); } } if (order.isPromoApplied()) { // work out the percentage of order level promotion per delivery // work out the real sub total using item promotional prices // DO NOT use the order.getListPrice() as this is the list price in catalog and we calculate // promotions against sale price BigDecimal orderTotalList = BigDecimal.ZERO; for (final CustomerOrderDet detail : order.getOrderDetail()) { orderTotalList = orderTotalList.add(detail.getQty().multiply(detail.getGrossPrice()) .setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP)); } final BigDecimal orderTotal = order.getGrossPrice(); // take the list price (sub total of items using list price) final BigDecimal discount = orderTotalList.subtract(orderTotal).divide(orderTotalList, 10, RoundingMode.HALF_UP); // scale delivery items total in accordance with order level discount percentage rez = rez.multiply(BigDecimal.ONE.subtract(discount)).setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP); } if (shipmentLine != null) { // shipping price already includes shipping level promotions rez = rez.add(shipmentLine.getUnitPrice()).setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP); } payment.setPaymentAmount(rez); payment.setOrderCurrency(order.getCurrency()); payment.setOrderLocale(order.getLocale()); }
From source file:edu.macalester.tagrelatedness.KendallsCorrelation.java
public BigDecimal get(BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); }/* www .j ava 2 s . c o m*/ BigDecimal initialGuess = getInitialApproximation(n); trace("Initial guess " + initialGuess.toString()); BigDecimal lastGuess = ZERO; BigDecimal guess = new BigDecimal(initialGuess.toString()); // Iterate iterations = 0; boolean more = true; while (more) { lastGuess = guess; guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP); guess = guess.add(lastGuess); guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP); trace("Next guess " + guess.toString()); error = n.subtract(guess.multiply(guess)); if (++iterations >= maxIterations) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; }
From source file:org.marketcetera.strategy.StrategyTestBase.java
/** * Generates FIX <code>Message</code> objects that contain execution reports for partial and/or * complete fills of the given order.//from w w w . j av a2 s . co m * * <p>The number of objects returned can be adjusted by changing the value of {@link #executionReportMultiplicity}. * Whether or not the list partially or fully fills the given order can be adjusted by changing the * value of {@link MockRecorderModule#shouldFullyFillOrders}. * * @param inOrder an <code>OrderSingle</code> value * @return a <code>List<Message></code> value * @throws Exception if an error occurs */ protected static List<Message> generateFixExecutionReports(OrderSingle inOrder) throws Exception { int multiplicity = executionReportMultiplicity; List<Message> reports = new ArrayList<Message>(); if (inOrder.getQuantity() != null) { BigDecimal totalQuantity = new BigDecimal(inOrder.getQuantity().toString()); BigDecimal lastQuantity = BigDecimal.ZERO; for (int iteration = 0; iteration < multiplicity - 1; iteration++) { BigDecimal thisQuantity = totalQuantity .subtract(totalQuantity.divide(new BigDecimal(Integer.toString(multiplicity)))); totalQuantity = totalQuantity.subtract(thisQuantity); Message rawExeReport = generateFixExecutionReport(inOrder, OrdStatus.PARTIALLY_FILLED, thisQuantity, lastQuantity, FIXVersion.FIX44); reports.add(rawExeReport); lastQuantity = thisQuantity; } Message rawExeReport = generateFixExecutionReport(inOrder, MockRecorderModule.shouldFullyFillOrders ? OrdStatus.FILLED : OrdStatus.PARTIALLY_FILLED, totalQuantity, lastQuantity, FIXVersion.FIX44); reports.add(rawExeReport); } return reports; }
From source file:org.efaps.esjp.accounting.transaction.Calculation_Base.java
/** * Calculate button./*from w w w . j a va 2 s .c o m*/ * * @param _parameter the parameter * @return the return * @throws EFapsException on error */ public Return calculateButton(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final StringBuilder js = new StringBuilder(); final int exConfOrd = Integer.parseInt(_parameter.getParameterValue("calculateConfig")); final CalculateConfig config = Accounting.CalculateConfig.values()[exConfOrd]; final Parameter parameter = ParameterUtil.clone(_parameter); switch (config) { case EXCHANGERATE: // update Rate js.append(getJS4ExchangeRate(_parameter, parameter, "Debit")) .append(getJS4ExchangeRate(_parameter, parameter, "Credit")); final BigDecimal sumDebit = getSum4UI(parameter, "Debit", null, null); final BigDecimal sumCredit = getSum4UI(parameter, "Credit", null, null); final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter(); final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter); final String sumDebitStr = formater.format(sumDebit) + " " + new Period().getCurrency(periodInstance).getSymbol(); final String sumCreditStr = formater.format(sumCredit) + " " + new Period().getCurrency(periodInstance).getSymbol(); final String sumTotalStr = formater.format(sumDebit.subtract(sumCredit).abs()) + " " + new Period().getCurrency(periodInstance).getSymbol(); js.append(getSetFieldValue(0, "sumDebit", sumDebitStr)) .append(getSetFieldValue(0, "sumCredit", sumCreditStr)) .append(getSetFieldValue(0, "sumTotal", sumTotalStr)); break; case FILLUPAMOUNT: js.append(getJS4FillUp(_parameter, parameter)); break; case FITEXRATE: js.append(getJS4FitExRate(_parameter, parameter)); break; case SUMMARIZE: js.append(getJS4Summarize(_parameter, parameter)); break; default: break; } ret.put(ReturnValues.SNIPLETT, js.toString()); return ret; }
From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java
/** * @param _parameter Parameter as passed by the eFasp API * @return new Return/*from w w w . j ava2 s . co m*/ * @throws EFapsException on error */ public Return createGainLoss4SimpleAccount(final Parameter _parameter) throws EFapsException { final PrintQuery printPer = new PrintQuery(_parameter.getInstance()); final SelectBuilder selCurrInst = SelectBuilder.get().linkto(CIAccounting.Period.CurrencyLink).instance(); printPer.addSelect(selCurrInst); printPer.addAttribute(CIAccounting.Period.FromDate, CIAccounting.Period.CurrencyLink); printPer.execute(); final DateTime dateFrom = printPer.<DateTime>getAttribute(CIAccounting.Period.FromDate); final Instance currencyInst = printPer.<Instance>getSelect(selCurrInst); final String[] relOIDs = (String[]) Context.getThreadContext() .getSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name); final DateTime dateTo = new DateTime(_parameter .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.transactionDate.name)); final DateTime dateEx = new DateTime(_parameter .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.exchangeDate.name)); Insert insert = null; BigDecimal totalSum = BigDecimal.ZERO; for (final String oid : relOIDs) { Instance tarCurInst = null; final Instance relInst = Instance.get(oid); final PrintQuery print = new PrintQuery(relInst); final SelectBuilder selAccount = new SelectBuilder() .linkto(CIAccounting.AccountConfigSimple2Period.FromLink).oid(); print.addSelect(selAccount); print.addAttribute(CIAccounting.AccountConfigSimple2Period.IsSale); if (print.execute()) { final Instance instAcc = Instance.get(print.<String>getSelect(selAccount)); final boolean isSale = print.<Boolean>getAttribute(CIAccounting.AccountConfigSimple2Period.IsSale); final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction); attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink, _parameter.getInstance()); attrQuerBldr.addWhereAttrGreaterValue(CIAccounting.Transaction.Date, dateFrom.minusMinutes(1)); attrQuerBldr.addWhereAttrLessValue(CIAccounting.Transaction.Date, dateTo.plusDays(1)); final AttributeQuery attrQuery = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID); final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.AccountLink, instAcc); queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selTRInst = SelectBuilder.get() .linkto(CIAccounting.TransactionPositionAbstract.RateCurrencyLink).instance(); multi.addSelect(selTRInst); multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount, CIAccounting.TransactionPositionAbstract.RateAmount); BigDecimal gainlossSum = BigDecimal.ZERO; multi.execute(); while (multi.next()) { final BigDecimal oldRateAmount = multi .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount); final BigDecimal oldAmount = multi .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount); final Instance targetCurrInst = multi.<Instance>getSelect(selTRInst); final BigDecimal rate = evaluateRate(_parameter, dateEx, currencyInst, targetCurrInst, isSale); final BigDecimal newAmount = oldRateAmount.divide(rate, BigDecimal.ROUND_HALF_UP); BigDecimal gainloss = BigDecimal.ZERO; if (!currencyInst.equals(targetCurrInst)) { gainloss = newAmount.subtract(oldAmount); tarCurInst = targetCurrInst; } else { gainloss = newAmount; } gainlossSum = gainlossSum.add(gainloss); } totalSum = totalSum.add(gainlossSum); final Map<String, String[]> map = validateInfo(_parameter, gainlossSum); final String[] accs = map.get("accs"); final String[] check = map.get("check"); if (checkAccounts(accs, 0, check).length() > 0) { if (gainlossSum.compareTo(BigDecimal.ZERO) != 0) { final String[] accOids = map.get("accountOids"); if (insert == null) { final String descr = DBProperties.getFormatedDBProperty( Recalculate.class.getName() + ".gainLoss4SimpleAccountTransDesc", dateTo.toDate()); insert = new Insert(CIAccounting.Transaction); insert.add(CIAccounting.Transaction.Description, descr); insert.add(CIAccounting.Transaction.Date, dateTo); insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance()); insert.add(CIAccounting.Transaction.Status, Status.find(CIAccounting.TransactionStatus.Open)); insert.execute(); } Insert insertPos = new Insert(CIAccounting.TransactionPositionDebit); insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getInstance()); if (gainlossSum.signum() > 0) { insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, Instance.get(accOids[0])); } else { insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc); } insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainlossSum.abs().negate()); insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount, BigDecimal.ZERO); insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currencyInst); insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, tarCurInst); insertPos.add(CIAccounting.TransactionPositionDebit.Rate, new Object[] { BigDecimal.ONE, BigDecimal.ONE }); insertPos.execute(); insertPos = new Insert(CIAccounting.TransactionPositionCredit); insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getInstance()); if (gainlossSum.signum() > 0) { insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc); } else { insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, Instance.get(accOids[0])); } insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainlossSum.abs()); insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, BigDecimal.ZERO); insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink, currencyInst); insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink, tarCurInst); insertPos.add(CIAccounting.TransactionPositionCredit.Rate, new Object[] { BigDecimal.ONE, BigDecimal.ONE }); insertPos.execute(); } } } } if (insert != null) { final Instance instance = insert.getInstance(); // create classifications final Classification classification1 = (Classification) CIAccounting.TransactionClass.getType(); final Insert relInsert1 = new Insert(classification1.getClassifyRelationType()); relInsert1.add(classification1.getRelLinkAttributeName(), instance); relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId()); relInsert1.execute(); final Insert classInsert1 = new Insert(classification1); classInsert1.add(classification1.getLinkAttributeName(), instance); classInsert1.execute(); final Classification classification = (Classification) CIAccounting.TransactionClassGainLoss.getType(); final Insert relInsert = new Insert(classification.getClassifyRelationType()); relInsert.add(classification.getRelLinkAttributeName(), instance); relInsert.add(classification.getRelTypeAttributeName(), classification.getId()); relInsert.execute(); final Insert classInsert = new Insert(classification); classInsert.add(classification.getLinkAttributeName(), instance); classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, totalSum); classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, totalSum); classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, currencyInst); classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink, currencyInst); classInsert.add(CIAccounting.TransactionClassGainLoss.Rate, new Object[] { BigDecimal.ONE, BigDecimal.ONE }); classInsert.execute(); } // clean up Context.getThreadContext() .removeSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name); return new Return(); }
From source file:nl.strohalm.cyclos.services.transactions.LoanServiceImpl.java
@Override public LoanRepaymentAmountsDTO getLoanPaymentAmount(final LoanPaymentDTO dto) { final LoanRepaymentAmountsDTO ret = new LoanRepaymentAmountsDTO(); Calendar date = dto.getDate(); if (date == null) { date = Calendar.getInstance(); }/* w ww. j a v a2 s . co m*/ final Loan loan = fetchService.fetch(dto.getLoan(), Loan.Relationships.TRANSFER, Loan.Relationships.PAYMENTS); LoanPayment payment = fetchService.fetch(dto.getLoanPayment()); if (payment == null) { payment = loan.getFirstOpenPayment(); } ret.setLoanPayment(payment); // Update the dto with fetched values dto.setLoan(loan); dto.setLoanPayment(payment); if (payment != null) { payment = fetchService.fetch(payment, LoanPayment.Relationships.TRANSFERS); final BigDecimal paymentAmount = payment.getAmount(); BigDecimal remainingAmount = paymentAmount; Calendar expirationDate = payment.getExpirationDate(); Calendar lastPaymentDate = (Calendar) expirationDate.clone(); expirationDate = DateUtils.truncate(expirationDate, Calendar.DATE); final LoanParameters parameters = loan.getParameters(); Collection<Transfer> transfers = payment.getTransfers(); if (transfers == null) { transfers = Collections.emptyList(); } final BigDecimal expirationDailyInterest = CoercionHelper.coerce(BigDecimal.class, parameters.getExpirationDailyInterest()); final LocalSettings localSettings = settingsService.getLocalSettings(); final MathContext mathContext = localSettings.getMathContext(); for (final Transfer transfer : transfers) { Calendar trfDate = transfer.getDate(); trfDate = DateUtils.truncate(trfDate, Calendar.DATE); final BigDecimal trfAmount = transfer.getAmount(); BigDecimal actualAmount = trfAmount; final int diffDays = (int) ((trfDate.getTimeInMillis() - expirationDate.getTimeInMillis()) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest actualAmount = actualAmount.subtract(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } remainingAmount = remainingAmount.subtract(actualAmount); lastPaymentDate = (Calendar) trfDate.clone(); } date = DateHelper.truncate(date); BigDecimal remainingAmountAtDate = remainingAmount; final int diffDays = (int) ((date.getTimeInMillis() - (expirationDate.before(lastPaymentDate) ? lastPaymentDate.getTimeInMillis() : expirationDate.getTimeInMillis())) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest remainingAmountAtDate = remainingAmountAtDate.add(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } final Amount expirationFee = parameters.getExpirationFee(); if (expirationFee != null && (remainingAmountAtDate.compareTo(BigDecimal.ZERO) == 1) && expirationDate.before(date) && (expirationFee.getValue().compareTo(BigDecimal.ZERO) == 1)) { // Apply expiration fee remainingAmountAtDate = remainingAmountAtDate.add(expirationFee.apply(remainingAmount)); } // Round the result ret.setRemainingAmountAtExpirationDate(localSettings.round(remainingAmount)); ret.setRemainingAmountAtDate(localSettings.round(remainingAmountAtDate)); } return ret; }