Modified: ofbiz/trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java?rev=731851&r1=731850&r2=731851&view=diff ============================================================================== --- ofbiz/trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java (original) +++ ofbiz/trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java Mon Jan 5 23:13:36 2009 @@ -253,17 +253,17 @@ if (currentProductId != null) { // only normalize items with a product associated (ignore non-product items) if (normalizedItemQuantities.get(currentProductId) == null) { - normalizedItemQuantities.put(currentProductId, new Double(orderItem.getDouble("quantity").doubleValue())); + normalizedItemQuantities.put(currentProductId, orderItem.getBigDecimal("quantity")); normalizedItemNames.put(currentProductId, orderItem.getString("itemDescription")); } else { - Double currentQuantity = (Double) normalizedItemQuantities.get(currentProductId); - normalizedItemQuantities.put(currentProductId, new Double(currentQuantity.doubleValue() + orderItem.getDouble("quantity").doubleValue())); + BigDecimal currentQuantity = (BigDecimal) normalizedItemQuantities.get(currentProductId); + normalizedItemQuantities.put(currentProductId, currentQuantity.add(orderItem.getBigDecimal("quantity"))); } try { // count product ordered quantities // run this synchronously so it will run in the same transaction - dispatcher.runSync("countProductQuantityOrdered", UtilMisc.<String, Object>toMap("productId", currentProductId, "quantity", orderItem.getDouble("quantity"), "userLogin", userLogin)); + dispatcher.runSync("countProductQuantityOrdered", UtilMisc.<String, Object>toMap("productId", currentProductId, "quantity", orderItem.getBigDecimal("quantity"), "userLogin", userLogin)); } catch (GenericServiceException e1) { Debug.logError(e1, "Error calling countProductQuantityOrdered service", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderErrorCallingCountProductQuantityOrderedService",locale) + e1.toString()); @@ -279,7 +279,7 @@ while (normalizedIter.hasNext()) { // lookup the product entity for each normalized item; error on products not found String currentProductId = (String) normalizedIter.next(); - Double currentQuantity = (Double) normalizedItemQuantities.get(currentProductId); + BigDecimal currentQuantity = (BigDecimal) normalizedItemQuantities.get(currentProductId); String itemName = (String) normalizedItemNames.get(currentProductId); GenericValue product = null; @@ -727,20 +727,19 @@ techDataCalendarExcDay = delegator.makeValue("TechDataCalendarExcDay"); techDataCalendarExcDay.set("calendarId", fixedAsset.get("calendarId")); techDataCalendarExcDay.set("exceptionDateStartTime", exceptionDateStartTime); - techDataCalendarExcDay.set("usedCapacity",new Double(00.00)); // initialise to zero - techDataCalendarExcDay.set("exceptionCapacity", fixedAsset.getDouble("productionCapacity")); + techDataCalendarExcDay.set("usedCapacity", BigDecimal.ZERO); // initialise to zero + techDataCalendarExcDay.set("exceptionCapacity", fixedAsset.getBigDecimal("productionCapacity")); // Debug.logInfo(" techData excday record not found creating for calendarId: " + techDataCalendarExcDay.getString("calendarId") + // " and date: " + exceptionDateStartTime.toString(), module); } // add the quantity to the quantity on the date record - Double newUsedCapacity = new Double(techDataCalendarExcDay.getDouble("usedCapacity").doubleValue() + - workEffort.getDouble("quantityToProduce").doubleValue()); + BigDecimal newUsedCapacity = techDataCalendarExcDay.getBigDecimal("usedCapacity").add(workEffort.getBigDecimal("quantityToProduce")); // check to see if the requested quantity is available on the requested day but only when the maximum capacity is set on the fixed asset if (fixedAsset.get("productionCapacity") != null) { // Debug.logInfo("see if maximum not reached, available: " + techDataCalendarExcDay.getString("exceptionCapacity") + // " already allocated: " + techDataCalendarExcDay.getString("usedCapacity") + // " Requested: " + workEffort.getString("quantityToProduce"), module); - if (newUsedCapacity.compareTo(techDataCalendarExcDay.getDouble("exceptionCapacity")) > 0) { + if (newUsedCapacity.compareTo(techDataCalendarExcDay.getBigDecimal("exceptionCapacity")) > 0) { String errMsg = "ERROR: fixed_Asset_sold_out AssetId: " + workEffort.get("fixedAssetId") + " on date: " + techDataCalendarExcDay.getString("exceptionDateStartTime"); Debug.logError(errMsg, module); errorMessages.add(errMsg); @@ -1144,9 +1143,9 @@ Iterator assocProductsIter = assocProducts.iterator(); while (assocProductsIter.hasNext()) { GenericValue productAssoc = (GenericValue) assocProductsIter.next(); - Double quantityOrd = productAssoc.getDouble("quantity"); - Double quantityKit = orderItemShipGroupAssoc.getDouble("quantity"); - Double quantity = new Double(quantityOrd.doubleValue() * quantityKit.doubleValue()); + BigDecimal quantityOrd = productAssoc.getBigDecimal("quantity"); + BigDecimal quantityKit = orderItemShipGroupAssoc.getBigDecimal("quantity"); + BigDecimal quantity = quantityOrd.multiply(quantityKit); Map reserveInput = new HashMap(); reserveInput.put("productStoreId", productStoreId); reserveInput.put("productId", productAssoc.getString("productIdTo")); @@ -1178,7 +1177,7 @@ reserveInput.put("shipGroupSeqId", orderItemShipGroupAssoc.getString("shipGroupSeqId")); reserveInput.put("facilityId", shipGroupFacilityId); // use the quantity from the orderItemShipGroupAssoc, NOT the orderItem, these are reserved by item-group assoc - reserveInput.put("quantity", orderItemShipGroupAssoc.getDouble("quantity")); + reserveInput.put("quantity", orderItemShipGroupAssoc.getBigDecimal("quantity")); reserveInput.put("userLogin", userLogin); Map reserveResult = dispatcher.runSync("reserveStoreInventory", reserveInput); @@ -1477,7 +1476,6 @@ } // prepare the service context - // pass in BigDecimal values instead of Double Map serviceContext = UtilMisc.toMap("productStoreId", orh.getProductStoreId(), "itemProductList", products, "itemAmountList", amounts, "itemShippingList", shipAmts, "itemPriceList", itPrices, "orderShippingAmount", orderShipping); serviceContext.put("shippingAddress", shippingAddress); @@ -1541,7 +1539,7 @@ createOrderAdjContext.put("orderItemSeqId", "_NA_"); createOrderAdjContext.put("shipGroupSeqId", "_NA_"); createOrderAdjContext.put("description", "Tax adjustment due to order change"); - createOrderAdjContext.put("amount", new Double(orderTaxDifference.doubleValue())); + createOrderAdjContext.put("amount", orderTaxDifference); createOrderAdjContext.put("userLogin", userLogin); Map createOrderAdjResponse = null; try { @@ -1607,7 +1605,7 @@ shippingTotal = ZERO; Debug.log("No valid order items found - " + shippingTotal, module); } else { - shippingTotal = UtilValidate.isEmpty(shippingEstMap.get("shippingTotal")) ? ZERO : new BigDecimal(((Double) shippingEstMap.get("shippingTotal")).doubleValue()); + shippingTotal = UtilValidate.isEmpty(shippingEstMap.get("shippingTotal")) ? ZERO : (BigDecimal)shippingEstMap.get("shippingTotal"); shippingTotal = shippingTotal.setScale(orderDecimals, orderRounding); Debug.log("Got new shipping estimate - " + shippingTotal, module); } @@ -1791,7 +1789,7 @@ Locale locale = (Locale) context.get("locale"); GenericValue userLogin = (GenericValue) context.get("userLogin"); - Double cancelQuantity = (Double) context.get("cancelQuantity"); + BigDecimal cancelQuantity = (BigDecimal) context.get("cancelQuantity"); String orderId = (String) context.get("orderId"); String orderItemSeqId = (String) context.get("orderItemSeqId"); String shipGroupSeqId = (String) context.get("shipGroupSeqId"); @@ -1840,33 +1838,33 @@ return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderErrorCannotCancelItemItemNotFound", UtilMisc.toMap("itemMsgInfo",itemMsgInfo), locale)); } - Double aisgaCancelQuantity = orderItemShipGroupAssoc.getDouble("cancelQuantity"); + BigDecimal aisgaCancelQuantity = orderItemShipGroupAssoc.getBigDecimal("cancelQuantity"); if (aisgaCancelQuantity == null) { - aisgaCancelQuantity = new Double(0.0); + aisgaCancelQuantity = BigDecimal.ZERO; } - Double availableQuantity = Double.valueOf(orderItemShipGroupAssoc.getDouble("quantity").doubleValue() - aisgaCancelQuantity.doubleValue()); + BigDecimal availableQuantity = orderItemShipGroupAssoc.getBigDecimal("quantity").subtract(aisgaCancelQuantity); - Double itemCancelQuantity = orderItem.getDouble("cancelQuantity"); + BigDecimal itemCancelQuantity = orderItem.getBigDecimal("cancelQuantity"); if (itemCancelQuantity == null) { - itemCancelQuantity = new Double(0.0); + itemCancelQuantity = BigDecimal.ZERO; } - Double itemQuantity = Double.valueOf(orderItem.getDouble("quantity").doubleValue() - itemCancelQuantity.doubleValue()); - if (availableQuantity == null) availableQuantity = new Double(0.0); - if (itemQuantity == null) itemQuantity = new Double(0.0); + BigDecimal itemQuantity = orderItem.getBigDecimal("quantity").subtract(itemCancelQuantity); + if (availableQuantity == null) availableQuantity = BigDecimal.ZERO; + if (itemQuantity == null) itemQuantity = BigDecimal.ZERO; - Double thisCancelQty = null; + BigDecimal thisCancelQty = null; if (cancelQuantity != null) { - thisCancelQty = new Double(cancelQuantity.doubleValue()); + thisCancelQty = cancelQuantity; } else { - thisCancelQty = new Double(availableQuantity.doubleValue()); + thisCancelQty = availableQuantity; } - if (availableQuantity.doubleValue() >= thisCancelQty.doubleValue()) { - if (availableQuantity.doubleValue() == 0) { + if (availableQuantity.compareTo(thisCancelQty) >= 0) { + if (availableQuantity.compareTo(BigDecimal.ZERO) == 0) { continue; //OrderItemShipGroupAssoc already cancelled } - orderItem.set("cancelQuantity", Double.valueOf(itemCancelQuantity.doubleValue() + thisCancelQty.doubleValue())); - orderItemShipGroupAssoc.set("cancelQuantity", Double.valueOf(aisgaCancelQuantity.doubleValue() + thisCancelQty.doubleValue())); + orderItem.set("cancelQuantity", itemCancelQuantity.add(thisCancelQty)); + orderItemShipGroupAssoc.set("cancelQuantity", aisgaCancelQuantity.add(thisCancelQty)); try { List toStore = UtilMisc.toList(orderItem, orderItemShipGroupAssoc); @@ -1907,7 +1905,7 @@ } } - if (thisCancelQty.doubleValue() >= itemQuantity.doubleValue()) { + if (thisCancelQty.compareTo(itemQuantity) >= 0) { // all items are cancelled -- mark the item as cancelled Map statusCtx = UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.getString("orderItemSeqId"), "statusId", "ITEM_CANCELLED", "userLogin", userLogin); try { @@ -3259,14 +3257,14 @@ String productId = (String) context.get("productId"); String prodCatalogId = (String) context.get("prodCatalogId"); BigDecimal basePrice = (BigDecimal) context.get("basePrice"); - Double quantity = (Double) context.get("quantity"); - Double amount = (Double) context.get("amount"); + BigDecimal quantity = (BigDecimal) context.get("quantity"); + BigDecimal amount = (BigDecimal) context.get("amount"); String overridePrice = (String) context.get("overridePrice"); String reasonEnumId = (String) context.get("reasonEnumId"); String changeComments = (String) context.get("changeComments"); if (amount == null) { - amount = new Double(0.00); + amount = BigDecimal.ZERO; } int shipGroupIdx = -1; @@ -3294,13 +3292,13 @@ // add in the new product try { - ShoppingCartItem item = ShoppingCartItem.makeItem(null, productId, null, quantity.doubleValue(), null, null, null, null, null, null, null, null, prodCatalogId, null, null, null, dispatcher, cart, null, null, null, Boolean.FALSE, Boolean.FALSE); + ShoppingCartItem item = ShoppingCartItem.makeItem(null, productId, null, quantity, null, null, null, null, null, null, null, null, prodCatalogId, null, null, null, dispatcher, cart, null, null, null, Boolean.FALSE, Boolean.FALSE); if (basePrice != null && overridePrice != null) { - item.setBasePrice(basePrice.doubleValue()); + item.setBasePrice(basePrice); // special hack to make sure we re-calc the promos after a price change - item.setQuantity(quantity.doubleValue() + 1, dispatcher, cart, false); - item.setQuantity(quantity.doubleValue(), dispatcher, cart, false); - item.setBasePrice(basePrice.doubleValue()); + item.setQuantity(quantity.add(BigDecimal.ONE), dispatcher, cart, false); + item.setQuantity(quantity, dispatcher, cart, false); + item.setBasePrice(basePrice); item.setIsModifiedPrice(true); } @@ -3369,24 +3367,24 @@ while (i.hasNext()) { String key = (String) i.next(); String quantityStr = (String) itemQtyMap.get(key); - double groupQty = 0.0; + BigDecimal groupQty = BigDecimal.ZERO; try { - groupQty = Double.parseDouble(quantityStr); + groupQty = new BigDecimal(quantityStr); } catch (NumberFormatException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } - if (groupQty == 0) { + if (groupQty.compareTo(BigDecimal.ZERO) == 0) { return ServiceUtil.returnError("Quantity must be >0, use cancel item to cancel completely!"); } String[] itemInfo = key.split(":"); - Double tally = (Double) itemTotals.get(itemInfo[0]); + BigDecimal tally = (BigDecimal) itemTotals.get(itemInfo[0]); if (tally == null) { - tally = new Double(groupQty); + tally = groupQty; } else { - tally = new Double(tally.doubleValue() + groupQty); + tally = tally.add(groupQty); } itemTotals.put(itemInfo[0], tally); } @@ -3398,12 +3396,12 @@ ShoppingCartItem cartItem = cart.findCartItem(itemSeqId); if (cartItem != null) { - Double qty = (Double) itemTotals.get(itemSeqId); - double priceSave = cartItem.getBasePrice(); + BigDecimal qty = (BigDecimal) itemTotals.get(itemSeqId); + BigDecimal priceSave = cartItem.getBasePrice(); // set quantity try { - cartItem.setQuantity(qty.doubleValue(), dispatcher, cart, false, false); // trigger external ops, don't reset ship groups (and update prices for both PO and SO items) + cartItem.setQuantity(qty, dispatcher, cart, false, false); // trigger external ops, don't reset ship groups (and update prices for both PO and SO items) } catch (CartItemModifyException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); @@ -3416,20 +3414,8 @@ if (overridePriceMap.containsKey(itemSeqId)) { String priceStr = (String) itemPriceMap.get(itemSeqId); if (UtilValidate.isNotEmpty(priceStr)) { - double price = -1; - //parse the price - NumberFormat nf = null; - if (locale != null) { - nf = NumberFormat.getNumberInstance(locale); - } else { - nf = NumberFormat.getNumberInstance(); - } - try { - price = nf.parse(priceStr).doubleValue(); - } catch (ParseException e) { - Debug.logError(e, module); - return ServiceUtil.returnError(e.getMessage()); - } + BigDecimal price = new BigDecimal("-1"); + price = new BigDecimal(priceStr).setScale(orderDecimals, orderRounding); cartItem.setBasePrice(price); cartItem.setIsModifiedPrice(true); Debug.log("Set item price: [" + itemSeqId + "] " + price, module); @@ -3457,9 +3443,9 @@ while (gai.hasNext()) { String key = (String) gai.next(); String quantityStr = (String) itemQtyMap.get(key); - double groupQty = 0.0; + BigDecimal groupQty = BigDecimal.ZERO; try { - groupQty = Double.parseDouble(quantityStr); + groupQty = new BigDecimal(quantityStr); } catch (NumberFormatException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); @@ -3686,11 +3672,11 @@ throw new GeneralException(ServiceUtil.getErrorMessage(result)); } - Double shippingTotal = (Double) result.get("shippingTotal"); + BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal"); if (shippingTotal == null) { - shippingTotal = new Double(0.00); + shippingTotal = BigDecimal.ZERO; } - cart.setItemShipGroupEstimate(shippingTotal.doubleValue(), gi); + cart.setItemShipGroupEstimate(shippingTotal, gi); } // calc the sales tax @@ -3764,8 +3750,8 @@ // Existing order item found. Check for modifications and store if any String oldItemDescription = oldOrderItem.getString("itemDescription") != null ? oldOrderItem.getString("itemDescription") : ""; - Double oldQuantity = oldOrderItem.getDouble("quantity") != null ? oldOrderItem.getDouble("quantity") : Double.valueOf(0.00); - Double oldUnitPrice = oldOrderItem.getDouble("unitPrice") != null ? oldOrderItem.getDouble("unitPrice") : Double.valueOf(0.00); + BigDecimal oldQuantity = oldOrderItem.getBigDecimal("quantity") != null ? oldOrderItem.getBigDecimal("quantity") : BigDecimal.ZERO; + BigDecimal oldUnitPrice = oldOrderItem.getBigDecimal("unitPrice") != null ? oldOrderItem.getBigDecimal("unitPrice") : BigDecimal.ZERO; boolean changeFound = false; Map modifiedItem = FastMap.newInstance(); @@ -3774,13 +3760,13 @@ changeFound = true; } - Double quantityDif = Double.valueOf(valueObj.getDouble("quantity").doubleValue() - oldQuantity.doubleValue()); - Double unitPriceDif = Double.valueOf(valueObj.getDouble("unitPrice").doubleValue() - oldUnitPrice.doubleValue()); - if (quantityDif.doubleValue() != 0) { + BigDecimal quantityDif = valueObj.getBigDecimal("quantity").subtract(oldQuantity); + BigDecimal unitPriceDif = valueObj.getBigDecimal("unitPrice").subtract(oldUnitPrice); + if (quantityDif.compareTo(BigDecimal.ZERO) != 0) { modifiedItem.put("quantity", quantityDif); changeFound = true; } - if (unitPriceDif.doubleValue() != 0) { + if (unitPriceDif.compareTo(BigDecimal.ZERO) != 0) { modifiedItem.put("unitPrice", unitPriceDif); changeFound = true; } @@ -3820,7 +3806,7 @@ appendedItem.put("orderId", valueObj.getString("orderId")); appendedItem.put("orderItemSeqId", valueObj.getString("orderItemSeqId")); - appendedItem.put("quantity", valueObj.getDouble("quantity")); + appendedItem.put("quantity", valueObj.getBigDecimal("quantity")); appendedItem.put("changeTypeEnumId", "ODR_ITM_APPEND"); modifiedItems.add(appendedItem); } @@ -3916,7 +3902,7 @@ try { Debug.log("Calling process payments...", module); //Debug.set(Debug.VERBOSE, true); - paymentResp = CheckOutHelper.processPayment(orderId, orh.getOrderGrandTotal().doubleValue(), orh.getCurrency(), productStore, userLogin, false, false, dispatcher, delegator); + paymentResp = CheckOutHelper.processPayment(orderId, orh.getOrderGrandTotal(), orh.getCurrency(), productStore, userLogin, false, false, dispatcher, delegator); //Debug.set(Debug.VERBOSE, false); } catch (GeneralException e) { Debug.logError(e, module); @@ -3938,8 +3924,8 @@ Locale locale = (Locale) context.get("locale"); ShoppingCart cart = new ShoppingCart(dctx.getDelegator(), "9000", "webStore", locale, "USD"); try { - cart.addOrIncreaseItem("GZ-1005", null, 1, null, null, null, null, null, null, null, "DemoCatalog", null, null, null, null, dctx.getDispatcher()); - } catch (CartItemModifyException e) { + cart.addOrIncreaseItem("GZ-1005", null, BigDecimal.ONE, null, null, null, null, null, null, null, "DemoCatalog", null, null, null, null, dctx.getDispatcher()); + } catch (CartItemModifyException e) { Debug.logError(e, module); } catch (ItemNotFoundException e) { Debug.logError(e, module); @@ -4007,12 +3993,12 @@ // create the payment Map paymentParams = new HashMap(); - double maxAmount = orderPaymentPreference.getDouble("maxAmount").doubleValue(); + BigDecimal maxAmount = orderPaymentPreference.getBigDecimal("maxAmount"); //if (maxAmount > 0.0) { paymentParams.put("paymentTypeId", "CUSTOMER_PAYMENT"); paymentParams.put("paymentMethodTypeId", orderPaymentPreference.getString("paymentMethodTypeId")); paymentParams.put("paymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId")); - paymentParams.put("amount", new Double(maxAmount)); + paymentParams.put("amount", maxAmount); paymentParams.put("statusId", "PMNT_RECEIVED"); paymentParams.put("effectiveDate", UtilDateTime.nowTimestamp()); paymentParams.put("partyIdFrom", billToParty.getString("partyId")); @@ -4315,7 +4301,7 @@ try { int itemIndex = cart.addOrIncreaseItem(item.getString("productId"), null, // amount - item.getDouble("quantity").doubleValue(), + item.getBigDecimal("quantity"), null, null, null, // reserv item.getTimestamp("shipBeforeDate"), item.getTimestamp("shipAfterDate"), @@ -4459,18 +4445,18 @@ if (! "PRODUCT_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) continue; // Get the cancelled quantity for the item - double orderItemCancelQuantity = 0; + BigDecimal orderItemCancelQuantity = BigDecimal.ZERO; if (! UtilValidate.isEmpty(orderItem.get("cancelQuantity")) ) { - orderItemCancelQuantity = orderItem.getDouble("cancelQuantity").doubleValue(); + orderItemCancelQuantity = orderItem.getBigDecimal("cancelQuantity"); } - if (orderItemCancelQuantity <= 0) continue; + if (orderItemCancelQuantity.compareTo(BigDecimal.ZERO) <= 0) continue; String productId = orderItem.getString("productId"); if (productRequirementQuantities.containsKey(productId)) { - orderItemCancelQuantity += ((Double) productRequirementQuantities.get(productId)).doubleValue(); + orderItemCancelQuantity = orderItemCancelQuantity.add((BigDecimal) productRequirementQuantities.get(productId)); } - productRequirementQuantities.put(productId, new Double(orderItemCancelQuantity)); + productRequirementQuantities.put(productId, orderItemCancelQuantity); } @@ -4478,7 +4464,7 @@ Iterator cqit = productRequirementQuantities.keySet().iterator(); while (cqit.hasNext()) { String productId = (String) cqit.next(); - Double requiredQuantity = (Double) productRequirementQuantities.get(productId); + BigDecimal requiredQuantity = (BigDecimal) productRequirementQuantities.get(productId); Map createRequirementResult = dispatcher.runSync("createRequirement", UtilMisc.<String, Object>toMap("requirementTypeId", "PRODUCT_REQUIREMENT", "facilityId", facilityId, "productId", productId, "quantity", requiredQuantity, "userLogin", userLogin)); if (ServiceUtil.isError(createRequirementResult)) return createRequirementResult; } @@ -4531,29 +4517,29 @@ if (! "PRODUCT_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) continue; // Get the ordered quantity for the item - double orderItemQuantity = 0; + BigDecimal orderItemQuantity = BigDecimal.ZERO; if (! UtilValidate.isEmpty(orderItem.get("quantity"))) { - orderItemQuantity = orderItem.getDouble("quantity").doubleValue(); + orderItemQuantity = orderItem.getBigDecimal("quantity"); } - double orderItemCancelQuantity = 0; + BigDecimal orderItemCancelQuantity = BigDecimal.ZERO; if (! UtilValidate.isEmpty(orderItem.get("cancelQuantity")) ) { - orderItemCancelQuantity = orderItem.getDouble("cancelQuantity").doubleValue(); + orderItemCancelQuantity = orderItem.getBigDecimal("cancelQuantity"); } // Get the received quantity for the order item - ignore the quantityRejected, since rejected items should be reordered List shipmentReceipts = orderItem.getRelated("ShipmentReceipt"); - double receivedQuantity = 0; + BigDecimal receivedQuantity = BigDecimal.ZERO; Iterator srit = shipmentReceipts.iterator(); while (srit.hasNext()) { GenericValue shipmentReceipt = (GenericValue) srit.next(); if (! UtilValidate.isEmpty(shipmentReceipt.get("quantityAccepted")) ) { - receivedQuantity += shipmentReceipt.getDouble("quantityAccepted").doubleValue(); + receivedQuantity = receivedQuantity.add(shipmentReceipt.getBigDecimal("quantityAccepted")); } } - double quantityToCancel = orderItemQuantity - orderItemCancelQuantity - receivedQuantity; - if (quantityToCancel > 0) { - Map cancelOrderItemResult = dispatcher.runSync("cancelOrderItem", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "cancelQuantity", new Double(quantityToCancel), "userLogin", userLogin)); + BigDecimal quantityToCancel = orderItemQuantity.subtract(orderItemCancelQuantity).subtract(receivedQuantity); + if (quantityToCancel.compareTo(BigDecimal.ZERO) > 0) { + Map cancelOrderItemResult = dispatcher.runSync("cancelOrderItem", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "cancelQuantity", quantityToCancel, "userLogin", userLogin)); if (ServiceUtil.isError(cancelOrderItemResult)) return cancelOrderItemResult; } @@ -4603,9 +4589,9 @@ Iterator i = itemMap.keySet().iterator(); while (i.hasNext()) { String item = (String) i.next(); - Double price = (Double) itemMap.get(item); + BigDecimal price = (BigDecimal) itemMap.get(item); try { - cart.addNonProductItem("BULK_ORDER_ITEM", item, null, price, 1, null, null, null, dispatcher); + cart.addNonProductItem("BULK_ORDER_ITEM", item, null, price, BigDecimal.ONE, null, null, null, dispatcher); } catch (CartItemModifyException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); Modified: ofbiz/trunk/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java?rev=731851&r1=731850&r2=731851&view=diff ============================================================================== --- ofbiz/trunk/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java (original) +++ ofbiz/trunk/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java Mon Jan 5 23:13:36 2009 @@ -19,6 +19,7 @@ package org.ofbiz.order.requirement; import java.util.*; +import java.math.BigDecimal; import java.sql.Timestamp; import javolution.util.FastList; @@ -87,8 +88,8 @@ Map productsSold = FastMap.newInstance(); // to count quantity, running total, and distinct products in list - double quantity = 0.0; - double amountTotal = 0.0; + BigDecimal quantity = BigDecimal.ZERO; + BigDecimal amountTotal = BigDecimal.ZERO; Set products = new HashSet(); // time period to count products ordered from, six months ago and the 1st of that month @@ -102,7 +103,7 @@ String productId = requirement.getString("productId"); partyId = requirement.getString("partyId"); String facilityId = requirement.getString("facilityId"); - double requiredQuantity = requirement.getDouble("quantity").doubleValue(); + BigDecimal requiredQuantity = requirement.getBigDecimal("quantity"); // get an available supplier product, preferably the one with the smallest minimum quantity to order, followed by price String supplierKey = partyId + "^" + productId; @@ -124,8 +125,8 @@ // add our supplier product and cost of this line to the data if (supplierProduct != null) { union.putAll(supplierProduct.getAllFields()); - double lastPrice = supplierProduct.getDouble("lastPrice").doubleValue(); - amountTotal += lastPrice * requiredQuantity; + BigDecimal lastPrice = supplierProduct.getBigDecimal("lastPrice"); + amountTotal = amountTotal.add(lastPrice.multiply(requiredQuantity)); } // for good identification, get the UPCA type (UPC code) @@ -154,7 +155,7 @@ } // how many of the products were sold (note this is for a fixed time period across all product stores) - Double sold = (Double) productsSold.get(productId); + BigDecimal sold = (BigDecimal) productsSold.get(productId); if (sold == null) { EntityCondition prodConditions = EntityCondition.makeCondition( UtilMisc.toList( EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), @@ -165,7 +166,7 @@ ), EntityOperator.AND); GenericValue count = EntityUtil.getFirst( delegator.findList("OrderItemQuantityReportGroupByProduct", prodConditions, UtilMisc.toSet("quantityOrdered"), null, null, false)); if (count != null) { - sold = count.getDouble("quantityOrdered"); + sold = count.getBigDecimal("quantityOrdered"); if (sold != null) productsSold.put(productId, sold); } } @@ -174,8 +175,8 @@ } // keep a running total of distinct products and quantity to order - if (requirement.getDouble("quantity") == null) requirement.put("quantity", new Double("1")); // default quantity = 1 - quantity += requiredQuantity; + if (requirement.getBigDecimal("quantity") == null) requirement.put("quantity", BigDecimal.ONE); // default quantity = 1 + quantity = quantity.add(requiredQuantity); products.add(productId); // add all the requirement fields last, to overwrite any conflicting fields @@ -186,8 +187,8 @@ Map results = ServiceUtil.returnSuccess(); results.put("requirementsForSupplier", requirements); results.put("distinctProductCount", new Integer(products.size())); - results.put("quantityTotal", new Double(quantity)); - results.put("amountTotal", new Double(amountTotal)); + results.put("quantityTotal", quantity); + results.put("amountTotal", amountTotal); return results; } catch (GenericServiceException e) { Debug.logError(e, module); @@ -216,10 +217,10 @@ if (product == null) continue; if (! "PRODRQM_AUTO".equals(product.get("requirementMethodEnumId"))) continue; - Double quantity = item.getDouble("quantity"); - Double cancelQuantity = item.getDouble("cancelQuantity"); - Double required = new Double( quantity.doubleValue() - (cancelQuantity == null ? 0.0 : cancelQuantity.doubleValue()) ); - if (required.doubleValue() <= 0.0) continue; + BigDecimal quantity = item.getBigDecimal("quantity"); + BigDecimal cancelQuantity = item.getBigDecimal("cancelQuantity"); + BigDecimal required = quantity.subtract(cancelQuantity == null ? BigDecimal.ZERO : cancelQuantity); + if (required.compareTo(BigDecimal.ZERO) <= 0) continue; Map input = UtilMisc.toMap("userLogin", userLogin, "facilityId", facilityId, "productId", product.get("productId"), "quantity", required, "requirementTypeId", "PRODUCT_REQUIREMENT"); Map results = dispatcher.runSync("createRequirement", input); @@ -270,23 +271,23 @@ if (product == null) continue; if (! "PRODRQM_ATP".equals(product.get("requirementMethodEnumId"))) continue; - Double quantity = item.getDouble("quantity"); - Double cancelQuantity = item.getDouble("cancelQuantity"); - double ordered = quantity.doubleValue() - (cancelQuantity == null ? 0.0 : cancelQuantity.doubleValue()); - if (ordered <= 0.0) continue; + BigDecimal quantity = item.getBigDecimal("quantity"); + BigDecimal cancelQuantity = item.getBigDecimal("cancelQuantity"); + BigDecimal ordered = quantity.subtract(cancelQuantity == null ? BigDecimal.ZERO : cancelQuantity); + if (ordered.compareTo(BigDecimal.ZERO) <= 0) continue; // get the minimum stock for this facility (don't do anything if not configured) GenericValue productFacility = delegator.findByPrimaryKey("ProductFacility", UtilMisc.toMap("facilityId", facilityId, "productId", product.get("productId"))); if (productFacility == null || productFacility.get("minimumStock") == null) continue; - double minimumStock = productFacility.getDouble("minimumStock").doubleValue(); + BigDecimal minimumStock = productFacility.getBigDecimal("minimumStock"); // get the facility ATP for product, which should be updated for this item's reservation Map results = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("userLogin", userLogin, "productId", product.get("productId"), "facilityId", facilityId)); if (ServiceUtil.isError(results)) return results; - double atp = ((Double) results.get("availableToPromiseTotal")).doubleValue(); // safe since this is a required OUT param + BigDecimal atp = ((BigDecimal) results.get("availableToPromiseTotal")); // safe since this is a required OUT param // count all current requirements for this product - double pendingRequirements = 0.0; + BigDecimal pendingRequirements = BigDecimal.ZERO; EntityConditionList<EntityExpr> ecl = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("productId", EntityOperator.EQUALS, product.get("productId")), @@ -297,20 +298,20 @@ List requirements = delegator.findList("Requirement", ecl, null, null, null, false); for (Iterator riter = requirements.iterator(); riter.hasNext(); ) { GenericValue requirement = (GenericValue) riter.next(); - pendingRequirements += (requirement.get("quantity") == null ? 0.0 : requirement.getDouble("quantity").doubleValue()); + pendingRequirements = pendingRequirements.add(requirement.get("quantity") == null ? BigDecimal.ZERO : requirement.getBigDecimal("quantity")); } // the minimum stock is an upper bound, therefore we either require up to the minimum stock or the input required quantity, whichever is less - double shortfall = minimumStock - atp - pendingRequirements; - double required = Math.min(ordered, shortfall); - if (required <= 0.0) continue; + BigDecimal shortfall = minimumStock.subtract(atp).subtract(pendingRequirements); + BigDecimal required = ordered.compareTo(shortfall) < 0 ? ordered : shortfall; + if (required.compareTo(BigDecimal.ZERO) <= 0) continue; - Map input = UtilMisc.toMap("userLogin", userLogin, "facilityId", facilityId, "productId", product.get("productId"), "quantity", new Double(required), "requirementTypeId", "PRODUCT_REQUIREMENT"); + Map input = UtilMisc.toMap("userLogin", userLogin, "facilityId", facilityId, "productId", product.get("productId"), "quantity", required, "requirementTypeId", "PRODUCT_REQUIREMENT"); results = dispatcher.runSync("createRequirement", input); if (ServiceUtil.isError(results)) return results; String requirementId = (String) results.get("requirementId"); - input = UtilMisc.toMap("userLogin", userLogin, "orderId", order.get("orderId"), "orderItemSeqId", item.get("orderItemSeqId"), "requirementId", requirementId, "quantity", new Double(required)); + input = UtilMisc.toMap("userLogin", userLogin, "orderId", order.get("orderId"), "orderItemSeqId", item.get("orderItemSeqId"), "requirementId", requirementId, "quantity", required); results = dispatcher.runSync("createOrderRequirementCommitment", input); if (ServiceUtil.isError(results)) return results; } Modified: ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java?rev=731851&r1=731850&r2=731851&view=diff ============================================================================== --- ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java (original) +++ ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java Mon Jan 5 23:13:36 2009 @@ -18,6 +18,7 @@ *******************************************************************************/ package org.ofbiz.order.shoppingcart; +import java.math.BigDecimal; import java.util.Iterator; import javax.servlet.http.HttpSession; @@ -85,17 +86,17 @@ cartAbandonedLine.set("cartAbandonedLineSeqId", (new Integer(seqId)).toString()); cartAbandonedLine.set("productId", cartItem.getProductId()); cartAbandonedLine.set("prodCatalogId", cartItem.getProdCatalogId()); - cartAbandonedLine.set("quantity", new Double(cartItem.getQuantity())); + cartAbandonedLine.set("quantity", cartItem.getQuantity()); cartAbandonedLine.set("reservStart", cartItem.getReservStart()); - cartAbandonedLine.set("reservLength", new Double(cartItem.getReservLength())); - cartAbandonedLine.set("reservPersons", new Double(cartItem.getReservPersons())); - cartAbandonedLine.set("unitPrice", new Double(cartItem.getBasePrice())); - cartAbandonedLine.set("reserv2ndPPPerc", new Double(cartItem.getReserv2ndPPPerc())); - cartAbandonedLine.set("reservNthPPPerc", new Double(cartItem.getReservNthPPPerc())); + cartAbandonedLine.set("reservLength", cartItem.getReservLength()); + cartAbandonedLine.set("reservPersons", cartItem.getReservPersons()); + cartAbandonedLine.set("unitPrice", cartItem.getBasePrice()); + cartAbandonedLine.set("reserv2ndPPPerc", cartItem.getReserv2ndPPPerc()); + cartAbandonedLine.set("reservNthPPPerc", cartItem.getReservNthPPPerc()); if (cartItem.getConfigWrapper() != null) { cartAbandonedLine.set("configId", cartItem.getConfigWrapper().getConfigId()); } - cartAbandonedLine.set("totalWithAdjustments", new Double(cartItem.getItemSubTotal())); + cartAbandonedLine.set("totalWithAdjustments", cartItem.getItemSubTotal()); //not doing pre-reservations now, so this is always N cartAbandonedLine.set("wasReserved", "N"); cartAbandonedLine.create(); Modified: ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutEvents.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutEvents.java?rev=731851&r1=731850&r2=731851&view=diff ============================================================================== --- ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutEvents.java (original) +++ ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutEvents.java Mon Jan 5 23:13:36 2009 @@ -18,6 +18,7 @@ *******************************************************************************/ package org.ofbiz.order.shoppingcart; +import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; @@ -168,7 +169,7 @@ String billingAccountId = request.getParameter("billingAccountId"); if (UtilValidate.isNotEmpty(billingAccountId)) { - Double billingAccountAmt = null; + BigDecimal billingAccountAmt = null; billingAccountAmt = determineBillingAccountAmount(billingAccountId, request.getParameter("billingAccountAmount"), dispatcher); if ((billingAccountId != null) && !"_NA_".equals(billingAccountId) && (billingAccountAmt == null)) { request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderInvalidAmountSetForBillingAccount", UtilMisc.toMap("billingAccountId",billingAccountId), (cart != null ? cart.getLocale() : Locale.getDefault()))); @@ -191,7 +192,7 @@ return "error"; } else { String gcPaymentMethodId = (String) gcResult.get("paymentMethodId"); - Double gcAmount = (Double) gcResult.get("amount"); + BigDecimal gcAmount = (BigDecimal) gcResult.get("amount"); if (gcPaymentMethodId != null) { selectedPaymentMethods.put(gcPaymentMethodId, UtilMisc.toMap("amount", gcAmount, "securityCode", null)); if ("Y".equalsIgnoreCase(request.getParameter("singleUseGiftCard"))) { @@ -299,11 +300,11 @@ paymentMethodInfo.put("securityCode", securityCode); } String amountStr = request.getParameter("amount_" + paymentMethods[i]); - Double amount = null; + BigDecimal amount = null; if (amountStr != null && amountStr.length() > 0 && !"REMAINING".equals(amountStr)) { try { - amount = new Double(formatter.parse(amountStr).doubleValue()); - } catch (ParseException e) { + amount = new BigDecimal(amountStr); + } catch (NumberFormatException e) { Debug.logError(e, module); errMsg = UtilProperties.getMessage(resource, "checkevents.invalid_amount_set_for_payment_method", (cart != null ? cart.getLocale() : Locale.getDefault())); request.setAttribute("_ERROR_MESSAGE_", errMsg); @@ -332,7 +333,7 @@ // get the billing account and amount String billingAccountId = request.getParameter("billingAccountId"); if (UtilValidate.isNotEmpty(billingAccountId)) { - Double billingAccountAmt = null; + BigDecimal billingAccountAmt = null; billingAccountAmt = determineBillingAccountAmount(billingAccountId, request.getParameter("billingAccountAmount"), dispatcher); if (billingAccountAmt == null) { request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderInvalidAmountSetForBillingAccount", UtilMisc.toMap("billingAccountId",billingAccountId), (cart != null ? cart.getLocale() : Locale.getDefault()))); @@ -389,7 +390,7 @@ } String gcPaymentMethodId = (String) gcResult.get("paymentMethodId"); - Double gcAmount = (Double) gcResult.get("amount"); + BigDecimal gcAmount = (BigDecimal) gcResult.get("amount"); if (gcPaymentMethodId != null) { selectedPaymentMethods.put(gcPaymentMethodId, UtilMisc.toMap("amount", gcAmount, "securityCode", null)); if ("Y".equalsIgnoreCase(request.getParameter("singleUseGiftCard"))) { @@ -823,7 +824,7 @@ // Set the billing account (if any) String billingAccountId = request.getParameter("billingAccountId"); if (UtilValidate.isNotEmpty(billingAccountId)) { - Double billingAccountAmt = null; + BigDecimal billingAccountAmt = null; billingAccountAmt = determineBillingAccountAmount(billingAccountId, request.getParameter("billingAccountAmount"), dispatcher); if (billingAccountAmt == null) { request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderInvalidAmountSetForBillingAccount", UtilMisc.toMap("billingAccountId",billingAccountId), (cart != null ? cart.getLocale() : Locale.getDefault()))); @@ -853,7 +854,7 @@ ServiceUtil.addErrors(errorMessages, errorMaps, callResult); if (errorMessages.size() == 0 && errorMaps.size() == 0) { String gcPaymentMethodId = (String) callResult.get("paymentMethodId"); - Double giftCardAmount = (Double) callResult.get("amount"); + BigDecimal giftCardAmount = (BigDecimal) callResult.get("amount"); // WARNING: if gcPaymentMethodId is not empty, all the previously set payment methods will be removed Map gcCallRes = checkOutHelper.finalizeOrderEntryPayment(gcPaymentMethodId, giftCardAmount, true, true); ServiceUtil.addErrors(errorMessages, errorMaps, gcCallRes); @@ -1029,8 +1030,8 @@ * * @return Amount to charge billing account or null if there was an error */ - private static Double determineBillingAccountAmount(String billingAccountId, String billingAccountAmount, LocalDispatcher dispatcher) { - Double billingAccountAmt = null; + private static BigDecimal determineBillingAccountAmount(String billingAccountId, String billingAccountAmount, LocalDispatcher dispatcher) { + BigDecimal billingAccountAmt = null; // set the billing account amount to the minimum of billing account available balance or amount input if less than balance if (UtilValidate.isNotEmpty(billingAccountId)) { @@ -1039,28 +1040,28 @@ String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00"); DecimalFormat formatter = new DecimalFormat(currencyFormat); try { - billingAccountAmt = new Double(formatter.parse(billingAccountAmount).doubleValue()); - } catch (ParseException e) { + billingAccountAmt = new BigDecimal(billingAccountAmount); + } catch (NumberFormatException e) { return null; } } if (billingAccountAmt == null) { - billingAccountAmt = new Double(0.0); + billingAccountAmt = BigDecimal.ZERO; } - double availableBalance = CheckOutHelper.availableAccountBalance(billingAccountId, dispatcher); + BigDecimal availableBalance = CheckOutHelper.availableAccountBalance(billingAccountId, dispatcher); // set amount to be charged to entered amount unless it exceeds the available balance - double chargeAmount = 0; - if (billingAccountAmt.doubleValue() < availableBalance) { - chargeAmount = billingAccountAmt.doubleValue(); + BigDecimal chargeAmount = BigDecimal.ZERO; + if (billingAccountAmt.compareTo(availableBalance) < 0) { + chargeAmount = billingAccountAmt; } else { chargeAmount = availableBalance; } - if (chargeAmount < 0.0) { - chargeAmount = 0.0; + if (chargeAmount.compareTo(BigDecimal.ZERO) < 0.0) { + chargeAmount = BigDecimal.ZERO; } - return new Double(chargeAmount); + return chargeAmount; } else { return null; } Modified: ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutHelper.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutHelper.java?rev=731851&r1=731850&r2=731851&view=diff ============================================================================== --- ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutHelper.java (original) +++ ofbiz/trunk/applications/order/src/org/ofbiz/order/shoppingcart/CheckOutHelper.java Mon Jan 5 23:13:36 2009 @@ -38,6 +38,7 @@ import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilFormatOut; import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilNumber; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericDelegator; @@ -70,6 +71,9 @@ public static final String resource = "OrderUiLabels"; public static final String resource_error = "OrderErrorUiLabels"; + public static final int scale = UtilNumber.getBigDecimalScale("order.decimals"); + public static final int rounding = UtilNumber.getBigDecimalRoundingMode("order.rounding"); + protected LocalDispatcher dispatcher = null; protected GenericDelegator delegator = null; protected ShoppingCart cart = null; @@ -252,9 +256,9 @@ if (UtilValidate.isNotEmpty(billingAccountId)) { Map billingAccountMap = (Map)selectedPaymentMethods.get("EXT_BILLACT"); - Double billingAccountAmt = (Double)billingAccountMap.get("amount"); + BigDecimal billingAccountAmt = (BigDecimal)billingAccountMap.get("amount"); // set cart billing account data and generate a payment method containing the amount we will be charging - cart.setBillingAccount(billingAccountId, (billingAccountAmt != null? billingAccountAmt.doubleValue(): 0.0)); + cart.setBillingAccount(billingAccountId, (billingAccountAmt != null ? billingAccountAmt: BigDecimal.ZERO)); // copy the billing account terms as order terms try { List billingAccountTerms = delegator.findByAnd("BillingAccountTerm", UtilMisc.toMap("billingAccountId", billingAccountId)); @@ -264,7 +268,7 @@ GenericValue billingAccountTerm = (GenericValue)billingAccountTermsIt.next(); // the term is not copied if in the cart a term of the same type is already set if (!cart.hasOrderTerm(billingAccountTerm.getString("termTypeId"))) { - cart.addOrderTerm(billingAccountTerm.getString("termTypeId"), billingAccountTerm.getDouble("termValue"), billingAccountTerm.getLong("termDays")); + cart.addOrderTerm(billingAccountTerm.getString("termTypeId"), billingAccountTerm.getBigDecimal("termValue"), billingAccountTerm.getLong("termDays")); } } } @@ -273,16 +277,16 @@ } } else { // remove the billing account from the cart - cart.setBillingAccount(null, 0.0); + cart.setBillingAccount(null, BigDecimal.ZERO); } // if checkoutPaymentId == EXT_BILLACT, then we have billing account only, so make sure we have enough credit if (selectedPaymentMethods.containsKey("EXT_BILLACT") && selectedPaymentMethods.size() == 1) { - double accountCredit = this.availableAccountBalance(cart.getBillingAccountId()); - double amountToUse = cart.getBillingAccountAmount(); + BigDecimal accountCredit = this.availableAccountBalance(cart.getBillingAccountId()); + BigDecimal amountToUse = cart.getBillingAccountAmount(); // if an amount was entered, check that it doesn't exceed availalble amount - if (amountToUse > 0 && amountToUse > accountCredit) { + if (amountToUse.compareTo(BigDecimal.ZERO) > 0 && amountToUse.compareTo(accountCredit) > 0) { errMsg = UtilProperties.getMessage(resource,"checkhelper.insufficient_credit_available_on_account", (cart != null ? cart.getLocale() : Locale.getDefault())); errorMessages.add(errMsg); @@ -292,9 +296,9 @@ } // check that the amount to use is enough to fulfill the order - double grandTotal = cart.getGrandTotal(); - if (grandTotal > amountToUse) { - cart.setBillingAccount(null, 0.0); // erase existing billing account data + BigDecimal grandTotal = cart.getGrandTotal(); + if (grandTotal.compareTo(amountToUse) > 0) { + cart.setBillingAccount(null, BigDecimal.ZERO); // erase existing billing account data errMsg = UtilProperties.getMessage(resource,"checkhelper.insufficient_credit_available_on_account", (cart != null ? cart.getLocale() : Locale.getDefault())); errorMessages.add(errMsg); @@ -305,9 +309,9 @@ // associate the cart billing account amount and EXT_BILLACT selected payment method with whatever amount we have now // XXX: Note that this step is critical for the billing account to be charged correctly - if (amountToUse > 0) { + if (amountToUse.compareTo(BigDecimal.ZERO) > 0) { cart.setBillingAccount(billingAccountId, amountToUse); - selectedPaymentMethods.put("EXT_BILLACT", UtilMisc.toMap("amount", new Double(amountToUse), "securityCode", null)); + selectedPaymentMethods.put("EXT_BILLACT", UtilMisc.toMap("amount", amountToUse, "securityCode", null)); } } @@ -328,11 +332,11 @@ } // get the selected amount to use - Double paymentAmount = null; + BigDecimal paymentAmount = null; String securityCode = null; if (selectedPaymentMethods.get(checkOutPaymentId) != null) { Map checkOutPaymentInfo = (Map) selectedPaymentMethods.get(checkOutPaymentId); - paymentAmount = (Double) checkOutPaymentInfo.get("amount"); + paymentAmount = (BigDecimal) checkOutPaymentInfo.get("amount"); securityCode = (String) checkOutPaymentInfo.get("securityCode"); } @@ -345,7 +349,7 @@ inf.securityCode = securityCode; } } - } else if (cart.getGrandTotal() != 0.00) { + } else if (cart.getGrandTotal().compareTo(BigDecimal.ZERO) != 0) { // only return an error if the order total is not 0.00 errMsg = UtilProperties.getMessage(resource,"checkhelper.select_method_of_payment", (cart != null ? cart.getLocale() : Locale.getDefault())); @@ -398,11 +402,11 @@ // Recalc shipping costs before setting payment Map shipEstimateMap = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0); - Double shippingTotal = (Double) shipEstimateMap.get("shippingTotal"); + BigDecimal shippingTotal = (BigDecimal) shipEstimateMap.get("shippingTotal"); if (shippingTotal == null) { - shippingTotal = new Double(0.00); + shippingTotal = BigDecimal.ZERO; } - cart.setItemShipGroupEstimate(shippingTotal.doubleValue(), 0); + cart.setItemShipGroupEstimate(shippingTotal, 0); //Recalc tax before setting payment try { @@ -439,7 +443,7 @@ String gcNum = (String) params.get("giftCardNumber"); String gcPin = (String) params.get("giftCardPin"); String gcAmt = (String) params.get("giftCardAmount"); - double gcAmount = -1; + BigDecimal gcAmount = BigDecimal.ONE.negate(); boolean gcFieldsOkay = true; if (gcNum == null || gcNum.length() == 0) { @@ -489,7 +493,7 @@ } if (gcAmt != null && gcAmt.length() > 0) { try { - gcAmount = Double.parseDouble(gcAmt); + gcAmount = new BigDecimal(gcAmt); } catch (NumberFormatException e) { Debug.logError(e, module); errMsg = UtilProperties.getMessage(resource,"checkhelper.invalid_amount_for_gift_card", (cart != null ? cart.getLocale() : Locale.getDefault())); @@ -519,9 +523,9 @@ if (errorMessages.size() == 0 && errorMaps.size() == 0) { // set the GC payment method - Double giftCardAmount = null; - if (gcAmount > 0) { - giftCardAmount = new Double(gcAmount); + BigDecimal giftCardAmount = null; + if (gcAmount.compareTo(BigDecimal.ZERO) > 0) { + giftCardAmount = gcAmount; } String gcPaymentMethodId = (String) gcResult.get("paymentMethodId"); result = ServiceUtil.returnSuccess(); @@ -563,19 +567,7 @@ String orderId = this.cart.getOrderId(); this.cart.clearAllItemStatus(); - // format the grandTotal - String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00"); - DecimalFormat formatter = new DecimalFormat(currencyFormat); - double cartTotal = this.cart.getGrandTotal(); - String grandTotalString = formatter.format(cartTotal); - Double grandTotal = null; - try { - grandTotal = new Double(formatter.parse(grandTotalString).doubleValue()); - } catch (ParseException e) { - Debug.logError(e, "Problem getting parsed currency amount from DecimalFormat", module); - String errMsg = UtilProperties.getMessage(resource,"checkhelper.could_not_create_order_parsing_totals", (cart != null ? cart.getLocale() : Locale.getDefault())); - return ServiceUtil.returnError(errMsg); - } + BigDecimal grandTotal = this.cart.getGrandTotal(); // store the order - build the context Map context = this.cart.makeCartMap(this.dispatcher, areOrderItemsExploded); @@ -646,7 +638,7 @@ inputMap.put("facilityId", productStore.getString("inventoryFacilityId")); inputMap.put("orderId", orderId); inputMap.put("orderItemSeqId", orderItem.getString("orderItemSeqId")); - inputMap.put("quantity", orderItem.getDouble("quantity")); + inputMap.put("quantity", orderItem.getBigDecimal("quantity")); inputMap.put("userLogin", permUserLogin); Map prunResult = dispatcher.runSync("createProductionRunFromConfiguration", inputMap); @@ -760,7 +752,6 @@ for (int i = 0; i < shipGroups; i++) { Map shoppingCartItemIndexMap = new HashMap(); Map serviceContext = this.makeTaxContext(i, shipAddress, shoppingCartItemIndexMap); - // pass in BigDecimal values instead of Double List taxReturn = this.getTaxAdjustments(dispatcher, "calcTax", serviceContext); if (Debug.verboseOn()) Debug.logVerbose("ReturnList: " + taxReturn, module); @@ -809,8 +800,8 @@ //Debug.logInfo("In makeTaxContext for item [" + i + "] in ship group [" + shipGroup + "] got itemInfo: " + itemInfo, module); product.add(i, cartItem.getProduct()); - amount.add(i, new BigDecimal(cartItem.getItemSubTotal(itemInfo.quantity))); - price.add(i, new BigDecimal(cartItem.getBasePrice())); + 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(i), cartItem); } @@ -819,7 +810,7 @@ List allAdjustments = cart.getAdjustments(); BigDecimal orderPromoAmt = OrderReadHelper.calcOrderPromoAdjustmentsBd(allAdjustments); - BigDecimal shipAmount = new BigDecimal(csi.shipEstimate); + BigDecimal shipAmount = csi.shipEstimate; if (shipAddress == null) { shipAddress = cart.getShippingAddress(shipGroup); // Debug.logInfo("====== makeTaxContext set shipAddress to cart.getShippingAddress(shipGroup): " + shipAddress, module); @@ -885,7 +876,7 @@ return CheckOutHelper.processPayment(this.cart.getOrderId(), this.cart.getGrandTotal(), this.cart.getCurrency(), productStore, userLogin, faceToFace, manualHold, dispatcher, delegator); } - public static Map processPayment(String orderId, double orderTotal, String currencyUomId, GenericValue productStore, GenericValue userLogin, boolean faceToFace, boolean manualHold, LocalDispatcher dispatcher, GenericDelegator delegator) throws GeneralException { + public static Map processPayment(String orderId, BigDecimal orderTotal, String currencyUomId, GenericValue productStore, GenericValue userLogin, boolean faceToFace, boolean manualHold, LocalDispatcher dispatcher, GenericDelegator delegator) throws GeneralException { // Get some payment related strings String DECLINE_MESSAGE = productStore.getString("authDeclinedMessage"); String ERROR_MESSAGE = productStore.getString("authErrorMessage"); @@ -917,7 +908,7 @@ if (opp.get("paymentMethodId") == null) { authCtx.put("serviceTypeEnum", "PRDS_PAY_EXTERNAL"); } - authCtx.put("processAmount", opp.getDouble("maxAmount")); + authCtx.put("processAmount", opp.getBigDecimal("maxAmount")); authCtx.put("authRefNum", opp.getString("manualRefNum")); authCtx.put("authResult", Boolean.TRUE); authCtx.put("userLogin", userLogin); @@ -939,7 +930,7 @@ } captCtx.put("payToPartyId", productStore.get("payToPartyId")); captCtx.put("captureResult", Boolean.TRUE); - captCtx.put("captureAmount", opp.getDouble("maxAmount")); + captCtx.put("captureAmount", opp.getBigDecimal("maxAmount")); captCtx.put("captureRefNum", opp.getString("manualRefNum")); captCtx.put("userLogin", userLogin); captCtx.put("currencyUomId", currencyUomId); @@ -960,7 +951,7 @@ // Invoke payment processing. if (UtilValidate.isNotEmpty(onlinePaymentPrefs)) { boolean autoApproveOrder = UtilValidate.isEmpty(productStore.get("autoApproveOrder")) || "Y".equalsIgnoreCase(productStore.getString("autoApproveOrder")); - if (orderTotal == 0 && autoApproveOrder) { + if (orderTotal.compareTo(BigDecimal.ZERO) == 0 && autoApproveOrder) { // if there is nothing to authorize; don't bother boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold); if (!ok) { @@ -1096,49 +1087,20 @@ return ServiceUtil.returnSuccess(); } - public static void adjustFaceToFacePayment(String orderId, double cartTotal, List allPaymentPrefs, GenericValue userLogin, GenericDelegator delegator) throws GeneralException { - String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00"); - DecimalFormat formatter = new DecimalFormat(currencyFormat); - - String grandTotalString = formatter.format(cartTotal); - Double grandTotal = null; - try { - grandTotal = new Double(formatter.parse(grandTotalString).doubleValue()); - } catch (ParseException e) { - throw new GeneralException("Problem getting parsed currency amount from DecimalFormat", e); - } - - double prefTotal = 0.00; + public static void adjustFaceToFacePayment(String orderId, BigDecimal cartTotal, List allPaymentPrefs, GenericValue userLogin, GenericDelegator delegator) throws GeneralException { + BigDecimal prefTotal = BigDecimal.ZERO; if (allPaymentPrefs != null) { Iterator i = allPaymentPrefs.iterator(); while (i.hasNext()) { GenericValue pref = (GenericValue) i.next(); - Double maxAmount = pref.getDouble("maxAmount"); - if (maxAmount == null) maxAmount = new Double(0.00); - prefTotal += maxAmount.doubleValue(); + BigDecimal maxAmount = pref.getBigDecimal("maxAmount"); + if (maxAmount == null) maxAmount = BigDecimal.ZERO; + prefTotal = prefTotal.add(maxAmount); } } - String payTotalString = formatter.format(prefTotal); - Double payTotal = null; - try { - payTotal = new Double(formatter.parse(payTotalString).doubleValue()); - } catch (ParseException e) { - throw new GeneralException("Problem getting parsed currency amount from DecimalFormat", e); - } - - if (grandTotal == null) grandTotal = new Double(0.00); - if (payTotal == null) payTotal = new Double(0.00); - - if (payTotal.doubleValue() > grandTotal.doubleValue()) { - double diff = (payTotal.doubleValue() - grandTotal.doubleValue()) * -1; - String diffString = formatter.format(diff); - Double change = null; - try { - change = new Double(formatter.parse(diffString).doubleValue()); - } catch (ParseException e) { - throw new GeneralException("Problem getting parsed currency amount from DecimalFormat", e); - } + if (prefTotal.compareTo(cartTotal) > 0) { + BigDecimal change = prefTotal.subtract(cartTotal).negate(); GenericValue newPref = delegator.makeValue("OrderPaymentPreference"); newPref.set("orderId", orderId); newPref.set("paymentMethodTypeId", "CASH"); @@ -1415,7 +1377,7 @@ * @return A Map conforming to the OFBiz Service conventions containing * any error messages. */ - public Map finalizeOrderEntryPayment(String checkOutPaymentId, Double amount, boolean singleUse, boolean append) { + public Map finalizeOrderEntryPayment(String checkOutPaymentId, BigDecimal amount, boolean singleUse, boolean append) { Map result = ServiceUtil.returnSuccess(); if (UtilValidate.isNotEmpty(checkOutPaymentId)) { @@ -1428,21 +1390,21 @@ return result; } - public static double availableAccountBalance(String billingAccountId, LocalDispatcher dispatcher) { - if (billingAccountId == null) return 0.0; + public static BigDecimal availableAccountBalance(String billingAccountId, LocalDispatcher dispatcher) { + if (billingAccountId == null) return BigDecimal.ZERO; try { Map res = dispatcher.runSync("calcBillingAccountBalance", UtilMisc.toMap("billingAccountId", billingAccountId)); - Double availableBalance = (Double) res.get("accountBalance"); + BigDecimal availableBalance = (BigDecimal) res.get("accountBalance"); if (availableBalance != null) { - return availableBalance.doubleValue(); + return availableBalance; } } catch (GenericServiceException e) { Debug.logError(e, module); } - return 0.0; + return BigDecimal.ZERO; } - public double availableAccountBalance(String billingAccountId) { + public BigDecimal availableAccountBalance(String billingAccountId) { return availableAccountBalance(billingAccountId, dispatcher); } @@ -1453,7 +1415,7 @@ while (i.hasNext()) { GenericValue pp = (GenericValue) i.next(); if (pp.get("billingAccountId") != null) { - accountMap.put(pp.getString("billingAccountId"), pp.getDouble("maxAmount")); + accountMap.put(pp.getString("billingAccountId"), pp.getBigDecimal("maxAmount")); } } } @@ -1463,9 +1425,9 @@ public Map validatePaymentMethods() { String errMsg = null; String billingAccountId = cart.getBillingAccountId(); - double billingAccountAmt = cart.getBillingAccountAmount(); - double availableAmount = this.availableAccountBalance(billingAccountId); - if (billingAccountAmt > availableAmount) { + BigDecimal billingAccountAmt = cart.getBillingAccountAmount(); + BigDecimal availableAmount = this.availableAccountBalance(billingAccountId); + if (billingAccountAmt.compareTo(availableAmount) > 0) { Map messageMap = UtilMisc.toMap("billingAccountId", billingAccountId); errMsg = UtilProperties.getMessage(resource, "checkevents.not_enough_available_on_account", messageMap, (cart != null ? cart.getLocale() : Locale.getDefault())); return ServiceUtil.returnError(errMsg); @@ -1475,7 +1437,7 @@ List paymentMethods = cart.getPaymentMethodIds(); List paymentTypes = cart.getPaymentMethodTypeIds(); if (paymentTypes.contains("EXT_BILLACT") && paymentTypes.size() == 1 && paymentMethods.size() == 0) { - if (cart.getGrandTotal() > availableAmount) { + if (cart.getGrandTotal().compareTo(availableAmount) > 0) { errMsg = UtilProperties.getMessage(resource, "checkevents.insufficient_credit_available_on_account", (cart != null ? cart.getLocale() : Locale.getDefault())); return ServiceUtil.returnError(errMsg); } @@ -1484,17 +1446,14 @@ // validate any gift card balances this.validateGiftCardAmounts(); - String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00"); - DecimalFormat formatter = new DecimalFormat(currencyFormat); - // update the selected payment methods amount with valid numbers if (paymentMethods != null) { List nullPaymentIds = new ArrayList(); Iterator i = paymentMethods.iterator(); while (i.hasNext()) { String paymentMethodId = (String) i.next(); - Double paymentAmount = cart.getPaymentAmount(paymentMethodId); - if (paymentAmount == null || paymentAmount.doubleValue() == 0) { + BigDecimal paymentAmount = cart.getPaymentAmount(paymentMethodId); + if (paymentAmount == null || paymentAmount.compareTo(BigDecimal.ZERO) == 0) { Debug.log("Found null paymentMethodId - " + paymentMethodId, module); nullPaymentIds.add(paymentMethodId); } @@ -1502,26 +1461,19 @@ Iterator npi = nullPaymentIds.iterator(); while (npi.hasNext()) { String paymentMethodId = (String) npi.next(); - double selectedPaymentTotal = cart.getPaymentTotal(); - double requiredAmount = cart.getGrandTotal(); - double nullAmount = requiredAmount - selectedPaymentTotal; + BigDecimal selectedPaymentTotal = cart.getPaymentTotal(); + BigDecimal requiredAmount = cart.getGrandTotal(); + BigDecimal newAmount = requiredAmount.subtract(selectedPaymentTotal); boolean setOverflow = false; ShoppingCart.CartPaymentInfo info = cart.getPaymentInfo(paymentMethodId); - String amountString = formatter.format(nullAmount); - double newAmount = 0; - try { - newAmount = formatter.parse(amountString).doubleValue(); - } catch (ParseException e) { - Debug.logError(e, "Problem getting parsed new amount; unable to update payment info!", module); - } Debug.log("Remaining total is - " + newAmount, module); - if (newAmount > 0) { - info.amount = new Double(newAmount); + if (newAmount.compareTo(BigDecimal.ZERO) > 0) { + info.amount = newAmount; Debug.log("Set null paymentMethodId - " + info.paymentMethodId + " / " + info.amount, module); } else { - info.amount = new Double(0); + info.amount = BigDecimal.ZERO; Debug.log("Set null paymentMethodId - " + info.paymentMethodId + " / " + info.amount, module); } if (!setOverflow) { @@ -1532,24 +1484,17 @@ } // verify the selected payment method amounts will cover the total - double reqAmtPreParse = cart.getGrandTotal() - cart.getBillingAccountAmount(); - double selectedPaymentTotal = cart.getPaymentTotal(); + BigDecimal reqAmtPreParse = cart.getGrandTotal().subtract(cart.getBillingAccountAmount()); + BigDecimal selectedPaymentTotal = cart.getPaymentTotal(); - String preParseString = formatter.format(reqAmtPreParse); - double requiredAmount = 0; - try { - requiredAmount = formatter.parse(preParseString).doubleValue(); - } catch (ParseException e) { - requiredAmount = reqAmtPreParse; - Debug.logError(e, "Problem getting parsed required amount; unable to update payment info!", module); - } - if (paymentMethods != null && paymentMethods.size() > 0 && requiredAmount > selectedPaymentTotal) { + BigDecimal requiredAmount = reqAmtPreParse.setScale(scale, rounding); + if (paymentMethods != null && paymentMethods.size() > 0 && requiredAmount.compareTo(selectedPaymentTotal) > 0) { Debug.logError("Required Amount : " + requiredAmount + " / Selected Amount : " + selectedPaymentTotal, module); errMsg = UtilProperties.getMessage(resource, "checkevents.payment_not_cover_this_order", (cart != null ? cart.getLocale() : Locale.getDefault())); return ServiceUtil.returnError(errMsg); } - if (paymentMethods != null && paymentMethods.size() > 0 && requiredAmount < selectedPaymentTotal) { - double changeAmount = selectedPaymentTotal - requiredAmount; + if (paymentMethods != null && paymentMethods.size() > 0 && requiredAmount.compareTo(selectedPaymentTotal) < 0) { + BigDecimal changeAmount = selectedPaymentTotal.subtract(requiredAmount); if (!paymentTypes.contains("CASH")){ Debug.logError("Change Amount : " + changeAmount + " / No cash.", module); errMsg = UtilProperties.getMessage(resource, "checkhelper.change_returned_cannot_be_greater_than_cash", (cart != null ? cart.getLocale() : Locale.getDefault())); @@ -1557,8 +1502,8 @@ }else{ int cashIndex = paymentTypes.indexOf("CASH"); String cashId = (String) paymentTypes.get(cashIndex); - double cashAmount = cart.getPaymentAmount(cashId); - if (cashAmount < changeAmount){ + BigDecimal cashAmount = cart.getPaymentAmount(cashId); + if (cashAmount.compareTo(changeAmount) < 0){ Debug.logError("Change Amount : " + changeAmount + " / Cash Amount : " + cashAmount, module); errMsg = UtilProperties.getMessage(resource, "checkhelper.change_returned_cannot_be_greater_than_cash", (cart != null ? cart.getLocale() : Locale.getDefault())); return ServiceUtil.returnError(errMsg); @@ -1585,7 +1530,7 @@ while (i.hasNext()) { GenericValue gc = (GenericValue) i.next(); Map gcBalanceMap = null; - double gcBalance = 0.00; + BigDecimal gcBalance = BigDecimal.ZERO; try { Map ctx = UtilMisc.toMap("userLogin", cart.getUserLogin()); ctx.put("currency", cart.getCurrency()); @@ -1606,18 +1551,18 @@ Debug.logError(e, module); } if (gcBalanceMap != null) { - Double bal = (Double) gcBalanceMap.get(balanceField); + BigDecimal bal = (BigDecimal) gcBalanceMap.get(balanceField); if (bal != null) { - gcBalance = bal.doubleValue(); + gcBalance = bal; } } // get the bill-up to amount - Double billUpTo = cart.getPaymentAmount(gc.getString("paymentMethodId")); + BigDecimal billUpTo = cart.getPaymentAmount(gc.getString("paymentMethodId")); // null bill-up to means use the full balance || update the bill-up to with the balance - if (billUpTo == null || billUpTo.doubleValue() == 0 || gcBalance < billUpTo.doubleValue()) { - cart.addPaymentAmount(gc.getString("paymentMethodId"), new Double(gcBalance)); + if (billUpTo == null || billUpTo.compareTo(BigDecimal.ZERO) == 0 || gcBalance.compareTo(billUpTo) < 0) { + cart.addPaymentAmount(gc.getString("paymentMethodId"), gcBalance); } } } |
Free forum by Nabble | Edit this page |