List of usage examples for java.math BigDecimal add
public BigDecimal add(BigDecimal augend)
From source file:com.opensourcestrategies.financials.accounts.GLAccountInTree.java
/** * Gets the balance of this GL account given child GL account. * @param childAccount a <code>GLAccountInTree</code> value * @return a <code>BigDecimal</code> value *//* ww w. j a v a 2s. c o m*/ private BigDecimal getBalanceOfChildrenRec(GLAccountInTree childAccount) { if (childAccount == null) { return BigDecimal.ZERO; } BigDecimal balanceOfChildren = childAccount.balance; if ((childAccount.isDebitAccount && this.isCreditAccount) || (childAccount.isCreditAccount && this.isDebitAccount)) { balanceOfChildren = balanceOfChildren.negate(); } for (GLAccountInTree grandchildAccount : childAccount.childAccounts) { balanceOfChildren = balanceOfChildren.add(getBalanceOfChildrenRec(grandchildAccount)); } return balanceOfChildren; }
From source file:com.xumpy.timesheets.services.TickedJobsDetailSrv.java
@Transactional(value = "transactionManager") public Map<JobsGroupSrvPojo, Map<String, String>> tickedOverviewMonth(String month) throws ParseException { List<? extends Jobs> jobs = jobsDao.selectPeriode(CustomDateUtils.getFirstDayOfMonth(month), CustomDateUtils.getLastDayOfMonth(month)); List<JobsGroup> jobsGroups = new ArrayList<JobsGroup>(); for (Jobs job : jobs) { if (!jobsGroups.contains(job.getJobsGroup())) { jobsGroups.add(job.getJobsGroup()); }/*from www .j a va2s.c o m*/ } Map<JobsGroupSrvPojo, Map<String, String>> returnMap = new HashMap<JobsGroupSrvPojo, Map<String, String>>(); for (JobsGroup jobsGroup : jobsGroups) { BigDecimal actualWorked = new BigDecimal(0); BigDecimal timesheetWorked = new BigDecimal(0); Map worked = new HashMap<String, String>(); for (Jobs job : jobs) { if (jobsGroup.getPk_id().equals(job.getJobsGroup().getPk_id())) { List<? extends TickedJobs> tickedJobs = tickedJobsDao.selectTickedJobsByJob(job.getPk_id()); TickedJobsDetail jobsDetail = calculate(tickedJobs, new BigDecimal(30)); timesheetWorked = timesheetWorked.add(job.getWorkedHours()); actualWorked = actualWorked.add(jobsDetail.getActualWorked()); } } worked.put("actualWorked", actualWorked.toString()); worked.put("timesheetWorked", timesheetWorked.multiply(new BigDecimal(60)).toString()); returnMap.put(new JobsGroupSrvPojo(jobsGroup), worked); } return returnMap; }
From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsReservationsController.java
private ModelAndView getIndexView(DateRange dateRange) { List<Booking> bookings = bookingDAO.findActiveBookingsBetween(dateRange.getStartDate(), dateRange.getEndDate());// w w w .j a va2s. c o m BigDecimal total = new BigDecimal(0); for (Booking booking : bookings) { if (booking.getAmount() != null) { total = total.add(booking.getAmount()); } } ModelAndView listView = new ModelAndView("admin/bookings/reservations/index"); listView.addObject("Total", total); listView.addObject("Bookings", bookings); listView.addObject("DateRange", dateRange); return listView; }
From source file:mx.edu.um.mateo.inventario.web.FacturaAlmacenController.java
@RequestMapping("/ver/{id}") public String ver(@PathVariable Long id, Model modelo) { log.debug("Mostrando factura {}", id); FacturaAlmacen factura = facturaDao.obtiene(id); switch (factura.getEstatus().getNombre()) { case Constantes.ABIERTA: modelo.addAttribute("puedeEditar", true); modelo.addAttribute("puedeEliminar", true); modelo.addAttribute("puedeCerrar", true); break;// www . j a va2 s .co m case Constantes.CERRADA: modelo.addAttribute("puedeCancelar", true); modelo.addAttribute("puedeReporte", true); break; } modelo.addAttribute("factura", factura); BigDecimal salidasTotal = BigDecimal.ZERO; BigDecimal salidasIva = BigDecimal.ZERO; for (Salida salida : factura.getSalidas()) { salidasTotal = salidasTotal.add(salida.getTotal()); salidasIva = salidasIva.add(salida.getIva()); } modelo.addAttribute("salidasTotal", salidasTotal); modelo.addAttribute("salidasIva", salidasIva); modelo.addAttribute("salidasSubtotal", salidasTotal.subtract(salidasIva)); BigDecimal entradasTotal = BigDecimal.ZERO; BigDecimal entradasIva = BigDecimal.ZERO; for (Entrada entrada : factura.getEntradas()) { entradasTotal = entradasTotal.add(entrada.getTotal()); entradasIva = entradasIva.add(entrada.getIva()); } modelo.addAttribute("entradasTotal", entradasTotal); modelo.addAttribute("entradasIva", entradasIva); modelo.addAttribute("entradasSubtotal", entradasTotal.subtract(entradasIva)); return "inventario/factura/ver"; }
From source file:com.stratio.cassandra.lucene.schema.mapping.BigDecimalMapper.java
/** {@inheritDoc} */ @Override/*from www. jav a 2 s .com*/ protected String doBase(String name, Object value) { // Parse big decimal BigDecimal bd; try { bd = new BigDecimal(value.toString()); } catch (NumberFormatException e) { throw new IndexException("Field '%s' requires a base 10 decimal, but found '%s'", name, value); } // Split integer and decimal part bd = bd.stripTrailingZeros(); String[] parts = bd.toPlainString().split("\\."); validateIntegerPart(name, value, parts); validateDecimalPart(name, value, parts); BigDecimal complemented = bd.add(complement); String bds[] = complemented.toString().split("\\."); String integerPart = StringUtils.leftPad(bds[0], integerDigits + 1, '0'); String decimalPart = bds.length == 2 ? bds[1] : "0"; return integerPart + "." + decimalPart; }
From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java
/** * Verifies that the stock is updated correctly if referred to by two different items in a transaction. *//*from w w w . j a va 2s . c o m*/ @Test public void testMultipleStockUpdatesInTxn() { final List<FinancialAct> acts = new ArrayList<FinancialAct>(createInvoice()); final FinancialAct item1 = acts.get(1); final FinancialAct item2 = FinancialTestHelper.createChargeItem(CustomerAccountArchetypes.INVOICE_ITEM, patient, product, BigDecimal.ONE); addStockLocation(item2); acts.add(item2); BigDecimal initialQuantity = BigDecimal.ZERO; BigDecimal quantity = BigDecimal.valueOf(5); item1.setQuantity(quantity); item2.setQuantity(quantity); checkEquals(initialQuantity, getStock(stockLocation, product)); BigDecimal expected = getQuantity(initialQuantity, quantity.add(quantity), false); TransactionTemplate template = new TransactionTemplate(txnManager); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { save(acts); } }); checkEquals(expected, getStock(stockLocation, product)); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { item1.setQuantity(BigDecimal.ONE); save(item1); remove(item2); } }); expected = getQuantity(initialQuantity, BigDecimal.ONE, false); checkEquals(expected, getStock(stockLocation, product)); }
From source file:churashima.action.manage.ReportAction.java
@Execute(validator = false) public String attendance() { String ym = reportForm.ym;/*from ww w. java 2 s . c o m*/ int year = Integer.parseInt(ym.substring(0, 4)); int month = Integer.parseInt(ym.substring(4)); Calendar calFrom = Calendar.getInstance(); calFrom.set(Calendar.YEAR, year); calFrom.set(Calendar.MONTH, month - 1); calFrom.set(Calendar.DAY_OF_MONTH, 1); Calendar calTo = Calendar.getInstance(); calTo.set(Calendar.YEAR, year); calTo.set(Calendar.MONTH, month); calTo.set(Calendar.DAY_OF_MONTH, 1); WorkDao workDao = SingletonS2Container.getComponent(WorkDao.class); List<ReportDto> reportDtoList = workDao.selectForReportAttendance(reportForm.kind, calFrom.getTime(), calTo.getTime()); BigDecimal workHourTotal = BigDecimal.valueOf(0); BigDecimal overHourTotal = BigDecimal.valueOf(0); BigDecimal overHourMorningTotal = BigDecimal.valueOf(0); BigDecimal overHourEveningTotal = BigDecimal.valueOf(0); BigDecimal overHourNightTotal = BigDecimal.valueOf(0); for (ReportDto dto : reportDtoList) { workHourTotal = workHourTotal.add(dto.workHourTotal); overHourTotal = overHourTotal.add(dto.overHourTotal); overHourMorningTotal = overHourMorningTotal.add(dto.overHourMorningTotal); overHourEveningTotal = overHourEveningTotal.add(dto.overHourEveningTotal); overHourNightTotal = overHourNightTotal.add(dto.overHourNightTotal); } reportForm.workHourTotal = workHourTotal; reportForm.overHourTotal = overHourTotal; reportForm.overHourMorningTotal = overHourMorningTotal; reportForm.overHourEveningTotal = overHourEveningTotal; reportForm.overHourNightTotal = overHourNightTotal; // ????? calFrom.add(Calendar.MONTH, -1); calTo.add(Calendar.MONTH, -1); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); int count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(), null); if (count > 0) { reportForm.ymBefore = sdf.format(calFrom.getTime()); } else { reportForm.ymBefore = null; } // ???? calFrom.add(Calendar.MONTH, +2); calTo.add(Calendar.MONTH, +2); count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(), null); if (count > 0) { reportForm.ymNext = sdf.format(calFrom.getTime()); } else { reportForm.ymNext = null; } reportForm.reportDtoList = reportDtoList; return "attendanceReport.jsp"; }
From source file:com.nkapps.billing.dao.OverpaymentDaoImpl.java
@Override public BankStatement saveReturnState(String bankStatementId, Short returnState, BigDecimal returnSum, Long issuerSerialNumber, String issuerIp) throws Exception { Session session = getSession();/*from w w w. j a v a2 s.c o m*/ Transaction transaction = session.beginTransaction(); BankStatement bs = (BankStatement) session.get(BankStatement.class, bankStatementId); String q = "SELECT COALESCE(bs.paymentSum,0) - COALESCE(bs.returnSum,0) - (SELECT COALESCE(SUM(kp.paidSum),0) FROM bs.bankStatementPayments bsp JOIN bsp.id.payment p JOIN p.keyPayments kp WHERE p.claim = 0) AS overpaymentSum" + " FROM BankStatement bs" + " WHERE bs = :bs"; Query query = session.createQuery(q); query.setParameter("bs", bs); BigDecimal overpaymentSum = (BigDecimal) query.uniqueResult(); LocalDateTime dateTime = LocalDateTime.now(); if (returnState == 0) { if (bs.getReturnSum() != null) { // get all overpayment sum overpaymentSum = overpaymentSum.add(bs.getReturnSum()); } bs.setReturnState(returnState); bs.setReturnSum(null); bs.setIssuerSerialNumber(issuerSerialNumber); bs.setIssuerIp(issuerIp); bs.setDateUpdated(dateTime); session.update(bs); returnStateRevert(session, bs, overpaymentSum, issuerSerialNumber, issuerIp, dateTime); } else { if (returnSum.compareTo(overpaymentSum) > 0) { // checking return sum must not be greater than overpayment sum returnSum = overpaymentSum; } bs.setReturnState(returnState); if (bs.getReturnSum() != null) { bs.setReturnSum(bs.getReturnSum().add(returnSum)); } else { bs.setReturnSum(returnSum); } bs.setIssuerSerialNumber(issuerSerialNumber); bs.setIssuerIp(issuerIp); bs.setDateUpdated(dateTime); session.update(bs); returnStateCommit(session, bs, returnSum, issuerSerialNumber, issuerIp, dateTime); } transaction.commit(); session.close(); return bs; }
From source file:se.backede.jeconomix.forms.report.SingleTransactionReport.java
private DefaultCategoryDataset createDataset(TransactionReportDto reports) { String lineTitle = "Kronor"; Map<Month, BigDecimal> sums = new HashMap<>(); List<Month> monthList = new LinkedList<>(Arrays.asList(Month.values())); monthList.forEach((month) -> {//from w w w . j ava 2 s .co m sums.put(month, BigDecimal.valueOf(0)); }); reports.getTransctions().forEach((TransactionDto transaction) -> { monthList.stream().filter((month) -> (transaction.getBudgetMonth().equals(month))) .forEachOrdered((month) -> { BigDecimal currentSum = sums.get(month); if (transaction.getSum() != null) { double abs = Math.abs(transaction.getSum().doubleValue()); BigDecimal newSum = currentSum.add(BigDecimal.valueOf(abs)); sums.put(month, newSum); } }); }); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(sums.get(Month.JANUARY), lineTitle, "Jan"); dataset.addValue(sums.get(Month.FEBRUARY), lineTitle, "Feb"); dataset.addValue(sums.get(Month.MARCH), lineTitle, "Mar"); dataset.addValue(sums.get(Month.APRIL), lineTitle, "Apr"); dataset.addValue(sums.get(Month.MAY), lineTitle, "May"); dataset.addValue(sums.get(Month.JUNE), lineTitle, "Jun"); dataset.addValue(sums.get(Month.JULY), lineTitle, "Jul"); dataset.addValue(sums.get(Month.AUGUST), lineTitle, "Aug"); dataset.addValue(sums.get(Month.SEPTEMBER), lineTitle, "Sep"); dataset.addValue(sums.get(Month.OCTOBER), lineTitle, "Oct"); dataset.addValue(sums.get(Month.NOVEMBER), lineTitle, "Nov"); dataset.addValue(sums.get(Month.DECEMBER), lineTitle, "Dec"); return dataset; }
From source file:com.salesmanager.core.module.impl.application.prices.MonthlyPriceModule.java
public OrderTotalSummary calculateOrderPrice(Order order, OrderTotalSummary orderSummary, OrderProduct orderProduct, OrderProductPrice productPrice, String currency, Locale locale) { /**/*from w w w . j a v a 2s . c o m*/ * Monthly price goes in the oneTime fees as well as in the upcoming * recursive fees */ BigDecimal finalPrice = null; BigDecimal discountPrice = null; BigDecimal originalPrice = orderProduct.getOriginalProductPrice(); if (!productPrice.isDefaultPrice()) { originalPrice = productPrice.getProductPriceAmount(); } int quantity = orderProduct.getProductQuantity(); // the real price is the price submited finalPrice = orderProduct.getProductPrice(); finalPrice = finalPrice.multiply(new BigDecimal(quantity)); // the final price is the product price * quantity if (finalPrice == null) {// pick it from the productPrice finalPrice = productPrice.getProductPriceAmount(); finalPrice = finalPrice.multiply(new BigDecimal(quantity)); } // this type of price needs an upfront payment BigDecimal otprice = orderSummary.getOneTimeSubTotal(); if (otprice == null) { otprice = new BigDecimal(0); } otprice = otprice.add(finalPrice); orderSummary.setOneTimeSubTotal(otprice); ProductPriceSpecial pps = productPrice.getSpecial(); // Build text StringBuffer notes = new StringBuffer(); notes.append(quantity).append(" x "); notes.append(orderProduct.getProductName()); notes.append(" "); if (!productPrice.isDefaultPrice()) { notes.append( CurrencyUtil.displayFormatedAmountWithCurrency(productPrice.getProductPriceAmount(), currency)); } else { notes.append(CurrencyUtil.displayFormatedAmountWithCurrency(orderProduct.getProductPrice(), currency)); } notes.append(" "); notes.append(this.getPriceSuffixText(currency, locale)); if (pps != null) { if (pps.getProductPriceSpecialStartDate() != null && pps.getProductPriceSpecialEndDate() != null) { if (pps.getProductPriceSpecialStartDate().before(order.getDatePurchased()) && pps.getProductPriceSpecialEndDate().after(order.getDatePurchased())) { BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue()); BigDecimal subTotal = originalPrice.multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount() .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal credit = subTotal.subtract(creditSubTotal); if (dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) { discountPrice = productPrice.getProductPriceAmount().subtract(dPrice); BigDecimal newPrice = orderProduct.getProductPrice(); if (!productPrice.isDefaultPrice()) { newPrice = productPrice.getProductPriceAmount(); } else { newPrice = newPrice.add(discountPrice); } StringBuffer spacialNote = new StringBuffer(); spacialNote.append("<font color=\"red\">["); spacialNote.append(orderProduct.getProductName()); spacialNote.append(" "); spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); spacialNote.append(" "); spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.rebate")); spacialNote.append(" "); spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.until")); spacialNote.append(" "); spacialNote.append(DateUtil.formatDate(pps.getProductPriceSpecialEndDate())); spacialNote.append("]</font>"); OrderTotalLine line = new OrderTotalLine(); // BigDecimal credit = discountPrice; line.setText(spacialNote.toString()); line.setCost(credit); line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); orderSummary.addDueNowCredits(line); orderSummary.addRecursiveCredits(line); BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge(); oneTimeCredit = oneTimeCredit.add(credit); orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit); } } else if (pps.getProductPriceSpecialDurationDays() > -1) { Date dt = new Date(new Date().getTime()); int numDays = pps.getProductPriceSpecialDurationDays(); Date purchased = order.getDatePurchased(); Calendar c = Calendar.getInstance(); c.setTime(dt); c.add(Calendar.DATE, numDays); BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue()); if (dt.before(c.getTime()) && dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) { discountPrice = productPrice.getProductPriceAmount().subtract(dPrice); BigDecimal newPrice = orderProduct.getProductPrice(); BigDecimal subTotal = originalPrice .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount() .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal credit = subTotal.subtract(creditSubTotal); if (!productPrice.isDefaultPrice()) { newPrice = productPrice.getProductPriceAmount(); } else { newPrice = newPrice.add(discountPrice); } StringBuffer spacialNote = new StringBuffer(); spacialNote.append("<font color=\"red\">["); spacialNote.append(orderProduct.getProductName()); spacialNote.append(" "); spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); spacialNote.append(" "); spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.rebate")); spacialNote.append(" "); spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.until")); spacialNote.append(" "); spacialNote.append(DateUtil.formatDate(c.getTime())); spacialNote.append("]</font>"); OrderTotalLine line = new OrderTotalLine(); line.setText(spacialNote.toString()); line.setCost(credit); line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); orderSummary.addDueNowCredits(line); if (numDays > 30) { orderSummary.addRecursiveCredits(line); } BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge(); oneTimeCredit = oneTimeCredit.add(credit); orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit); // } } } } } BigDecimal newPrice = orderProduct.getProductPrice(); if (!productPrice.isDefaultPrice()) { newPrice = productPrice.getProductPriceAmount(); } newPrice = newPrice.multiply(new BigDecimal(quantity)); // Recursive sub total BigDecimal rprice = orderSummary.getRecursiveSubTotal(); if (rprice == null) { rprice = new BigDecimal(0); } // recursive always contain full price rprice = rprice.add(newPrice); orderSummary.setRecursiveSubTotal(rprice); // recursive price OrderTotalLine scl = new OrderTotalLine(); scl.setText(notes.toString()); scl.setCost(newPrice); scl.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(newPrice, currency)); orderSummary.addRecursivePrice(scl); return orderSummary; }