Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

In this page you can find the example usage for java.math BigDecimal compareTo.

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:com.jeans.iservlet.service.asset.impl.AssetServiceImpl.java

@Override
@Transactional/*from  ww w  . j  ava2 s.  c o m*/
public int saveProps(Set<Long> ids, byte type, Map<String, Object> props) {
    if (ids.isEmpty()) {
        return 0;
    }
    if (ids.size() == 1) {
        Asset asset = loadAsset(ids.iterator().next(), type);
        if (null == asset) {
            return 0;
        }
        /*
         * ? ?? null?null -99???? ?
         */
        asset.setName((String) props.get("name"));
        asset.setVendor((String) props.get("vendor"));
        asset.setModelOrVersion((String) props.get("modelOrVersion"));
        asset.setAssetUsage((String) props.get("assetUsage"));
        asset.setPurchaseTime((Date) props.get("purchaseTime"));
        int q = (int) props.get("quantity");
        asset.setQuantity(q < 0 ? 1 : q);
        BigDecimal c = (BigDecimal) props.get("cost");
        asset.setCost(c.compareTo(BigDecimal.ZERO) == -1 ? BigDecimal.ZERO : c);
        asset.setComment((String) props.get("comment"));
        if (asset instanceof Hardware) {
            ((Hardware) asset).setCode((String) props.get("code"));
            ((Hardware) asset).setFinancialCode((String) props.get("financialCode"));
            ((Hardware) asset).setSn((String) props.get("sn"));
            ((Hardware) asset).setConfiguration((String) props.get("configuration"));
            byte w = (byte) props.get("warranty");
            if (w >= -1 && w <= 1) {
                ((Hardware) asset).setWarranty(w);
            }
            ((Hardware) asset).setLocation((String) props.get("location"));
            ((Hardware) asset).setIp((String) props.get("ip"));
            byte i = (byte) props.get("importance");
            if (i >= 0 && i <= 2) {
                ((Hardware) asset).setImportance(i);
            }
            hwDao.update((Hardware) asset);
            return 1;
        } else if (asset instanceof Software) {
            byte s = (byte) props.get("softwareType");
            if (s >= 0 && s <= 6) {
                ((Software) asset).setSoftwareType(s);
            }
            ((Software) asset).setLicense((String) props.get("license"));
            ((Software) asset).setExpiredTime((Date) props.get("expiredTime"));
            swDao.update((Software) asset);
            return 1;
        } else {
            return 0;
        }
    } else {
        List<Asset> assets = loadAssets(ids, type);
        int count = assets.size();
        for (Asset asset : assets) {
            /*
             *  ????? null????? -99????? ?????
             */
            String v = (String) props.get("name");
            if (!StringUtils.isEmpty(v)) {
                asset.setName(v);
            }
            v = (String) props.get("vendor");
            if (!StringUtils.isEmpty(v)) {
                asset.setVendor(v);
            }
            v = (String) props.get("modelOrVersion");
            if (!StringUtils.isEmpty(v)) {
                asset.setModelOrVersion(v);
            }
            v = (String) props.get("assetUsage");
            if (!StringUtils.isEmpty(v)) {
                asset.setAssetUsage(v);
            }
            Date d = (Date) props.get("purchaseTime");
            if (null != d) {
                asset.setPurchaseTime(d);
            }
            int q = (int) props.get("quantity");
            if (q >= 0) {
                asset.setQuantity(q);
            }
            BigDecimal c = (BigDecimal) props.get("cost");
            if (c.compareTo(BigDecimal.ZERO) != -1) {
                asset.setCost(c);
            }
            v = (String) props.get("comment");
            if (!StringUtils.isEmpty(v)) {
                asset.setComment(v);
            }
            if (asset instanceof Hardware) {
                v = (String) props.get("sn");
                if (!StringUtils.isEmpty(v)) {
                    ((Hardware) asset).setSn(v);
                }
                v = (String) props.get("configuration");
                if (!StringUtils.isEmpty(v)) {
                    ((Hardware) asset).setConfiguration(v);
                }
                byte w = (byte) props.get("warranty");
                if (w >= -1 && w <= 1) {
                    ((Hardware) asset).setWarranty(w);
                }
                v = (String) props.get("location");
                if (!StringUtils.isEmpty(v)) {
                    ((Hardware) asset).setLocation(v);
                }
                v = (String) props.get("ip");
                if (!StringUtils.isEmpty(v)) {
                    ((Hardware) asset).setIp(v);
                }
                byte i = (byte) props.get("importance");
                if (i >= 0 && i <= 2) {
                    ((Hardware) asset).setImportance(i);
                }
                hwDao.update((Hardware) asset);
            } else if (asset instanceof Software) {
                byte s = (byte) props.get("softwareType");
                if (s >= 0 && s <= 6) {
                    ((Software) asset).setSoftwareType(s);
                }
                v = (String) props.get("license");
                if (!StringUtils.isEmpty(v)) {
                    ((Software) asset).setLicense(v);
                }
                d = (Date) props.get("expiredTime");
                if (null != d) {
                    ((Software) asset).setExpiredTime(d);
                }
                swDao.update((Software) asset);
            } else {
                count--;
            }
        }
        return count;
    }
}

