List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.openvpms.archetype.rules.finance.account.CustomerAccountRules.java
/** * Calculates a new balance for a customer from the current outstanding * balance and a running total.// ww w. j av a2 s . c o m * If the new balance is: * <ul> * <li>< 0 returns 0.00 for payments, or -balance for refunds</li> * <li>> 0 returns 0.00 for refunds</li> * </ul> * * @param customer the customer * @param total the running total * @param payment if {@code true} indicates the total is for a payment, * if {@code false} indicates it is for a refund * @return the new balance * @throws ArchetypeServiceException for any archetype service error */ public BigDecimal getBalance(Party customer, BigDecimal total, boolean payment) { BigDecimal balance = getBalance(customer); BigDecimal result; if (payment) { result = balance.subtract(total); } else { result = balance.add(total); } if (result.signum() == -1) { result = (payment) ? BigDecimal.ZERO : result.negate(); } else if (result.signum() == 1 && !payment) { result = BigDecimal.ZERO; } return result; }
From source file:com.siapa.managedbean.RegistroAlimentacionManagedBean.java
public Boolean UpdateStock() { Boolean isOk;//w ww . j a va 2 s. c o m BigDecimal existencia = BigDecimal.ZERO; BigDecimal existenciaActual = alimento.getExistenciaAlimento(); Integer id = alimento.getIdAlimento(); BigDecimal existenciaNueva; BigDecimal reduccion = registroAlimentacion.getCantidadRegistroAlimentacion(); if (existenciaActual.compareTo(reduccion) == -1) { FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, new FacesMessage("El inventario no es suficiente")); isOk = false; } else { existenciaNueva = existenciaActual.subtract(reduccion); Alimento newAlimento = getAlimento(); Alimento idAlimento = registroAlimentacion.getIdAlimento(); Alimento cactual = alimentoService.findById(idAlimento.getIdAlimento()); existencia = cactual.getExistenciaAlimento().subtract(reduccion); newAlimento.setExistenciaAlimento(existencia); alimentoService.merge(newAlimento); isOk = true; } /* System.out.println("el id es "+id); System.out.println("la existencia es "+existenciaActual); System.out.println("la reduccion es "+reduccion);*/ // System.out.println("la nueva existencia es "+existenciaNueva); return isOk; }
From source file:com.haulmont.timesheets.gui.approve.BulkTimeEntriesApprove.java
@Override public void init(Map<String, Object> params) { super.init(params); if (securityAssistant.isSuperUser()) { timeEntriesDs.setQuery("select e from ts$TimeEntry e " + "where e.date >= :component$dateFrom and e.date <= :component$dateTo"); }/*from ww w . j a v a2s . c o m*/ timeEntriesTable.getColumn("overtime") .setAggregation(ComponentsHelper.createAggregationInfo( projectsService.getEntityMetaPropertyPath(TimeEntry.class, "overtime"), new TimeEntryOvertimeAggregation())); timeEntriesDs.addCollectionChangeListener(e -> { Multimap<Map<String, Object>, TimeEntry> map = ArrayListMultimap.create(); for (TimeEntry item : timeEntriesDs.getItems()) { Map<String, Object> key = new TreeMap<>(); key.put("user", item.getUser()); key.put("date", item.getDate()); map.put(key, item); } for (Map.Entry<Map<String, Object>, Collection<TimeEntry>> entry : map.asMap().entrySet()) { BigDecimal thisDaysSummary = BigDecimal.ZERO; for (TimeEntry timeEntry : entry.getValue()) { thisDaysSummary = thisDaysSummary.add(timeEntry.getTimeInHours()); } for (TimeEntry timeEntry : entry.getValue()) { BigDecimal planHoursForDay = workdaysTools.isWorkday(timeEntry.getDate()) ? workTimeConfigBean.getWorkHourForDay() : BigDecimal.ZERO; BigDecimal overtime = thisDaysSummary.subtract(planHoursForDay); timeEntry.setOvertimeInHours(overtime); } } }); Date previousMonth = DateUtils.addMonths(timeSource.currentTimestamp(), -1); dateFrom.setValue(DateUtils.truncate(previousMonth, Calendar.MONTH)); dateTo.setValue(DateUtils.addDays(DateUtils.truncate(timeSource.currentTimestamp(), Calendar.MONTH), -1)); approve.addAction(new AbstractAction("approveAll") { @Override public void actionPerform(Component component) { setStatus(timeEntriesDs.getItems(), TimeEntryStatus.APPROVED); } }); approve.addAction(new AbstractAction("approveSelected") { @Override public void actionPerform(Component component) { setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.APPROVED); } }); reject.addAction(new AbstractAction("rejectAll") { @Override public void actionPerform(Component component) { setStatus(timeEntriesDs.getItems(), TimeEntryStatus.REJECTED); } }); reject.addAction(new AbstractAction("rejectSelected") { @Override public void actionPerform(Component component) { setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.REJECTED); } }); status.setOptionsList(Arrays.asList(TimeEntryStatus.values())); user.setOptionsList( projectsService.getManagedUsers(userSession.getCurrentOrSubstitutedUser(), View.MINIMAL)); }
From source file:org.openvpms.archetype.rules.supplier.OrderGenerator.java
/** * Creates a {@link Stock} from {@code set}, if stock needs to be ordered. * * @param set the object set * @param product the product * @param supplier the product supplier * @param stockLocation the product stock location * @param belowIdealQuantity if {@code true}, create stock if the current quantity {@code <=} the ideal quantity, * create stock if the current quantity {@code <=} the critical quantity * @return the stock, or {@code null} if the requirements for ordering the stock aren't met *///from w w w . jav a2 s.com private Stock getStock(ObjectSet set, Product product, Party supplier, Party stockLocation, boolean belowIdealQuantity) { Stock stock = null; long productSupplierId = set.getLong("productSupplierId"); BigDecimal quantity = getDecimal("quantity", set); BigDecimal idealQty = getDecimal("idealQty", set); BigDecimal criticalQty = getDecimal("criticalQty", set); int packageSize = set.getInt("packageSize"); String packageUnits = set.getString("packageUnits"); String reorderCode = set.getString("reorderCode"); String reorderDesc = set.getString("reorderDesc"); BigDecimal nettPrice = getDecimal("nettPrice", set); BigDecimal listPrice = getDecimal("listPrice", set); BigDecimal orderedQty = getDecimal("orderedQty", set); BigDecimal receivedQty = getDecimal("receivedQty", set); BigDecimal cancelledQty = getDecimal("cancelledQty", set); if (packageSize != 0) { BigDecimal decSize = BigDecimal.valueOf(packageSize); BigDecimal onOrder; if (receivedQty.compareTo(orderedQty) > 0) { onOrder = receivedQty; } else { onOrder = orderedQty.subtract(receivedQty).subtract(cancelledQty); } BigDecimal current = quantity.add(onOrder); // the on-hand and on-order stock BigDecimal toOrder = ZERO; BigDecimal units = idealQty.subtract(current); // no. of units required to get to idealQty if (!MathRules.equals(ZERO, units)) { // Round up as the desired no. may be less than a packageSize, but must order a whole pack. toOrder = units.divide(decSize, 0, RoundingMode.UP); } if (log.isDebugEnabled()) { log.debug("Stock: product=" + product.getName() + " (" + product.getId() + "), location=" + stockLocation.getName() + " (" + stockLocation.getId() + "), supplier=" + supplier.getName() + " (" + supplier.getId() + "), onHand=" + quantity + ", onOrder=" + onOrder + ", toOrder=" + toOrder + ", idealQty=" + idealQty + ", criticalQty=" + criticalQty); } if (!MathRules.equals(ZERO, toOrder) && (belowIdealQuantity && current.compareTo(idealQty) <= 0 || (current.compareTo(criticalQty) <= 0))) { stock = new Stock(product, stockLocation, supplier, productSupplierId, quantity, idealQty, onOrder, toOrder, reorderCode, reorderDesc, packageSize, packageUnits, nettPrice, listPrice); } } else { if (log.isDebugEnabled()) { log.debug("Cannot order product=" + product.getName() + " (" + product.getId() + ") at location=" + stockLocation.getName() + " (" + stockLocation.getId() + ") from supplier=" + supplier.getName() + " (" + supplier.getId() + ") - no package size"); } } return stock; }
From source file:org.kalypso.model.wspm.tuhh.schema.simulation.ResultLSTinSldFile.java
/** * @see org.kalypso.model.wspm.tuhh.schema.simulation.AbstractResultLSFile#doWrite(java.io.File) *///from w w w. ja v a 2 s . c o m @Override protected void doWrite(final File outputFile) throws IOException, XMLParsingException, SAXException, GMLSchemaException, GM_Exception { final Range<Double> range = m_breakLines.getRange(); if (range == null) return; /* Fetch template polygon symbolizer */ final URL wspSldLocation = getClass().getResource("resources/WspTin.sld"); //$NON-NLS-1$ final FeatureTypeStyle wspStyle = SLDFactory.createFeatureTypeStyle(null, wspSldLocation); final Rule[] rules = wspStyle.getRules(); final SurfacePolygonSymbolizer polySymb = (SurfacePolygonSymbolizer) rules[0].getSymbolizers()[0]; final PolygonColorMap colorMap = polySymb.getColorMap(); final BigDecimal stepWidth = new BigDecimal("0.01"); //$NON-NLS-1$ final BigDecimal minValue = new BigDecimal(range.getMinimum()); final BigDecimal maxValue = new BigDecimal(range.getMaximum()); final Color minFill = new Color(0, 255, 0, 128); final Color maxFill = new Color(255, 0, 0, 128); final Color minStroke = ColorUtilities.createTransparent(minFill, 255); final Color maxStroke = ColorUtilities.createTransparent(maxFill, 255); final PolygonColorMapEntry fromEntry = StyleFactory.createPolygonColorMapEntry(minFill, minStroke, minValue, minValue.add(stepWidth)); final PolygonColorMapEntry toEntry = StyleFactory.createPolygonColorMapEntry(maxFill, maxStroke, maxValue.subtract(stepWidth), maxValue); /* Create and replace new color map */ final List<PolygonColorMapEntry> colorMapEntries = PolygonSymbolizerUtils.createColorMap(fromEntry, toEntry, stepWidth, minValue, maxValue, true); colorMap.replaceColorMap(colorMapEntries); /* Save as tin-sld */ final String styleAsString = wspStyle.exportAsXML(); FileUtils.writeStringToFile(outputFile, styleAsString, "UTF-8"); //$NON-NLS-1$ }
From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java
/** * This function should only be called when it should update the payment amounts *//*from w ww . java2s.c om*/ public static void updatePaymentAmounts(FIN_PaymentScheduleDetail psd) { if (psd.getInvoicePaymentSchedule() != null) { BusinessPartner bPartner = psd.getInvoicePaymentSchedule().getInvoice().getBusinessPartner(); BigDecimal creditUsed = bPartner.getCreditUsed(); BigDecimal amountWithSign = psd.getInvoicePaymentSchedule().getInvoice().isSalesTransaction() ? psd.getAmount() : psd.getAmount().negate(); creditUsed = creditUsed.subtract(amountWithSign); bPartner.setCreditUsed(creditUsed); OBDal.getInstance().save(bPartner); FIN_AddPayment.updatePaymentScheduleAmounts(psd.getPaymentDetails(), psd.getInvoicePaymentSchedule(), psd.getAmount(), psd.getWriteoffAmount()); } if (psd.getOrderPaymentSchedule() != null) { FIN_AddPayment.updatePaymentScheduleAmounts(psd.getPaymentDetails(), psd.getOrderPaymentSchedule(), psd.getAmount(), psd.getWriteoffAmount()); } if (psd.getPaymentDetails().isPrepayment() && psd.getOrderPaymentSchedule() == null && psd.getInvoicePaymentSchedule() == null) { // This PSD is credit BusinessPartner bPartner = psd.getPaymentDetails().getFinPayment().getBusinessPartner(); BigDecimal creditUsed = bPartner.getCreditUsed(); BigDecimal amountWithSign = psd.getPaymentDetails().getFinPayment().isReceipt() ? psd.getAmount() : psd.getAmount().negate(); creditUsed = creditUsed.subtract(amountWithSign); bPartner.setCreditUsed(creditUsed); OBDal.getInstance().save(bPartner); } }
From source file:org.devgateway.ocds.web.rest.controller.CostEffectivenessVisualsController.java
@ApiOperation(value = "Aggregated version of /api/costEffectivenessTenderAmount and " + "/api/costEffectivenessAwardAmount." + "This endpoint aggregates the responses from the specified endpoints, per year. " + "Responds to the same filters.") @RequestMapping(value = "/api/costEffectivenessTenderAwardAmount", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<DBObject> costEffectivenessTenderAwardAmount( @ModelAttribute @Valid final GroupingFilterPagingRequest filter) { Future<List<DBObject>> costEffectivenessAwardAmountFuture = controllerLookupService.asyncInvoke( new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() { @Override/* w ww . j av a 2 s.co m*/ public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) { return costEffectivenessAwardAmount(filter); } }, filter); Future<List<DBObject>> costEffectivenessTenderAmountFuture = controllerLookupService.asyncInvoke( new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() { @Override public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) { return costEffectivenessTenderAmount(filter); } }, filter); //this is completely unnecessary since the #get methods are blocking //controllerLookupService.waitTillDone(costEffectivenessAwardAmountFuture, costEffectivenessTenderAmountFuture); LinkedHashMap<Object, DBObject> response = new LinkedHashMap<>(); try { costEffectivenessAwardAmountFuture.get() .forEach(dbobj -> response.put(getYearMonthlyKey(filter, dbobj), dbobj)); costEffectivenessTenderAmountFuture.get().forEach(dbobj -> { if (response.containsKey(getYearMonthlyKey(filter, dbobj))) { Map<?, ?> map = dbobj.toMap(); map.remove(Keys.YEAR); if (filter.getMonthly()) { map.remove(Keys.MONTH); } response.get(getYearMonthlyKey(filter, dbobj)).putAll(map); } else { response.put(getYearMonthlyKey(filter, dbobj), dbobj); } }); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } Collection<DBObject> respCollection = response.values(); respCollection.forEach(dbobj -> { BigDecimal totalTenderAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_TENDER_AMOUNT) == null ? 0d : ((Number) dbobj.get(Keys.TOTAL_TENDER_AMOUNT)).doubleValue()); BigDecimal totalAwardAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_AWARD_AMOUNT) == null ? 0d : ((Number) dbobj.get(Keys.TOTAL_AWARD_AMOUNT)).doubleValue()); dbobj.put(Keys.DIFF_TENDER_AWARD_AMOUNT, totalTenderAmount.subtract(totalAwardAmount)); dbobj.put(Keys.PERCENTAGE_AWARD_AMOUNT, totalTenderAmount.compareTo(BigDecimal.ZERO) != 0 ? (totalAwardAmount.setScale(15).divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP) .multiply(ONE_HUNDRED)) : BigDecimal.ZERO); dbobj.put(Keys.PERCENTAGE_DIFF_AMOUNT, totalTenderAmount.compareTo(BigDecimal.ZERO) != 0 ? (((BigDecimal) dbobj.get(Keys.DIFF_TENDER_AWARD_AMOUNT)).setScale(15) .divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP).multiply(ONE_HUNDRED)) : BigDecimal.ZERO); }); return new ArrayList<>(respCollection); }
From source file:com.salesmanager.core.module.impl.application.prices.OneTimePriceModule.java
public OrderTotalSummary calculateOrderPrice(Order order, OrderTotalSummary orderSummary, OrderProduct orderProduct, OrderProductPrice productPrice, String currency, Locale locale) { // TODO Auto-generated method stub /**// ww w. j av a2 s .co m * activation price goes in the oneTime fees */ BigDecimal finalPrice = null; // BigDecimal discountPrice=null; // order price this type of price needs an upfront payment BigDecimal otprice = orderSummary.getOneTimeSubTotal(); if (otprice == null) { otprice = new BigDecimal(0); } // the final price is in the product price finalPrice = productPrice.getProductPriceAmount(); int quantity = orderProduct.getProductQuantity(); finalPrice = finalPrice.multiply(new BigDecimal(quantity)); 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(" "); notes.append( CurrencyUtil.displayFormatedAmountWithCurrency(productPrice.getProductPriceAmount(), currency)); notes.append(" "); notes.append(productPrice.getProductPriceName()); BigDecimal originalPrice = orderProduct.getOriginalProductPrice(); if (!productPrice.isDefaultPrice()) { originalPrice = productPrice.getProductPriceAmount(); } 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()); if (dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) { BigDecimal subTotal = originalPrice .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount() .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal credit = subTotal.subtract(creditSubTotal); StringBuffer spacialNote = new StringBuffer(); spacialNote.append("<font color=\"red\">["); spacialNote.append(productPrice.getProductPriceName()); // spacialNote.append(getPriceText(currency,locale)); spacialNote.append(" "); spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); spacialNote.append("]</font>"); if (productPrice.getProductPriceAmount().doubleValue() > pps.getProductPriceSpecialAmount() .doubleValue()) { OrderTotalLine line = new OrderTotalLine(); line.setText(spacialNote.toString()); line.setCost(credit); line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); orderSummary.addDueNowCredits(line); BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge(); oneTimeCredit = oneTimeCredit.add(credit); orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit); } } } else if (pps.getProductPriceSpecialDurationDays() > -1) { Date dt = new Date(); 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()) { BigDecimal subTotal = originalPrice .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount() .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal credit = subTotal.subtract(creditSubTotal); StringBuffer spacialNote = new StringBuffer(); spacialNote.append("<font color=\"red\">["); spacialNote.append(productPrice.getProductPriceName()); // spacialNote.append(getPriceText(currency,locale)); spacialNote.append(" "); spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); spacialNote.append("]</font>"); if (productPrice.getProductPriceAmount().doubleValue() > pps.getProductPriceSpecialAmount() .doubleValue()) { OrderTotalLine line = new OrderTotalLine(); line.setText(spacialNote.toString()); line.setCost(credit); line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); orderSummary.addDueNowCredits(line); BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge(); oneTimeCredit = oneTimeCredit.add(credit); orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit); } } } } } if (!productPrice.isDefaultPrice()) { // add a price description OrderTotalLine scl = new OrderTotalLine(); scl.setText(notes.toString()); scl.setCost(finalPrice); scl.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(finalPrice, currency)); orderSummary.addOtherDueNowPrice(scl); } return orderSummary; }
From source file:org.openvpms.esci.adapter.map.order.OrderMapperImpl.java
/** * Returns a <tt>MonetaryTotalType</tt> for an order. * * @param order the order/* w ww . j a va 2s .c o m*/ * @param currency the currency * @return the corresponding <tt>MonetaryTotalType</tt> */ private MonetaryTotalType getMonetaryTotal(FinancialAct order, Currency currency) { BigDecimal payableAmount = order.getTotal(); BigDecimal lineExtensionAmount = payableAmount.subtract(order.getTaxAmount()); MonetaryTotalType result = new MonetaryTotalType(); result.setLineExtensionAmount( UBLHelper.initAmount(new LineExtensionAmountType(), lineExtensionAmount, currency)); result.setPayableAmount(UBLHelper.initAmount(new PayableAmountType(), payableAmount, currency)); return result; }
From source file:org.libreplan.web.orders.materials.AssignedMaterialsController.java
/** * Creates a new {@link MaterialAssignment} out of materialAssignment, but * setting its units attribute to units. * * materialAssignment passed as parameter decreases its units attribute in units * * @param materialAssignment/*www.j a v a 2 s. co m*/ * @param units */ private void splitMaterialAssignment(A materialAssignment, BigDecimal units) { A newAssignment = copyFrom(materialAssignment); BigDecimal currentUnits = getUnits(materialAssignment); if (units.compareTo(currentUnits) > 0) { units = currentUnits; currentUnits = BigDecimal.ZERO; } else { currentUnits = currentUnits.subtract(units); } setUnits(newAssignment, units); setUnits(materialAssignment, currentUnits); getModel().addMaterialAssignment(newAssignment); reloadGridMaterials(); }