Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_UP.

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:hr.diskobolos.service.impl.DashboardServiceImpl.java

private double calculatePercentage(Integer totalPoints, Integer categoryPoints) {
    if (categoryPoints == null) {
        return 0.0;
    }//from   www .j  a v  a  2 s  . c om
    return BigDecimal.valueOf((double) (categoryPoints * 100) / (double) totalPoints)
            .setScale(2, RoundingMode.HALF_UP).doubleValue();
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.MultiPieChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final Plot plot = chart.getPlot();
    final MultiplePiePlot mpp = (MultiplePiePlot) plot;
    final JFreeChart pc = mpp.getPieChart();
    configureSubChart(pc);/*w w  w.ja v a2  s .c o m*/

    final PiePlot pp = (PiePlot) pc.getPlot();
    if (StringUtils.isEmpty(getTooltipFormula()) == false) {
        pp.setToolTipGenerator(new FormulaPieTooltipGenerator(getRuntime(), getTooltipFormula()));
    }
    if (StringUtils.isEmpty(getUrlFormula()) == false) {
        pp.setURLGenerator(new FormulaPieURLGenerator(getRuntime(), getUrlFormula()));
    }

    if (shadowPaint != null) {
        pp.setShadowPaint(shadowPaint);
    }
    if (shadowXOffset != null) {
        pp.setShadowXOffset(shadowXOffset.doubleValue());
    }
    if (shadowYOffset != null) {
        pp.setShadowYOffset(shadowYOffset.doubleValue());
    }

    final CategoryDataset c = mpp.getDataset();
    if (c != null) {
        final String[] colors = getSeriesColor();
        final int keysSize = c.getColumnKeys().size();
        for (int i = 0; i < colors.length; i++) {
            if (keysSize > i) {
                pp.setSectionPaint(c.getColumnKey(i), parseColorFromString(colors[i]));
            }
        }
    }

    if (StringUtils.isEmpty(getLabelFont()) == false) {
        pp.setLabelFont(Font.decode(getLabelFont()));
    }

    if (Boolean.FALSE.equals(getItemsLabelVisible())) {
        pp.setLabelGenerator(null);
    } else {
        final ExpressionRuntime runtime = getRuntime();
        final Locale locale = runtime.getResourceBundleFactory().getLocale();

        final FastDecimalFormat fastPercent = new FastDecimalFormat(FastDecimalFormat.TYPE_PERCENT, locale);
        final FastDecimalFormat fastInteger = new FastDecimalFormat(FastDecimalFormat.TYPE_INTEGER, locale);

        final DecimalFormat numFormat = new DecimalFormat(fastInteger.getPattern(),
                new DecimalFormatSymbols(locale));
        numFormat.setRoundingMode(RoundingMode.HALF_UP);

        final DecimalFormat percentFormat = new DecimalFormat(fastPercent.getPattern(),
                new DecimalFormatSymbols(locale));
        percentFormat.setRoundingMode(RoundingMode.HALF_UP);

        final StandardPieSectionLabelGenerator labelGen = new StandardPieSectionLabelGenerator(
                multipieLabelFormat, numFormat, percentFormat);
        pp.setLabelGenerator(labelGen);
    }
}

From source file:mx.edu.um.mateo.inventario.web.EntradaController.java