From source file:com.axelor.apps.account.service.payment.PayboxService.java

/**
 * Procdure permettant de vrifier que le montant rgl par Paybox n'est pas suprieur au solde du payeur
 * @param partner//from   w w  w.j  a v  a 2s.  c  o m
 * @param paidAmount
 * @throws AxelorException
 */
public void checkPaidAmount(Partner partner, Company company, BigDecimal paidAmount) throws AxelorException {
    AccountingSituation accountingSituation = Beans.get(AccountingSituationService.class)
            .getAccountingSituation(partner, company);

    BigDecimal partnerBalance = accountingSituation.getBalanceCustAccount();

    if (paidAmount.compareTo(partnerBalance) > 0) {
        throw new AxelorException(
                String.format(I18n.get(IExceptionMessage.PAYBOX_2), GeneralServiceImpl.EXCEPTION),
                IException.CONFIGURATION_ERROR);
    }

}

From source file:org.alfresco.extension.bulkimport.impl.BatchImporterImpl.java

private final void importVersion(final NodeRef nodeRef, final BulkImportItemVersion previousVersion,
        final BulkImportItemVersion version, final boolean dryRun, final boolean onlyOneVersion)
        throws InterruptedException {
    Map<String, Serializable> versionProperties = new HashMap<>();
    boolean isMajor = true;

    if (version == null) {
        throw new IllegalStateException(
                "version was null. This is indicative of a bug in the chosen import source.");
    }/*from ww  w.  j ava2 s.c om*/

    importVersionContentAndMetadata(nodeRef, version, dryRun);

    if (previousVersion != null && version.getVersionNumber() != null) {
        final BigDecimal difference = version.getVersionNumber().subtract(previousVersion.getVersionNumber());

        isMajor = difference.compareTo(BigDecimal.ONE) >= 0;
    }

    // Note: PROP_VERSION_LABEL is a "reserved" property, and cannot be modified by custom code.
    // In other words, we can't use the source's version label as the version label in Alfresco.  :-(
    // See: https://github.com/pmonks/alfresco-bulk-import/issues/13
    //        versionProperties.put(ContentModel.PROP_VERSION_LABEL.toString(), String.valueOf(version.getVersionNumber().toString()));

    versionProperties.put(VersionModel.PROP_VERSION_TYPE, isMajor ? VersionType.MAJOR : VersionType.MINOR);

    if (version.getVersionComment() != null) {
        versionProperties.put(Version.PROP_DESCRIPTION, version.getVersionComment());
    }

    if (dryRun) {
        if (info(log))
            info(log, "[DRY RUN] Would have created " + (isMajor ? "major" : "minor") + " version of node '"
                    + String.valueOf(nodeRef) + "'.");
    } else {
        // Only create versions if we have to - this is an exceptionally expensive operation in Alfresco
        if (onlyOneVersion) {
            if (trace(log))
                trace(log, "Skipping creation of a version for node '" + String.valueOf(nodeRef)
                        + "' as it only has one version.");
        } else {
            if (trace(log))
                trace(log, "Creating " + (isMajor ? "major" : "minor") + " version of node '"
                        + String.valueOf(nodeRef) + "'.");
            versionService.createVersion(nodeRef, versionProperties);
        }
    }
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.ProcessingLimitService.java

/**
 * Check notifications to sent//from w w w .  ja  va  2s. co  m
 * 
 * @param control
 * @param limit
 * @param total
 * @return
 */
@Transactional
private BigDecimal checkNotification(DbeExpendControl control, DbeExpendLimit limit, BigDecimal total) {
    ProcessingLimitUtil utils = new ProcessingLimitUtil();
    List<BigDecimal> limits = utils.getLimitsFromString(limit.getTxNotifAmounts());
    BigDecimal maxLevel = new BigDecimal(0);
    if (null != limits && limits.size() > 0) {
        for (BigDecimal value : limits) {
            // the total is equal or greater to the threshold
            if (total.compareTo(value) >= 0) {
                // Obtain the maxLevel
                if (value.compareTo(maxLevel) > 0) {
                    maxLevel = value;
                }
            }
        }
    }
    ProcessingLimitService.logger.debug("MaxLevel reached: " + maxLevel);
    // Compare against the notifications sent
    BigDecimal lastNotificationSent = utils.getLastNotificationSent(control.getTxNotifications());
    if (null == lastNotificationSent) {
        lastNotificationSent = new BigDecimal(0);
    }
    ProcessingLimitService.logger.debug("Last notification sent: " + lastNotificationSent);
    if (maxLevel.compareTo(lastNotificationSent) > 0) {
        ProcessingLimitService.logger.debug("Add Notification for level: " + maxLevel);
        // Add new notification and sent.
        control.setTxNotifications(utils.addValueToLimits(maxLevel, control.getTxNotifications()));
        expendControlDao.createOrUpdate(control);
        return maxLevel;
    }
    return new BigDecimal(0);
}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Method is executed on update trigger for the amount field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger/*from  www.  ja va 2  s .  com*/
 * @throws EFapsException on error
 */
public Return update4Amount(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();
    try {
        final String postfix = getProperty(_parameter, "TypePostfix");
        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);
        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Amount.ParseException", e);
    }
    return retVal;
}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Method is executed on update trigger for the rate field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger/*from w w w  .  jav  a 2s . c  o m*/
 * @throws EFapsException on error
 */