@RequestMapping("/ver/{id}")
public String ver(@PathVariable Long id, Model modelo) {
    log.debug("Mostrando entrada {}", id);
    Entrada entrada = entradaDao.obtiene(id);
    switch (entrada.getEstatus().getNombre()) {
    case Constantes.ABIERTA:
        modelo.addAttribute("puedeEditar", true);
        modelo.addAttribute("puedeEliminar", true);
        modelo.addAttribute("puedeCerrar", true);
        modelo.addAttribute("puedePendiente", true);
        break;//from   w  w w.  j ava2s  .  c  o m
    case Constantes.PENDIENTE:
        modelo.addAttribute("puedeEditarPendiente", true);
        break;
    case Constantes.CERRADA:
        modelo.addAttribute("puedeCancelar", true);
        break;
    }

    modelo.addAttribute("entrada", entrada);

    BigDecimal subtotal = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    BigDecimal iva = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    for (LoteEntrada lote : entrada.getLotes()) {
        subtotal = subtotal.add(lote.getPrecioUnitario().multiply(lote.getCantidad()));
        iva = iva.add(lote.getIva());
    }
    BigDecimal total = subtotal.add(iva);
    modelo.addAttribute("subtotal", subtotal.setScale(2, RoundingMode.HALF_UP));
    modelo.addAttribute("iva", iva);
    modelo.addAttribute("total", total.setScale(2, RoundingMode.HALF_UP));
    if (iva.compareTo(entrada.getIva()) == 0 && total.compareTo(entrada.getTotal()) == 0) {
        modelo.addAttribute("estiloTotales", "label label-success");
    } else {
        BigDecimal variacion = new BigDecimal("0.05");
        BigDecimal topeIva = entrada.getIva().multiply(variacion);
        BigDecimal topeTotal = entrada.getTotal().multiply(variacion);
        log.debug("Estilos {} {} {} {} {} {}",
                new Object[] { iva, entrada.getIva(), topeIva, total, entrada.getTotal(), topeTotal });
        if (iva.compareTo(entrada.getIva()) < 0 || total.compareTo(entrada.getTotal()) < 0) {
            log.debug("La diferencia es menor");
            if (iva.compareTo(entrada.getIva().subtract(topeIva)) >= 0
                    && total.compareTo(entrada.getTotal().subtract(topeTotal)) >= 0) {
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        } else {
            log.debug("La diferencia es mayor {} {}",
                    new Object[] { iva.compareTo(entrada.getIva().add(topeIva)),
                            total.compareTo(entrada.getTotal().add(topeTotal)) });
            if (iva.compareTo(entrada.getIva().add(topeIva)) <= 0
                    && total.compareTo(entrada.getTotal().add(topeTotal)) <= 0) {
                log.debug("estilo warning");
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                log.debug("estilo error");
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        }
    }

    return "inventario/entrada/ver";
}

From source file:org.rm3l.ddwrt.tiles.status.bandwidth.BandwidthWANMonitoringTile.java

@Nullable
@Override//ww  w .j ava 2 s  .  c  o m
protected Loader<None> getLoader(int id, Bundle args) {
    return new AsyncTaskLoader<None>(this.mParentFragmentActivity) {

        @Nullable
        @Override
        public None loadInBackground() {

            try {
                Log.d(LOG_TAG,
                        "Init background loader for " + BandwidthMonitoringTile.class + ": routerInfo="
                                + mRouter + " / this.mAutoRefreshToggle= " + mAutoRefreshToggle
                                + " / nbRunsLoader=" + nbRunsLoader);

                if (nbRunsLoader > 0 && !mAutoRefreshToggle) {
                    //Skip run
                    Log.d(LOG_TAG, "Skip loader run");
                    return (None) new None().setException(new DDWRTTileAutoRefreshNotAllowedException());
                }
                nbRunsLoader++;

                //Start by getting information about the WAN iface name
                @Nullable
                final NVRAMInfo nvRamInfoFromRouter = SSHUtils.getNVRamInfoFromRouter(mRouter,
                        mGlobalPreferences, NVRAMInfo.WAN_IFACE);
                if (nvRamInfoFromRouter == null) {
                    throw new IllegalStateException("Whoops. WAN Iface could not be determined.");
                }

                wanIface = nvRamInfoFromRouter.getProperty(NVRAMInfo.WAN_IFACE);

                if (Strings.isNullOrEmpty(wanIface)) {
                    throw new IllegalStateException("Whoops. WAN Iface could not be determined.");
                }

                @Nullable
                final String[] netDevWanIfaces = SSHUtils.getManualProperty(mRouter, mGlobalPreferences,
                        "cat /proc/net/dev | grep \"" + wanIface + "\"");
                if (netDevWanIfaces == null || netDevWanIfaces.length == 0) {
                    return null;
                }

                String netDevWanIface = netDevWanIfaces[0];
                if (netDevWanIface == null) {
                    return null;
                }

                netDevWanIface = netDevWanIface.replaceAll(wanIface + ":", "");

                final List<String> netDevWanIfaceList = Splitter.on(" ").omitEmptyStrings().trimResults()
                        .splitToList(netDevWanIface);
                if (netDevWanIfaceList == null || netDevWanIfaceList.size() <= 15) {
                    return null;
                }

                final long timestamp = System.currentTimeMillis();

                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_bytes", netDevWanIfaceList.get(0));
                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_packets", netDevWanIfaceList.get(1));
                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_errs", netDevWanIfaceList.get(2));
                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_drop", netDevWanIfaceList.get(3));
                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_fifo", netDevWanIfaceList.get(4));
                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_frame", netDevWanIfaceList.get(5));
                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_compressed", netDevWanIfaceList.get(6));
                nvRamInfoFromRouter.setProperty(wanIface + "_rcv_multicast", netDevWanIfaceList.get(7));

                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_bytes", netDevWanIfaceList.get(8));
                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_packets", netDevWanIfaceList.get(9));
                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_errs", netDevWanIfaceList.get(10));
                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_drop", netDevWanIfaceList.get(11));
                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_fifo", netDevWanIfaceList.get(12));
                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_colls", netDevWanIfaceList.get(13));
                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_carrier", netDevWanIfaceList.get(14));
                nvRamInfoFromRouter.setProperty(wanIface + "_xmit_compressed", netDevWanIfaceList.get(15));

                //Ingress
                double wanRcvMBytes;
                final String wanRcvBytes = nvRamInfoFromRouter.getProperty(wanIface + "_rcv_bytes", "-1");
                try {
                    wanRcvMBytes = Double.parseDouble(wanRcvBytes) / (1024 * 1024);
                    if (wanRcvMBytes >= 0.) {
                        wanRcvMBytes = new BigDecimal(wanRcvMBytes).setScale(2, RoundingMode.HALF_UP)
                                .doubleValue();
                        bandwidthMonitoringIfaceData.addData("IN",
                                new BandwidthMonitoringTile.DataPoint(timestamp, wanRcvMBytes));
                    }
                } catch (@NotNull final NumberFormatException nfe) {
                    return null;
                }
                nvRamInfoFromRouter.setProperty(wanIface + "_ingress_MB", Double.toString(wanRcvMBytes));

                //Egress
                double wanXmitMBytes;
                final String wanXmitBytes = nvRamInfoFromRouter.getProperty(wanIface + "_xmit_bytes", "-1");
                try {
                    wanXmitMBytes = Double.parseDouble(wanXmitBytes) / (1024 * 1024);
                    if (wanXmitMBytes >= 0.) {
                        wanXmitMBytes = new BigDecimal(wanXmitMBytes).setScale(2, RoundingMode.HALF_UP)
                                .doubleValue();
                        bandwidthMonitoringIfaceData.addData("OUT",
                                new BandwidthMonitoringTile.DataPoint(timestamp, wanXmitMBytes));
                    }

                } catch (@NotNull final NumberFormatException nfe) {
                    return null;
                }

                nvRamInfoFromRouter.setProperty(wanIface + "_egress_MB", Double.toString(wanXmitMBytes));

                return new None();

            } catch (@NotNull final Exception e) {
                e.printStackTrace();
                return (None) new None().setException(e);
            }
        }
    };
}

From source file:org.openbravo.costing.AverageCostAdjustment.java

@Override
protected void getRelatedTransactionsByAlgorithm() {
    // Search all transactions after the date of the adjusted line and recalculate the costs of them
    // to adjust differences
    MaterialTransaction basetrx = getTransaction();
    // Transactions of closing inventories are managed by generic CostAdjustmentProcess adjusting
    // the cost of the related opening inventory.
    if (basetrx.getPhysicalInventoryLine() != null
            && basetrx.getPhysicalInventoryLine().getRelatedInventory() != null) {
        return;/*from w  w  w .j  av  a2s.  c o m*/
    }
    BigDecimal signMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
    Date trxDate = basetrx.getTransactionProcessDate();

    BigDecimal adjustmentBalance = BigDecimal.ZERO;
    BigDecimal unitCostAdjustmentBalance = BigDecimal.ZERO;
    // Initialize adjustment balance looping through all cost adjustment lines of current
    // transaction.
    log.debug("Initialize adjustment balance");
    CostAdjustmentLine baseCAL = getCostAdjLine();
    for (CostAdjustmentLine costAdjLine : getTrxAdjustmentLines(basetrx)) {
        if (costAdjLine.isSource() && !costAdjLine.isRelatedTransactionAdjusted()
                && !costAdjLine.getId().equals(strCostAdjLineId)) {
            searchRelatedTransactionCosts(costAdjLine);
        }

        costAdjLine.setRelatedTransactionAdjusted(Boolean.TRUE);
        if (!costAdjLine.getId().equals(strCostAdjLineId)) {
            costAdjLine.setParentCostAdjustmentLine(baseCAL);
        }
        OBDal.getInstance().save(costAdjLine);
        // If the cost adjustment line has Transaction Costs those adjustment amount are included
        // in the Current Value Amount and not in the Adjustment Balance
        if (!costAdjLine.getTransactionCostList().isEmpty()) {
            continue;
        }
        BigDecimal adjustmentAmt = costAdjLine.getAdjustmentAmount();
        if (!strCostCurrencyId.equals(costAdjLine.getCurrency().getId())) {
            adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, costAdjLine.getCurrency(),
                    getCostCurrency(), costAdjLine.getAccountingDate(), getCostOrg(),
                    FinancialUtils.PRECISION_STANDARD);
        }
        adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(signMultiplier));
        if (costAdjLine.isUnitCost()) {
            unitCostAdjustmentBalance = unitCostAdjustmentBalance.add(adjustmentAmt);
        }
    }

    // Initialize current stock qty and value amt.
    BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed);
    BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed, getCostCurrency());
    log.debug(
            "Adjustment balance: " + adjustmentBalance.toPlainString() + ", current stock {}, current value {}",
            currentStock.toPlainString(), currentValueAmt.toPlainString());

    // Initialize current unit cost including the cost adjustments.
    Costing costing = AverageAlgorithm.getProductCost(trxDate, basetrx.getProduct(), getCostDimensions(),
            getCostOrg());
    if (costing == null) {
        throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: "
                + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(trxDate));
    }
    BigDecimal cost = null;
    // If current stock is zero the cost is not modified until a related transaction that modifies
    // the stock is found.
    if (currentStock.signum() != 0) {
        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                RoundingMode.HALF_UP);
    }
    log.debug("Starting average cost {}", cost == null ? "not cost" : cost.toPlainString());
    if (cost != null && (AverageAlgorithm.modifiesAverage(trxType) || !baseCAL.isBackdatedTrx())) {
        BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(basetrx, true, getCostCurrency());
        BigDecimal trxPrice = null;
        if (basetrx.getMovementQuantity().signum() == 0) {
            trxPrice = BigDecimal.ZERO;
        } else {
            trxPrice = trxUnitCost.add(unitCostAdjustmentBalance).divide(basetrx.getMovementQuantity().abs(),
                    costCurPrecission, RoundingMode.HALF_UP);
        }
        if (checkNegativeStockCorrection && currentStock.compareTo(basetrx.getMovementQuantity()) < 0
                && cost.compareTo(trxPrice) != 0 && !baseCAL.isNegativeStockCorrection()
                && AverageAlgorithm.modifiesAverage(trxType)) {
            // stock was negative and cost different than trx price then Negative Stock Correction
            // is added
            BigDecimal trxSignMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
            BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                    .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                    .subtract(adjustmentBalance);
            adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
            // If there is a difference insert a cost adjustment line.
            CostAdjustmentLine newCAL = insertCostAdjustmentLine(basetrx, negCorrAmt, null);
            newCAL.setNegativeStockCorrection(Boolean.TRUE);
            newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
            newCAL.setUnitCost(Boolean.FALSE);
            OBDal.getInstance().save(newCAL);
            cost = trxPrice;
            log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                    cost.toPlainString());
        }
        if (basetrx.getMaterialMgmtCostingList().size() == 0) {
            Date newDate = new Date();
            Date dateTo = costing.getEndingDate();
            costing.setEndingDate(newDate);
            OBDal.getInstance().save(costing);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(basetrx);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(basetrx.getMovementQuantity());
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
            OBDal.getInstance().flush();
        } else {
            Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0);

            if (curCosting.getCost().compareTo(cost) != 0
                    || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                curCosting.setPermanent(Boolean.FALSE);
                OBDal.getInstance().save(curCosting);
                OBDal.getInstance().flush();
                // Update existing costing
                if (curCosting.getCost().compareTo(cost) != 0) {
                    if (curCosting.getOriginalCost() == null) {
                        curCosting.setOriginalCost(curCosting.getCost());
                    }
                    curCosting.setCost(cost);
                    curCosting.setPrice(trxPrice);
                }
                curCosting.setTotalMovementQuantity(currentStock);
                curCosting.setPermanent(Boolean.TRUE);
                OBDal.getInstance().flush();
                OBDal.getInstance().save(curCosting);
            }
        }
    }

    // Modify isManufacturingProduct flag in case it has changed at some point.
    isManufacturingProduct = ((String) DalUtil.getId(costing.getOrganization())).equals("0");

    ScrollableResults trxs = getRelatedTransactions();
    String strCurrentCurId = strCostCurrencyId;
    try {
        while (trxs.next()) {
            MaterialTransaction trx = (MaterialTransaction) trxs.get()[0];
            log.debug("Process related transaction {}", trx.getIdentifier());
            BigDecimal trxSignMultiplier = new BigDecimal(trx.getMovementQuantity().signum());
            BigDecimal trxAdjAmt = BigDecimal.ZERO;
            BigDecimal trxUnitCostAdjAmt = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(bdCostingId) && !isBackdatedTransaction(trx)) {
                // If there is a backdated source adjustment pending modify the dates of its m_costing.
                updateBDCostingTimeRange(trx);
                // This update is done only on the first related transaction.
                bdCostingId = "";
            }

            if (!strCurrentCurId.equals(trx.getCurrency().getId())) {
                Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                Organization costOrg = getCostOrg();

                currentValueAmt = FinancialUtils.getConvertedAmount(currentValueAmt, curCurrency,
                        trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_STANDARD);
                if (cost != null) {
                    cost = FinancialUtils.getConvertedAmount(cost, curCurrency, trx.getCurrency(),
                            trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_COSTING);
                }

                strCurrentCurId = trx.getCurrency().getId();
            }

            List<CostAdjustmentLine> existingAdjLines = getTrxAdjustmentLines(trx);
            for (CostAdjustmentLine existingCAL : existingAdjLines) {
                if (existingCAL.isSource() && !existingCAL.isRelatedTransactionAdjusted()) {
                    searchRelatedTransactionCosts(existingCAL);
                }
                if (existingCAL.getTransactionCostList().isEmpty()
                        && !existingCAL.isRelatedTransactionAdjusted()) {
                    BigDecimal adjustmentAmt = existingCAL.getAdjustmentAmount();
                    if (!strCurrentCurId.equals(existingCAL.getCurrency().getId())) {
                        Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                        adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt,
                                existingCAL.getCurrency(), curCurrency, existingCAL.getAccountingDate(),
                                getCostOrg(), FinancialUtils.PRECISION_STANDARD);
                    }
                    trxAdjAmt = trxAdjAmt.add(adjustmentAmt);
                    adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(trxSignMultiplier));
                    if (existingCAL.isUnitCost()) {
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(adjustmentAmt);
                    }
                }

                existingCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                existingCAL.setParentCostAdjustmentLine((CostAdjustmentLine) OBDal.getInstance()
                        .getProxy(CostAdjustmentLine.ENTITY_NAME, strCostAdjLineId));

                OBDal.getInstance().save(existingCAL);
            }
            log.debug("Current trx adj amount of existing CALs {}", trxAdjAmt.toPlainString());

            BigDecimal trxCost = CostAdjustmentUtils.getTrxCost(trx, false,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            currentValueAmt = currentValueAmt.add(trxCost.multiply(trxSignMultiplier));
            currentStock = currentStock.add(trx.getMovementQuantity());
            log.debug("Updated current stock {} and, current value {}", currentStock.toPlainString(),
                    currentValueAmt.toPlainString());

            TrxType currentTrxType = TrxType.getTrxType(trx);

            if (AverageAlgorithm.modifiesAverage(currentTrxType)) {
                // Recalculate average, if current stock is zero the average is not modified
                if (currentStock.signum() != 0) {
                    cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                            RoundingMode.HALF_UP);
                }
                if (cost == null) {
                    continue;
                }
                log.debug("New average cost: {}", cost.toPlainString());
                Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                BigDecimal trxPrice = null;
                if (trx.getMovementQuantity().signum() == 0) {
                    trxPrice = BigDecimal.ZERO;
                } else {
                    trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                            costCurPrecission, RoundingMode.HALF_UP);
                }

                if (checkNegativeStockCorrection && currentStock.compareTo(trx.getMovementQuantity()) < 0
                        && cost.compareTo(trxPrice) != 0) {
                    // stock was negative and cost different than trx price then Negative Stock Correction
                    // is added
                    BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                            .subtract(adjustmentBalance);
                    adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
                    trxAdjAmt = trxAdjAmt.add(negCorrAmt.multiply(trxSignMultiplier));
                    // If there is a difference insert a cost adjustment line.
                    CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, negCorrAmt, null);
                    newCAL.setNegativeStockCorrection(Boolean.TRUE);
                    newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                    newCAL.setUnitCost(Boolean.FALSE);
                    OBDal.getInstance().save(newCAL);
                    cost = trxPrice;
                    log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                            cost.toPlainString());
                }

                if (curCosting.getCost().compareTo(cost) == 0 && StringUtils.isEmpty(bdCostingId)
                        && curCosting.getTotalMovementQuantity().compareTo(currentStock) == 0) {
                    // new cost hasn't changed and total movement qty is equal to current stock, following
                    // transactions will have the same cost, so no more
                    // related transactions are needed to include.
                    // If bdCosting is not empty it is needed to loop through the next related transaction
                    // to set the new time ringe of the costing.
                    log.debug("New cost matches existing cost. Adjustment finished.");
                    return;
                } else {
                    // Update existing costing
                    curCosting.setPermanent(Boolean.FALSE);
                    OBDal.getInstance().save(curCosting);
                    OBDal.getInstance().flush();
                    if (curCosting.getCost().compareTo(cost) != 0) {
                        if (curCosting.getOriginalCost() == null) {
                            curCosting.setOriginalCost(curCosting.getCost());
                        }
                        curCosting.setPrice(trxPrice);
                        curCosting.setCost(cost);
                    }
                    curCosting.setTotalMovementQuantity(currentStock);
                    curCosting.setPermanent(Boolean.TRUE);
                    OBDal.getInstance().save(curCosting);
                }
            } else if (cost != null && !isVoidedTrx(trx, currentTrxType)) {
                if (!trx.isCostPermanent()) {
                    // Check current trx unit cost matches new expected cost
                    BigDecimal expectedCost = cost.multiply(trx.getMovementQuantity().abs())
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP);
                    BigDecimal unitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                            OBDal.getInstance().get(Currency.class, strCurrentCurId));
                    unitCost = unitCost.add(trxAdjAmt);
                    log.debug("Is adjustment needed? Expected {} vs Current {}", expectedCost.toPlainString(),
                            unitCost.toPlainString());
                    if (expectedCost.compareTo(unitCost) != 0) {
                        trxAdjAmt = trxAdjAmt.add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(expectedCost.subtract(unitCost));
                        adjustmentBalance = adjustmentBalance
                                .add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        // If there is a difference insert a cost adjustment line.
                        CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx,
                                expectedCost.subtract(unitCost), null);
                        newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                        OBDal.getInstance().save(newCAL);
                        log.debug("Adjustment added. Amount {}.",
                                expectedCost.subtract(unitCost).toPlainString());
                    }
                }
                if (trx.getMaterialMgmtCostingList().size() != 0) {
                    Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                    if (currentStock.signum() != 0) {
                        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                                RoundingMode.HALF_UP);
                    }
                    BigDecimal trxPrice = null;
                    if (trx.getMovementQuantity().signum() == 0) {
                        trxPrice = BigDecimal.ZERO;
                    } else {
                        trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                                costCurPrecission, RoundingMode.HALF_UP);
                    }
                    if (curCosting.getCost().compareTo(cost) != 0
                            || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                        curCosting.setPermanent(Boolean.FALSE);
                        OBDal.getInstance().save(curCosting);
                        OBDal.getInstance().flush();
                        if (curCosting.getCost().compareTo(cost) != 0) {
                            if (curCosting.getOriginalCost() == null) {
                                curCosting.setOriginalCost(curCosting.getCost());
                            }
                            curCosting.setPrice(trxPrice);
                            curCosting.setCost(cost);
                        }
                        curCosting.setTotalMovementQuantity(currentStock);
                        curCosting.setPermanent(Boolean.TRUE);
                        OBDal.getInstance().save(curCosting);
                    }
                }
            }

            OBDal.getInstance().flush();
            OBDal.getInstance().getSession().clear();
        }
    } finally {
        trxs.close();
    }

    if (getCostingRule().getEndingDate() == null && cost != null) {
        // This is the current costing rule. Check if current average cost needs to be updated.
        Costing currentCosting = AverageAlgorithm.getProductCost(new Date(), basetrx.getProduct(),
                getCostDimensions(), getCostOrg());
        if (currentCosting == null) {
            throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName()
                    + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: "
                    + OBDateUtils.formatDate(new Date()));
        }
        if (currentCosting.getCost().compareTo(cost) != 0) {
            basetrx = getTransaction();
            Date newDate = new Date();
            Date dateTo = currentCosting.getEndingDate();
            currentCosting.setEndingDate(newDate);
            OBDal.getInstance().save(currentCosting);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCurrentCurId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(null);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(null);
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
        }
    }
}

From source file:org.yes.cart.payment.impl.PostFinancePaymentGatewayImpl.java

/**
 * {@inheritDoc}//  w w  w.  ja va 2 s.c o  m
 */
public String getHtmlForm(final String cardHolderName, final String locale, final BigDecimal amount,
        final String currencyCode, final String orderReference, final Payment payment) {

    // Parameters must be in apha order for hash
    final Map<String, String> params = new TreeMap<String, String>();

    // 1. general parameters

    // Your affiliation name in our system
    params.put("PSPID", getParameterValue(PF_PSPID));
    // Your unique order number (merchant reference). The system checks that a payment has not been requested twice
    // for the same order. The ORDERID has to be assigned dynamically.
    params.put("ORDERID", orderReference);
    // Amount to be paid MULTIPLIED BY 100 since the format of the amount must not contain any decimals or other separators.
    // The amount must be assigned dynamically.
    params.put("AMOUNT", amount.multiply(MoneyUtils.HUNDRED).setScale(0, RoundingMode.HALF_UP).toPlainString());
    // ISO alpha order currency code, for example: EUR, USD, GBP, CHF, ...
    params.put("CURRENCY", currencyCode);
    // Language of the customer, for example: en_US, nl_NL, fr_FR, ...
    params.put("LANGUAGE", paymentLocaleTranslator.translateLocale(this, locale));

    // 2. optional customer details, highly recommended for fraud prevention

    // Customer name. It will be pre-initialised (but still editable) in the cardholder name field of the credit card details.
    setValueIfNotNull(params, "CN", cardHolderName);
    // Customers e-mail address
    setValueIfNotNull(params, "EMAIL", payment.getBillingEmail());

    final PaymentAddress address = payment.getBillingAddress();
    if (address != null) {
        // Customers street name and number
        setValueIfNotNull(params, "OWNERADDRESS", getAddressLines(address));
        // Customers postcode
        setValueIfNotNull(params, "OWNERZIP", address.getPostcode());
        // Customers town/city name
        setValueIfNotNull(params, "OWNERTOWN", address.getCity());
        // Customers country
        setValueIfNotNull(params, "OWNERCTY", address.getCountryCode());
        // Customers telephone number
        setValueIfNotNull(params, "OWNERTELNO", address.getPhone1());
    }

    // Order description
    final boolean itemised = Boolean.valueOf(getParameterValue(PF_ITEMISED));
    params.put("COM", getDescription(payment, itemised));
    if (itemised) {
        populateItems(payment, params);
    }

    // 3. layout information: see Look & Feel of the Payment Page

    // Title and header of the page
    setParameterIfNotNull(params, "TITLE", PF_STYLE_TITLE);
    // Background colour
    setParameterIfNotNull(params, "BGCOLOR", PF_STYLE_BGCOLOR);
    // Text colour
    setParameterIfNotNull(params, "TXTCOLOR", PF_STYLE_TXTCOLOR);
    // Table background colour
    setParameterIfNotNull(params, "TBLBGCOLOR", PF_STYLE_TBLBGCOLOR);
    // Table text colour
    setParameterIfNotNull(params, "TBLTXTCOLOR", PF_STYLE_TBLTXTCOLOR);
    // Button background colour
    setParameterIfNotNull(params, "BUTTONBGCOLOR", PF_STYLE_BUTTONBGCOLOR);
    // Button text colour
    setParameterIfNotNull(params, "BUTTONTXTCOLOR", PF_STYLE_BUTTONTXTCOLOR);
    // Font family
    setParameterIfNotNull(params, "FONTTYPE", PF_STYLE_FONTTYPE);
    // URL/filename of the logo you want to display at the top of the payment page, next to the title.
    // The URL must be absolute (i.e. contain the full path), it cannot be relative.
    setParameterIfNotNull(params, "LOGO", PF_STYLE_LOGO);

    // 4. dynamic template page: see Look & Feel of the Payment Page
    setParameterIfNotNull(params, "TP", PF_STYLE_TP);

    // 5. payment methods/page specifics: see Payment method and payment page specifics
    // Payment method e.g. CreditCard, iDEAL or blank
    setParameterIfNotNull(params, "PM", PF_PM);
    // Credit card brand e.g. VISA or blank
    setParameterIfNotNull(params, "BRAND", PF_BRAND);
    // 3-D secure: MAINW or POPUP
    setParameterIfNotNull(params, "WIN3DS", PF_WIN3DS);
    // List of selected payment methods and/or credit card brands. Separated by a ;? (semicolon).  e.g. VISA;iDEAL
    setParameterIfNotNull(params, "PMLIST", PF_PMLIST);
    // List of payment methods and/or credit card brands that should NOT be shown. Separated by a ;? (semicolon).
    setParameterIfNotNull(params, "EXCLPMLIST", PF_EXCLPMLIST);
    // The possible values are 0, 1 and 2:
    // 0: Horizontally grouped logos with the group name on the left (default value)
    // 1: Horizontally grouped logos with no group names
    // 2: Vertical list of logos with specific payment method or brand name
    setParameterIfNotNull(params, "PMLISTTYPE", PF_PMLISTTYPE);

    // 6. link to your website: see Default reaction
    setParameterIfNotNull(params, "HOMEURL", PF_RESULT_URL_HOME);
    setParameterIfNotNull(params, "CATALOGURL", PF_RESULT_URL_CATALOG);

    // 7. post payment parameters: see Redirection depending on the payment result
    // <input type="hidden" name="COMPLUS" value="">
    // <input type="hidden" name="PARAMPLUS" value="">

    // 8. post payment parameters: see Direct feedback requests (Post-payment)
    // <input type="hidden" name="PARAMVAR" value="">

    // 9.  post payment redirection: see Redirection depending on the payment result
    setParameterIfNotNull(params, "ACCEPTURL", PF_RESULT_URL_ACCEPT);
    setParameterIfNotNull(params, "DECLINEURL", PF_RESULT_URL_DECLINE);
    setParameterIfNotNull(params, "EXCEPTIONURL", PF_RESULT_URL_EXCEPTION);
    setParameterIfNotNull(params, "CANCELURL", PF_RESULT_URL_CANCEL);

    // 10. optional operation field: see Operation
    // Operation code for the transaction. Possible values for new orders:
    // RES: request for authorisation
    // SAL: request for sale (payment)
    // NOTE: for now we shall support only SAL (AUTH_CAPTURE) because PostFinance does not have CAPTURE API and merchants
    //       need to login to their system to CAPTURE payments, which is a bit inconvenient and does nothave integration
    //       with YC.
    params.put("OPERATION", getExternalFormOperation());

    // 11. optional extra login detail field: see User field
    setValueIfNotNull(params, "USERID", payment.getBillingEmail());

    // 12. Alias details: see Alias Management documentation
    //        <input type="hidden" name="ALIAS" value="">
    //        <input type="hidden" name="ALIASUSAGE" value="">
    //        <input type="hidden" name="ALIASOPERATION" value="">

    // 13. check before the payment: see SHA-IN signature
    params.put("SHASIGN", sha1sign(params, getParameterValue(PF_SHA_IN)));

    final StringBuilder form = new StringBuilder();
    for (final Map.Entry<String, String> param : params.entrySet()) {
        form.append(getHiddenField(param.getKey(), param.getValue()));
    }

    form.append(getHiddenField("SUBMIT2", ""));

    return form.toString();

}