public Return update4Rate(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();

    try {
        final String postfix = getProperty(_parameter, "TypePostfix");

        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ONE : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);

        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Rate.ParseException", e);
    }
    return retVal;
}

From source file:com.osafe.events.CheckOutEvents.java

public static String calcLoyaltyTax(HttpServletRequest request, HttpServletResponse response) {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);

    String isTaxedOnStore = (String) request.getAttribute("isTaxedOnStore");
    GenericValue shipAddress = null;//from w ww  .j  av  a 2 s .com
    if (UtilValidate.isNotEmpty(isTaxedOnStore) && "Y".equalsIgnoreCase(isTaxedOnStore)) {
        shipAddress = (GenericValue) request.getAttribute("taxedStoreAddress");
    }

    if (UtilValidate.isEmpty(cart.getShippingContactMechId()) && cart.getBillingAddress() == null
            && shipAddress == null) {
        return "success";
    }

    CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher, delegator, cart);
    BigDecimal orderAdjustmentOtherAmount = BigDecimal.ZERO;
    List<GenericValue> loyaltyAdjustments = EntityUtil.filterByAnd(cart.getAdjustments(),
            UtilMisc.toMap("orderAdjustmentTypeId", "LOYALTY_POINTS"));
    if (UtilValidate.isEmpty(loyaltyAdjustments)) {
        return "success";

    }

    BigDecimal loyaltyAdjTotal = BigDecimal.ZERO;

    Iterator<GenericValue> loyaltyAdjIter = loyaltyAdjustments.iterator();
    while (loyaltyAdjIter.hasNext()) {
        GenericValue loyaltyAdjustment = loyaltyAdjIter.next();

        if (UtilValidate.isNotEmpty(loyaltyAdjustment)) {
            BigDecimal amount = loyaltyAdjustment.getBigDecimal("amount").setScale(taxCalcScale, taxRounding);
            loyaltyAdjTotal = loyaltyAdjTotal.add(amount);
        }
    }

    if (loyaltyAdjTotal.compareTo(BigDecimal.ZERO) == 0) {
        return "success";

    }

    int shipGroups = cart.getShipGroupSize();
    for (int i = 0; i < shipGroups; i++) {
        Map shoppingCartItemIndexMap = new HashMap();
        Map serviceContext = null;
        ShoppingCart.CartShipInfo csi = cart.getShipInfo(i);
        if (shipAddress == null) {
            shipAddress = cart.getShippingAddress(i);
            // Debug.logInfo("====== makeTaxContext set shipAddress to cart.getShippingAddress(shipGroup): " + shipAddress, module);
        }

        try {

            int totalItems = csi.shipItemInfo.size();

            List product = new ArrayList(totalItems);
            List amount = new ArrayList(totalItems);
            List price = new ArrayList(totalItems);
            List shipAmt = new ArrayList(totalItems);

            Iterator<ShoppingCartItem> it = csi.shipItemInfo.keySet().iterator();
            for (int itemIdx = 0; itemIdx < totalItems; itemIdx++) {
                ShoppingCartItem cartItem = it.next();
                ShoppingCart.CartShipInfo.CartShipItemInfo itemInfo = csi.getShipItemInfo(cartItem);
                product.add(i, cartItem.getProduct());
                amount.add(i, cartItem.getItemSubTotal(itemInfo.quantity));
                price.add(i, cartItem.getBasePrice());
                shipAmt.add(i, BigDecimal.ZERO); // no per item shipping yet
                shoppingCartItemIndexMap.put(Integer.valueOf(itemIdx), cartItem);
            }

            serviceContext = UtilMisc.toMap("productStoreId", cart.getProductStoreId());
            serviceContext.put("payToPartyId", cart.getBillFromVendorPartyId());
            serviceContext.put("billToPartyId", cart.getBillToCustomerPartyId());
            serviceContext.put("itemProductList", product);
            serviceContext.put("itemAmountList", amount);
            serviceContext.put("itemPriceList", price);
            serviceContext.put("shippingAddress", shipAddress);
            serviceContext.put("orderLoyaltyAmount", loyaltyAdjTotal);
            Map serviceResult = null;

            try {
                serviceResult = dispatcher.runSync("calcAdjustmentTax", serviceContext);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }

            if (ServiceUtil.isError(serviceResult)) {
                Debug.logError(ServiceUtil.getErrorMessage(serviceResult), module);
                return "success";
            }

            // the adjustments (returned in order) from taxware.
            List orderAdj = (List) serviceResult.get("orderAdjustments");
            csi.shipTaxAdj.addAll(orderAdj);

        } catch (Exception e) {
            Debug.logError(e, module);
        }

    }
    return "success";
}