From source file:org.pentaho.plugin.jfreereport.reportcharts.PieChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final Plot plot = chart.getPlot();
    final PiePlot pp = (PiePlot) plot;
    final PieDataset pieDS = pp.getDataset();
    pp.setDirection(rotationClockwise ? Rotation.CLOCKWISE : Rotation.ANTICLOCKWISE);
    if ((explodeSegment != null) && (explodePct != null)) {
        configureExplode(pp);/*from  ww w. j  a  v a  2 s.  c o m*/
    }
    if (StringUtils.isEmpty(getTooltipFormula()) == false) {
        pp.setToolTipGenerator(new FormulaPieTooltipGenerator(getRuntime(), getTooltipFormula()));
    }
    if (StringUtils.isEmpty(getUrlFormula()) == false) {
        pp.setURLGenerator(new FormulaPieURLGenerator(getRuntime(), getUrlFormula()));
    }

    pp.setIgnoreNullValues(ignoreNulls);
    pp.setIgnoreZeroValues(ignoreZeros);
    if (Boolean.FALSE.equals(getItemsLabelVisible())) {
        pp.setLabelGenerator(null);
    } else {
        final ExpressionRuntime runtime = getRuntime();
        final Locale locale = runtime.getResourceBundleFactory().getLocale();

        final FastDecimalFormat fastPercent = new FastDecimalFormat(FastDecimalFormat.TYPE_PERCENT, locale);
        final FastDecimalFormat fastInteger = new FastDecimalFormat(FastDecimalFormat.TYPE_INTEGER, locale);

        final DecimalFormat numFormat = new DecimalFormat(fastInteger.getPattern(),
                new DecimalFormatSymbols(locale));
        numFormat.setRoundingMode(RoundingMode.HALF_UP);

        final DecimalFormat percentFormat = new DecimalFormat(fastPercent.getPattern(),
                new DecimalFormatSymbols(locale));
        percentFormat.setRoundingMode(RoundingMode.HALF_UP);

        final StandardPieSectionLabelGenerator labelGen = new StandardPieSectionLabelGenerator(pieLabelFormat,
                numFormat, percentFormat);
        pp.setLabelGenerator(labelGen);

        final StandardPieSectionLabelGenerator legendGen = new StandardPieSectionLabelGenerator(
                pieLegendLabelFormat, numFormat, percentFormat);
        pp.setLegendLabelGenerator(legendGen);
    }

    if (StringUtils.isEmpty(getLabelFont()) == false) {
        pp.setLabelFont(Font.decode(getLabelFont()));
    }

    if (pieDS != null) {
        final String[] colors = getSeriesColor();
        for (int i = 0; i < colors.length; i++) {
            if (i < pieDS.getItemCount()) {
                pp.setSectionPaint(pieDS.getKey(i), parseColorFromString(colors[i]));
            } else {
                break;
            }
        }
    }

    if (shadowPaint != null) {
        pp.setShadowPaint(shadowPaint);
    }
    if (shadowXOffset != null) {
        pp.setShadowXOffset(shadowXOffset.doubleValue());
    }
    if (shadowYOffset != null) {
        pp.setShadowYOffset(shadowYOffset.doubleValue());
    }
    pp.setCircular(circular);

    if (isShowBorder() == false || isChartSectionOutline() == false) {
        chart.setBorderVisible(false);
        chart.getPlot().setOutlineVisible(false);
    }

}

From source file:org.businessmanager.web.controller.page.invoice.InvoiceEditController.java

public BigDecimal getTotalGrossPrice() {
    BigDecimal totalGrossPrice = BigDecimal.ZERO;
    for (LineItemBean lineItem : bean.getLineItems()) {
        BigDecimal sumPrice = lineItem.getSumPriceGross();
        totalGrossPrice = totalGrossPrice.add(sumPrice);
    }//from  w  w  w .java2s .  c  o  m

    return totalGrossPrice.setScale(2, RoundingMode.HALF_UP);
}

From source file:com.autentia.tnt.manager.billing.BillManager.java

public List<BillBreakDown> getAllBitacoreBreakDowns(Date start, Date end, Project project) {

    final List<BillBreakDown> desgloses = new ArrayList<BillBreakDown>();

    ActivityDAO activityDAO = ActivityDAO.getDefault();
    ActivitySearch actSearch = new ActivitySearch();
    actSearch.setBillable(new Boolean(true));
    actSearch.setStartStartDate(start);//  ww w  .j  a  v a2  s  . c  o m
    actSearch.setEndStartDate(end);

    List<Activity> actividadesTotal = new ArrayList<Activity>();
    Hashtable user_roles = new Hashtable();

    ProjectRoleDAO projectRoleDAO = ProjectRoleDAO.getDefault();
    ProjectRoleSearch prjRolSearch = new ProjectRoleSearch();
    prjRolSearch.setProject(project);
    List<ProjectRole> roles = projectRoleDAO.search(prjRolSearch, new SortCriteria("id", false));
    for (ProjectRole proyRole : roles) {
        actSearch.setRole(proyRole);
        List<Activity> actividades = activityDAO.search(actSearch, new SortCriteria("startDate", false));
        actividadesTotal.addAll(actividades);
    }

    for (Activity act : actividadesTotal) {
        String key = act.getRole().getId().toString() + act.getUser().getId().toString();

        if (!user_roles.containsKey(key)) {
            Hashtable value = new Hashtable();
            value.put("ROLE", act.getRole());
            value.put("USER", act.getUser());
            user_roles.put(key, value);
        }
    }

    Enumeration en = user_roles.keys();

    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        Hashtable pair = (Hashtable) user_roles.get(key);
        actSearch.setBillable(new Boolean(true));
        actSearch.setStartStartDate(start);
        actSearch.setEndStartDate(end);

        ProjectRole pR = (ProjectRole) pair.get("ROLE");
        User u = (User) pair.get("USER");
        actSearch.setRole(pR);
        actSearch.setUser(u);
        List<Activity> actividadesUsuarioRol = activityDAO.search(actSearch,
                new SortCriteria("startDate", false));

        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Imputaciones (usuario - rol): " + u.getName() + " - " + pR.getName());
        brd.setAmount(pR.getCostPerHour());

        IvaApplicator.applyIvaToTaxableObject(start, brd);

        BigDecimal unitsTotal = new BigDecimal(0);
        for (Activity act : actividadesUsuarioRol) {
            BigDecimal unitsActual = new BigDecimal(act.getDuration());
            unitsActual = unitsActual.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
            unitsTotal = unitsTotal.add(unitsActual);
        }
        brd.setUnits(unitsTotal);
        brd.setSelected(true);
        desgloses.add(brd);
    }

    ProjectCostDAO prjCostDAO = ProjectCostDAO.getDefault();
    ProjectCostSearch prjCostSearch = new ProjectCostSearch();
    prjCostSearch.setProject(project);
    List<ProjectCost> costes = prjCostDAO.search(prjCostSearch, new SortCriteria("id", false));
    for (ProjectCost proyCost : costes) {
        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Coste: " + proyCost.getName());
        brd.setUnits(new BigDecimal(1));
        brd.setAmount(proyCost.getCost());

        IvaApplicator.applyIvaToTaxableObject(start, brd);

        brd.setSelected(true);
        desgloses.add(brd);
    }

    return desgloses;

}