From source file:UserInterface.FinanceRole.DonateToPoorPeopleJPanel.java

private void donateJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_donateJButtonActionPerformed

    //Validation/*from w w w  .  j a  v  a 2 s.c om*/
    boolean validationSuccess;
    validationSuccess = validation();

    if (validationSuccess) {

        Person objPPPerson = null;
        UserAccount objPPUserAccount = null;

        int selectedPP = poorPeopleJTable.getSelectedRow();

        if (selectedPP < 0) {
            JOptionPane.showMessageDialog(null, "Please select a Person");
            return;
        }

        objPPUserAccount = (UserAccount) poorPeopleJTable.getValueAt(selectedPP, 2);

        if (objPPUserAccount != null) {
            objPPPerson = objPPUserAccount.getObjPerson();

            objWorldEnterprise.getObjTransactionDirectory().updateTransactionAccount();

            BigDecimal worldBalance = objWorldEnterprise.getObjTransactionDirectory().getAvailableRealBalance();

            int positiveWorldBalance = worldBalance.compareTo(donationAmount);

            if (positiveWorldBalance >= 1) {

                int response = JOptionPane.showConfirmDialog(null,
                        "Total donation of $ " + donationAmount + "/- Do you want to Donate?", "Confirm",
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.YES_OPTION) {

                    //PoorPeople Transaction
                    Transaction objVirtualPPTransaction = (Transaction) objPPPerson
                            .getObjPoorPeopleTransactionDirectory().addNewTransaction();
                    objVirtualPPTransaction
                            .setTransactionBDAmount(new BigDecimal(donationAmountJTextField.getText()));
                    objVirtualPPTransaction.setObjUserAccountSource(objUserAccount);
                    objVirtualPPTransaction.setObjUserAccountDestination(objPPUserAccount);
                    objVirtualPPTransaction.setTransactionSource(
                            Transaction.TransactionSourceType.FromWorldEnterprise.getValue());
                    objVirtualPPTransaction.setTransactionDestination(
                            Transaction.TransactionSourceType.ToPoorPeople.getValue());
                    objVirtualPPTransaction.setTransactionType(Transaction.TransactionType.Credit.getValue());
                    objVirtualPPTransaction
                            .setTransactionMode(Transaction.TransactionModeType.Virtual.getValue());
                    objPPPerson.getObjPoorPeopleTransactionDirectory().updateTransactionAccount();

                    //WorldEnterprise Transaction
                    Transaction objVirtualWETransaction = (Transaction) objWorldEnterprise
                            .getObjTransactionDirectory().addNewTransaction();
                    objVirtualWETransaction
                            .setTransactionBDAmount(new BigDecimal(donationAmountJTextField.getText()));
                    objVirtualWETransaction.setObjUserAccountSource(objUserAccount);
                    objVirtualWETransaction.setObjUserAccountDestination(objPPUserAccount);
                    objVirtualWETransaction.setTransactionSource(
                            Transaction.TransactionSourceType.FromWorldEnterprise.getValue());
                    objVirtualWETransaction.setTransactionDestination(
                            Transaction.TransactionSourceType.ToPoorPeople.getValue());
                    objVirtualWETransaction.setTransactionType(Transaction.TransactionType.Debit.getValue());
                    objVirtualWETransaction
                            .setTransactionMode(Transaction.TransactionModeType.Virtual.getValue());
                    objWorldEnterprise.getObjTransactionDirectory().updateTransactionAccount();

                    JOptionPane.showMessageDialog(null, "$ " + donationAmount + "/- donated successfully");

                    //DonationGivenRecords
                    String donationLogs = objVirtualWETransaction.getTransactionID() + ","
                            + objVirtualWETransaction.getTransactionBDAmount() + ","
                            + objVirtualWETransaction.getObjUserAccountSource() + ","
                            + objVirtualWETransaction.getTransactionSource() + ","
                            + objVirtualWETransaction.getObjUserAccountDestination() + ","
                            + objVirtualWETransaction.getTransactionDestination() + ","
                            + objVirtualWETransaction.getTransactionType() + ","
                            + objVirtualWETransaction.getTransactionMode();

                    GenerateReports.donationGivenRecords(donationLogs);

                    donationAmountJTextField.setText(null);

                    populateTransactionTable(objPPPerson);
                }
            } else {
                JOptionPane.showMessageDialog(null, "World Balance is low");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Please select again");
        }
    }
}

From source file:com.qcadoo.mes.operationTimeCalculations.OrderRealizationTimeServiceImpl.java

@Override
public int evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(Entity operationComponent,
        final boolean includeTpz, final boolean includeAdditionalTime,
        final Map<Long, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation,
        final OperationProductComponentWithQuantityContainer productComponentQuantities) {
    operationComponent = operationComponent.getDataDefinition().get(operationComponent.getId());
    BigDecimal cycles = BigDecimal.ONE;
    BigDecimal nextOperationAfterProducedQuantity = BigDecimalUtils
            .convertNullToZero(operationComponent.getDecimalField("nextOperationAfterProducedQuantity"));
    BigDecimal productComponentQuantity = productComponentQuantities.get(getOutputProduct(operationComponent));
    Entity technologyOperationComponent = getTechnologyOperationComponent(operationComponent);

    if (nextOperationAfterProducedQuantity.compareTo(productComponentQuantity) != 1) {
        cycles = getQuantityCyclesNeededToProducedNextOperationAfterProducedQuantity(
                technologyOperationComponent, nextOperationAfterProducedQuantity);
    } else {//  ww w . j av  a  2s .  co  m
        cycles = operationRuns.get(technologyOperationComponent.getId());
    }
    return evaluateOperationDurationOutOfCycles(cycles, operationComponent, productionLine, maxForWorkstation,
            includeTpz, includeAdditionalTime);
}

From source file:org.broadleafcommerce.core.pricing.service.workflow.FulfillmentItemPricingActivity.java

/**
 * Distributes the order adjustments (if any) to the individual fulfillment group items.
 * @param order/*  w  ww . java2s.c  o m*/
 * @param totalAllItems
 * @return
 */
protected Money distributeOrderSavingsToItems(Order order, BigDecimal totalAllItems) {
    Money returnAmount = new Money(order.getCurrency());

    BigDecimal orderAdjAmt = order.getOrderAdjustmentsValue().getAmount();

    for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {
        for (FulfillmentGroupItem fgItem : fulfillmentGroup.getFulfillmentGroupItems()) {
            BigDecimal fgItemAmount = fgItem.getTotalItemAmount().getAmount();
            BigDecimal proratedAdjAmt = totalAllItems.compareTo(BigDecimal.ZERO) == 0 ? totalAllItems
                    : orderAdjAmt.multiply(fgItemAmount).divide(totalAllItems, RoundingMode.FLOOR);
            fgItem.setProratedOrderAdjustmentAmount(new Money(proratedAdjAmt, order.getCurrency()));
            returnAmount = returnAmount.add(fgItem.getProratedOrderAdjustmentAmount());
        }
    }
    return returnAmount;
}