From source file:mx.edu.um.mateo.inventario.web.SalidaController.java

@RequestMapping("/ver/{id}")
public String ver(@PathVariable Long id, Model modelo) {
    log.debug("Mostrando salida {}", id);
    Salida salida = salidaDao.obtiene(id);
    switch (salida.getEstatus().getNombre()) {
    case Constantes.ABIERTA:
        modelo.addAttribute("puedeEditar", true);
        modelo.addAttribute("puedeEliminar", true);
        modelo.addAttribute("puedeCerrar", true);
        break;//from   www.j  a v a2  s . c o m
    case Constantes.CERRADA:
        modelo.addAttribute("puedeCancelar", true);
        modelo.addAttribute("puedeReporte", true);
        break;
    case Constantes.CANCELADA:
        log.debug("Puede ver reporte");
        modelo.addAttribute("puedeReporte", true);
        break;
    }

    modelo.addAttribute("salida", salida);

    BigDecimal subtotal = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    BigDecimal iva = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    for (LoteSalida lote : salida.getLotes()) {
        subtotal = subtotal.add(lote.getPrecioUnitario().multiply(lote.getCantidad()));
        iva = iva.add(lote.getIva());
    }
    BigDecimal total = subtotal.add(iva);
    modelo.addAttribute("subtotal", subtotal.setScale(2, RoundingMode.HALF_UP));
    modelo.addAttribute("iva", iva);
    modelo.addAttribute("total", total.setScale(2, RoundingMode.HALF_UP));
    if (iva.compareTo(salida.getIva()) == 0 && total.compareTo(salida.getTotal()) == 0) {
        modelo.addAttribute("estiloTotales", "label label-success");
    } else {
        BigDecimal variacion = new BigDecimal("0.05");
        BigDecimal topeIva = salida.getIva().multiply(variacion);
        BigDecimal topeTotal = salida.getTotal().multiply(variacion);
        log.debug("Estilos {} {} {} {} {} {}",
                new Object[] { iva, salida.getIva(), topeIva, total, salida.getTotal(), topeTotal });
        if (iva.compareTo(salida.getIva()) < 0 || total.compareTo(salida.getTotal()) < 0) {
            log.debug("La diferencia es menor");
            if (iva.compareTo(salida.getIva().subtract(topeIva)) >= 0
                    && total.compareTo(salida.getTotal().subtract(topeTotal)) >= 0) {
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        } else {
            log.debug("La diferencia es mayor {} {}",
                    new Object[] { iva.compareTo(salida.getIva().add(topeIva)),
                            total.compareTo(salida.getTotal().add(topeTotal)) });
            if (iva.compareTo(salida.getIva().add(topeIva)) <= 0
                    && total.compareTo(salida.getTotal().add(topeTotal)) <= 0) {
                log.debug("estilo warning");
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                log.debug("estilo error");
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        }
    }

    return "inventario/salida/ver";
}