use of org.apache.ofbiz.order.shoppingcart.ShoppingCartItem in project ofbiz-framework by apache.
the class PayPalServices method addCartDetails.
private static void addCartDetails(NVPEncoder encoder, ShoppingCart cart) throws GenericEntityException {
encoder.add("CURRENCYCODE", cart.getCurrency());
int line = 0;
for (ShoppingCartItem item : cart.items()) {
encoder.add("L_NUMBER" + line, item.getProductId());
encoder.add("L_NAME" + line, item.getName());
encoder.add("L_AMT" + line, item.getBasePrice().setScale(2, RoundingMode.HALF_UP).toPlainString());
encoder.add("L_QTY" + line, item.getQuantity().toBigInteger().toString());
line++;
BigDecimal otherAdjustments = item.getOtherAdjustments();
if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
encoder.add("L_NUMBER" + line, item.getProductId());
encoder.add("L_NAME" + line, item.getName() + " Adjustments");
encoder.add("L_AMT" + line, otherAdjustments.setScale(2, RoundingMode.HALF_UP).toPlainString());
encoder.add("L_QTY" + line, "1");
line++;
}
}
BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
encoder.add("L_NUMBER" + line, "N/A");
encoder.add("L_NAME" + line, "Order Adjustments");
encoder.add("L_AMT" + line, otherAdjustments.setScale(2, RoundingMode.HALF_UP).toPlainString());
encoder.add("L_QTY" + line, "1");
line++;
}
encoder.add("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
encoder.add("SHIPPINGAMT", "0.00");
encoder.add("TAXAMT", "0.00");
encoder.add("AMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
// NOTE: The docs say this is optional but then won't work without it
encoder.add("MAXAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
}
use of org.apache.ofbiz.order.shoppingcart.ShoppingCartItem in project ofbiz-framework by apache.
the class PayflowPro method addCartDetails.
private static void addCartDetails(Map<String, String> parameterMap, ShoppingCart cart) throws GenericEntityException {
parameterMap.put("CURRENCY", cart.getCurrency());
int line = 0;
for (ShoppingCartItem item : cart.items()) {
// paramMap.put("L_NUMBER" + line, item.getProductId());
parameterMap.put("L_NAME" + line, item.getName());
parameterMap.put("L_DESC" + line, item.getDescription());
parameterMap.put("L_AMT" + line, item.getBasePrice().setScale(2).toPlainString());
parameterMap.put("L_QTY" + line, item.getQuantity().toBigInteger().toString());
line++;
BigDecimal otherAdjustments = item.getOtherAdjustments();
if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
parameterMap.put("L_NAME" + line, item.getName() + " Adjustments");
parameterMap.put("L_DESC" + line, "Adjustments for item: " + item.getName());
parameterMap.put("L_AMT" + line, otherAdjustments.setScale(2).toPlainString());
parameterMap.put("L_QTY" + line, "1");
line++;
}
}
BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
parameterMap.put("L_NAME" + line, "Order Adjustments");
parameterMap.put("L_AMT" + line, otherAdjustments.setScale(2).toPlainString());
parameterMap.put("L_QTY" + line, "1");
line++;
}
parameterMap.put("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
parameterMap.put("TAXAMT", cart.getTotalSalesTax().setScale(2).toPlainString());
parameterMap.put("FREIGHTAMT", cart.getTotalShipping().setScale(2).toPlainString());
parameterMap.put("AMT", cart.getGrandTotal().setScale(2).toPlainString());
if (!cart.shippingApplies()) {
parameterMap.put("NOSHIPPING", "1");
} else {
GenericValue shippingAddress = cart.getShippingAddress();
parameterMap.put("ADDROVERRIDE", "1");
parameterMap.put("SHIPTOSTREET", StringUtils.left(shippingAddress.getString("address1"), 30));
parameterMap.put("SHIPTOSTREET2", StringUtils.left(shippingAddress.getString("address2"), 30));
parameterMap.put("SHIPTOCITY", StringUtils.left(shippingAddress.getString("city"), 40));
if (shippingAddress.getString("stateProvinceGeoId") != null && !"_NA_".equals(shippingAddress.getString("stateProvinceGeoId"))) {
GenericValue stateProvinceGeo = shippingAddress.getRelatedOne("StateProvinceGeo", false);
parameterMap.put("SHIPTOSTATE", StringUtils.left(stateProvinceGeo.getString("geoCode"), 40));
}
parameterMap.put("SHIPTOZIP", StringUtils.left(shippingAddress.getString("postalCode"), 16));
GenericValue countryGeo = shippingAddress.getRelatedOne("CountryGeo", false);
parameterMap.put("SHIPTOCOUNTRY", StringUtils.left(countryGeo.getString("geoCode"), 2));
}
}
use of org.apache.ofbiz.order.shoppingcart.ShoppingCartItem in project ofbiz-framework by apache.
the class OrderServices method addItemToApprovedOrder.
public static Map<String, Object> addItemToApprovedOrder(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
String shipGroupSeqId = (String) context.get("shipGroupSeqId");
String orderId = (String) context.get("orderId");
String productId = (String) context.get("productId");
String prodCatalogId = (String) context.get("prodCatalogId");
BigDecimal basePrice = (BigDecimal) context.get("basePrice");
BigDecimal quantity = (BigDecimal) context.get("quantity");
Timestamp itemDesiredDeliveryDate = (Timestamp) context.get("itemDesiredDeliveryDate");
String overridePrice = (String) context.get("overridePrice");
String reasonEnumId = (String) context.get("reasonEnumId");
String orderItemTypeId = (String) context.get("orderItemTypeId");
String changeComments = (String) context.get("changeComments");
Boolean calcTax = (Boolean) context.get("calcTax");
Map<String, String> itemAttributesMap = UtilGenerics.checkMap(context.get("itemAttributesMap"));
if (calcTax == null) {
calcTax = Boolean.TRUE;
}
int shipGroupIdx = -1;
try {
shipGroupIdx = Integer.parseInt(shipGroupSeqId);
shipGroupIdx--;
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (shipGroupIdx < 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderShipGroupSeqIdInvalid", UtilMisc.toMap("shipGroupSeqId", shipGroupSeqId), locale));
}
if (quantity.compareTo(BigDecimal.ONE) < 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderItemQtyMustBePositive", locale));
}
// obtain a shopping cart object for updating
ShoppingCart cart = null;
try {
cart = loadCartForUpdate(dispatcher, delegator, userLogin, orderId);
} catch (GeneralException e) {
return ServiceUtil.returnError(e.getMessage());
}
try {
// if not and if quantity is in decimal format then return error.
if (!ProductWorker.isDecimalQuantityOrderAllowed(delegator, productId, cart.getProductStoreId())) {
BigDecimal remainder = quantity.remainder(BigDecimal.ONE);
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "cart.addToCart.quantityInDecimalNotAllowed", locale));
}
quantity = quantity.setScale(0, UtilNumber.getRoundingMode("order.rounding"));
} else {
quantity = quantity.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getRoundingMode("order.rounding"));
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
quantity = BigDecimal.ONE;
}
shipGroupIdx = cart.getShipInfoIndex(shipGroupSeqId);
// add in the new product
try {
ShoppingCartItem item = null;
if ("PURCHASE_ORDER".equals(cart.getOrderType())) {
GenericValue supplierProduct = cart.getSupplierProduct(productId, quantity, dispatcher);
if (supplierProduct != null) {
item = ShoppingCartItem.makePurchaseOrderItem(null, productId, null, quantity, null, null, prodCatalogId, null, orderItemTypeId, null, dispatcher, cart, supplierProduct, itemDesiredDeliveryDate, itemDesiredDeliveryDate, null);
cart.addItem(0, item);
} else {
throw new CartItemModifyException("No supplier information found for product [" + productId + "] and quantity quantity [" + quantity + "], cannot add to cart.");
}
if (basePrice != null) {
item.setBasePrice(basePrice);
item.setIsModifiedPrice(true);
}
item.setItemComment(changeComments);
item.setDesiredDeliveryDate(itemDesiredDeliveryDate);
cart.clearItemShipInfo(item);
cart.setItemShipGroupQty(item, item.getQuantity(), shipGroupIdx);
} else {
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);
// special hack to make sure we re-calc the promos after a price change
item.setQuantity(quantity.add(BigDecimal.ONE), dispatcher, cart, false);
item.setQuantity(quantity, dispatcher, cart, false);
item.setBasePrice(basePrice);
item.setIsModifiedPrice(true);
}
// set the item in the selected ship group
item.setDesiredDeliveryDate(itemDesiredDeliveryDate);
shipGroupIdx = cart.getShipInfoIndex(shipGroupSeqId);
int itemId = cart.getItemIndex(item);
cart.positionItemToGroup(itemId, quantity, cart.getItemShipGroupIndex(itemId), shipGroupIdx, false);
cart.clearItemShipInfo(item);
cart.setItemShipGroupQty(item, item.getQuantity(), shipGroupIdx);
}
// set the order item attributes
if (itemAttributesMap != null) {
// go through the item attributes map once to get a list of key names
Set<String> attributeNames = new HashSet<>();
Set<String> keys = itemAttributesMap.keySet();
for (String key : keys) {
attributeNames.add(key);
}
String attrValue = null;
for (String attrName : attributeNames) {
attrValue = itemAttributesMap.get(attrName);
if (UtilValidate.isNotEmpty(attrName)) {
item.setOrderItemAttribute(attrName, attrValue);
Debug.logInfo("Set item attribute Name: " + attrName + " , Value:" + attrValue, module);
}
}
}
} catch (CartItemModifyException | ItemNotFoundException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
Map<String, Object> changeMap = UtilMisc.<String, Object>toMap("itemReasonMap", UtilMisc.<String, Object>toMap("reasonEnumId", reasonEnumId), "itemCommentMap", UtilMisc.<String, Object>toMap("changeComments", changeComments));
// save all the updated information
try {
saveUpdatedCartToOrder(dispatcher, delegator, cart, locale, userLogin, orderId, changeMap, calcTax, false);
} catch (GeneralException e) {
return ServiceUtil.returnError(e.getMessage());
}
// log an order note
try {
String addedItemToOrder = UtilProperties.getMessage(resource, "OrderAddedItemToOrder", locale);
Map<String, Object> result = dispatcher.runSync("createOrderNote", UtilMisc.<String, Object>toMap("orderId", orderId, "note", addedItemToOrder + productId + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin));
if (ServiceUtil.isError(result)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
result.put("orderId", orderId);
return result;
}
use of org.apache.ofbiz.order.shoppingcart.ShoppingCartItem in project ofbiz-framework by apache.
the class OrderServices method updateApprovedOrderItems.
public static Map<String, Object> updateApprovedOrderItems(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
String orderId = (String) context.get("orderId");
Map<String, String> overridePriceMap = UtilGenerics.checkMap(context.get("overridePriceMap"));
Map<String, String> itemDescriptionMap = UtilGenerics.checkMap(context.get("itemDescriptionMap"));
Map<String, String> itemPriceMap = UtilGenerics.checkMap(context.get("itemPriceMap"));
Map<String, String> itemQtyMap = UtilGenerics.checkMap(context.get("itemQtyMap"));
Map<String, String> itemReasonMap = UtilGenerics.checkMap(context.get("itemReasonMap"));
Map<String, String> itemCommentMap = UtilGenerics.checkMap(context.get("itemCommentMap"));
Map<String, String> itemAttributesMap = UtilGenerics.checkMap(context.get("itemAttributesMap"));
Map<String, String> itemEstimatedShipDateMap = UtilGenerics.checkMap(context.get("itemShipDateMap"));
Map<String, String> itemEstimatedDeliveryDateMap = UtilGenerics.checkMap(context.get("itemDeliveryDateMap"));
Boolean calcTax = (Boolean) context.get("calcTax");
if (calcTax == null) {
calcTax = Boolean.TRUE;
}
// obtain a shopping cart object for updating
ShoppingCart cart = null;
try {
cart = loadCartForUpdate(dispatcher, delegator, userLogin, orderId);
} catch (GeneralException e) {
return ServiceUtil.returnError(e.getMessage());
}
// go through the item map and obtain the totals per item
Map<String, BigDecimal> itemTotals = new HashMap<>();
for (String key : itemQtyMap.keySet()) {
String quantityStr = itemQtyMap.get(key);
BigDecimal groupQty = BigDecimal.ZERO;
try {
groupQty = (BigDecimal) ObjectType.simpleTypeConvert(quantityStr, "BigDecimal", null, locale);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (groupQty.compareTo(BigDecimal.ZERO) < 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderItemQtyMustBePositive", locale));
}
String[] itemInfo = key.split(":");
BigDecimal tally = itemTotals.get(itemInfo[0]);
if (tally == null) {
tally = groupQty;
} else {
tally = tally.add(groupQty);
}
itemTotals.put(itemInfo[0], tally);
}
// set the items amount/price
for (String itemSeqId : itemTotals.keySet()) {
ShoppingCartItem cartItem = cart.findCartItem(itemSeqId);
if (cartItem != null) {
BigDecimal qty = itemTotals.get(itemSeqId);
BigDecimal priceSave = cartItem.getBasePrice();
try {
// if not and if quantity is in decimal format then return error.
if (!ProductWorker.isDecimalQuantityOrderAllowed(delegator, cartItem.getProductId(), cart.getProductStoreId())) {
BigDecimal remainder = qty.remainder(BigDecimal.ONE);
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "cart.addToCart.quantityInDecimalNotAllowed", locale));
}
qty = qty.setScale(0, UtilNumber.getRoundingMode("order.rounding"));
} else {
qty = qty.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getRoundingMode("order.rounding"));
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
qty = BigDecimal.ONE;
}
// set quantity
try {
// trigger external ops, don't reset ship groups (and update prices for both PO and SO items)
cartItem.setQuantity(qty, dispatcher, cart, false, false);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
Debug.logInfo("Set item quantity: [" + itemSeqId + "] " + qty, module);
if (cartItem.getIsModifiedPrice()) {
cartItem.setBasePrice(priceSave);
}
if (overridePriceMap.containsKey(itemSeqId)) {
String priceStr = itemPriceMap.get(itemSeqId);
if (UtilValidate.isNotEmpty(priceStr)) {
BigDecimal price = null;
try {
price = (BigDecimal) ObjectType.simpleTypeConvert(priceStr, "BigDecimal", null, locale);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
cartItem.setBasePrice(price);
cartItem.setIsModifiedPrice(true);
Debug.logInfo("Set item price: [" + itemSeqId + "] " + price, module);
}
}
// Update the item description
if (itemDescriptionMap != null && itemDescriptionMap.containsKey(itemSeqId)) {
String description = itemDescriptionMap.get(itemSeqId);
if (UtilValidate.isNotEmpty(description)) {
cartItem.setName(description);
Debug.logInfo("Set item description: [" + itemSeqId + "] " + description, module);
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderItemDescriptionCannotBeEmpty", locale));
}
}
// Update the item comment
if (itemCommentMap != null && itemCommentMap.containsKey(itemSeqId)) {
String comments = itemCommentMap.get(itemSeqId);
if (UtilValidate.isNotEmpty(comments)) {
cartItem.setItemComment(comments);
Debug.logInfo("Set item comment: [" + itemSeqId + "] " + comments, module);
}
}
// update the order item attributes
if (itemAttributesMap != null) {
// go through the item attributes map once to get a list of key names
Set<String> attributeNames = new HashSet<>();
Set<String> keys = itemAttributesMap.keySet();
for (String key : keys) {
String[] attributeInfo = key.split(":");
attributeNames.add(attributeInfo[0]);
}
String attrValue = null;
for (String attrName : attributeNames) {
attrValue = itemAttributesMap.get(attrName + ":" + itemSeqId);
if (UtilValidate.isNotEmpty(attrName)) {
cartItem.setOrderItemAttribute(attrName, attrValue);
Debug.logInfo("Set item attribute Name: [" + itemSeqId + "] " + attrName + " , Value:" + attrValue, module);
}
}
}
} else {
Debug.logInfo("Unable to locate shopping cart item for seqId #" + itemSeqId, module);
}
}
// Create Estimated Delivery dates
if (null != itemEstimatedDeliveryDateMap) {
for (Map.Entry<String, String> entry : itemEstimatedDeliveryDateMap.entrySet()) {
String itemSeqId = entry.getKey();
// ignore internationalised variant of dates
if (!itemSeqId.endsWith("_i18n")) {
String estimatedDeliveryDate = entry.getValue();
if (UtilValidate.isNotEmpty(estimatedDeliveryDate)) {
Timestamp deliveryDate = Timestamp.valueOf(estimatedDeliveryDate);
ShoppingCartItem cartItem = cart.findCartItem(itemSeqId);
cartItem.setDesiredDeliveryDate(deliveryDate);
}
}
}
}
// Create Estimated ship dates
if (null != itemEstimatedShipDateMap) {
for (Map.Entry<String, String> entry : itemEstimatedShipDateMap.entrySet()) {
String itemSeqId = entry.getKey();
// ignore internationalised variant of dates
if (!itemSeqId.endsWith("_i18n")) {
String estimatedShipDate = entry.getValue();
if (UtilValidate.isNotEmpty(estimatedShipDate)) {
Timestamp shipDate = Timestamp.valueOf(estimatedShipDate);
ShoppingCartItem cartItem = cart.findCartItem(itemSeqId);
cartItem.setEstimatedShipDate(shipDate);
}
}
}
}
// update the group amounts
for (String key : itemQtyMap.keySet()) {
String quantityStr = itemQtyMap.get(key);
BigDecimal groupQty = BigDecimal.ZERO;
try {
groupQty = (BigDecimal) ObjectType.simpleTypeConvert(quantityStr, "BigDecimal", null, locale);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
String[] itemInfo = key.split(":");
int groupIdx = -1;
try {
groupIdx = Integer.parseInt(itemInfo[1]);
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the group qty
ShoppingCartItem cartItem = cart.findCartItem(itemInfo[0]);
if (cartItem != null) {
try {
// if not and if quantity is in decimal format then return error.
if (!ProductWorker.isDecimalQuantityOrderAllowed(delegator, cartItem.getProductId(), cart.getProductStoreId())) {
BigDecimal remainder = groupQty.remainder(BigDecimal.ONE);
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "cart.addToCart.quantityInDecimalNotAllowed", locale));
}
groupQty = groupQty.setScale(0, UtilNumber.getRoundingMode("order.rounding"));
} else {
groupQty = groupQty.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getRoundingMode("order.rounding"));
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
groupQty = BigDecimal.ONE;
}
int shipGroupIndex = cart.getShipInfoIndex(itemInfo[1]);
if (Debug.infoOn()) {
Debug.logInfo("Shipping info (before) for group #" + (shipGroupIndex) + " [" + cart.getShipmentMethodTypeId(shipGroupIndex) + " / " + cart.getCarrierPartyId(shipGroupIndex) + "]", module);
}
cart.setItemShipGroupQty(cartItem, groupQty, shipGroupIndex);
if (Debug.infoOn()) {
Debug.logInfo("Set ship group qty: [" + itemInfo[0] + " / " + itemInfo[1] + " (" + (shipGroupIndex) + ")] " + groupQty, module);
Debug.logInfo("Shipping info (after) for group #" + (shipGroupIndex) + " [" + cart.getShipmentMethodTypeId(shipGroupIndex) + " / " + cart.getCarrierPartyId(shipGroupIndex) + "]", module);
}
}
}
// save all the updated information
try {
saveUpdatedCartToOrder(dispatcher, delegator, cart, locale, userLogin, orderId, UtilMisc.<String, Object>toMap("itemReasonMap", itemReasonMap, "itemCommentMap", itemCommentMap), calcTax, false);
} catch (GeneralException e) {
return ServiceUtil.returnError(e.getMessage());
}
// run promotions to handle all changes in the cart
ProductPromoWorker.doPromotions(cart, dispatcher);
// log an order note
try {
Map<String, Object> result = dispatcher.runSync("createOrderNote", UtilMisc.<String, Object>toMap("orderId", orderId, "note", "Updated order.", "internalNote", "Y", "userLogin", userLogin));
if (ServiceUtil.isError(result)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
result.put("orderId", orderId);
return result;
}
use of org.apache.ofbiz.order.shoppingcart.ShoppingCartItem in project ofbiz-framework by apache.
the class ProductDisplayWorker method getQuickReorderProducts.
public static Map<String, Object> getQuickReorderProducts(ServletRequest request) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
HttpServletRequest httpRequest = (HttpServletRequest) request;
GenericValue userLogin = (GenericValue) httpRequest.getSession().getAttribute("userLogin");
Map<String, Object> results = new HashMap<>();
if (userLogin == null) {
userLogin = (GenericValue) httpRequest.getSession().getAttribute("autoUserLogin");
}
if (userLogin == null) {
return results;
}
try {
Map<String, GenericValue> products = UtilGenerics.checkMap(httpRequest.getSession().getAttribute("_QUICK_REORDER_PRODUCTS_"));
Map<String, BigDecimal> productQuantities = UtilGenerics.checkMap(httpRequest.getSession().getAttribute("_QUICK_REORDER_PRODUCT_QUANTITIES_"));
Map<String, Integer> productOccurances = UtilGenerics.checkMap(httpRequest.getSession().getAttribute("_QUICK_REORDER_PRODUCT_OCCURANCES_"));
if (products == null || productQuantities == null || productOccurances == null) {
products = new HashMap<>();
productQuantities = new HashMap<>();
// keep track of how many times a product occurs in order to find averages and rank by purchase amount
productOccurances = new HashMap<>();
// get all order role entities for user by customer role type : PLACING_CUSTOMER
List<GenericValue> orderRoles = EntityQuery.use(delegator).from("OrderRole").where("partyId", userLogin.get("partyId"), "roleTypeId", "PLACING_CUSTOMER").queryList();
Iterator<GenericValue> ordersIter = UtilMisc.toIterator(orderRoles);
while (ordersIter != null && ordersIter.hasNext()) {
GenericValue orderRole = ordersIter.next();
// for each order role get all order items
List<GenericValue> orderItems = orderRole.getRelated("OrderItem", null, null, false);
Iterator<GenericValue> orderItemsIter = UtilMisc.toIterator(orderItems);
while (orderItemsIter != null && orderItemsIter.hasNext()) {
GenericValue orderItem = orderItemsIter.next();
String productId = orderItem.getString("productId");
if (UtilValidate.isNotEmpty(productId)) {
// for each order item get the associated product
GenericValue product = orderItem.getRelatedOne("Product", true);
products.put(product.getString("productId"), product);
BigDecimal curQuant = productQuantities.get(product.get("productId"));
if (curQuant == null) {
curQuant = BigDecimal.ZERO;
}
BigDecimal orderQuant = orderItem.getBigDecimal("quantity");
if (orderQuant == null) {
orderQuant = BigDecimal.ZERO;
}
productQuantities.put(product.getString("productId"), curQuant.add(orderQuant));
Integer curOcc = productOccurances.get(product.get("productId"));
if (curOcc == null) {
curOcc = Integer.valueOf(0);
}
productOccurances.put(product.getString("productId"), Integer.valueOf(curOcc.intValue() + 1));
}
}
}
// go through each product quantity and divide it by the occurances to get the average
for (Map.Entry<String, BigDecimal> entry : productQuantities.entrySet()) {
String prodId = entry.getKey();
BigDecimal quantity = entry.getValue();
Integer occs = productOccurances.get(prodId);
BigDecimal nqint = quantity.divide(new BigDecimal(occs), new MathContext(10));
if (nqint.compareTo(BigDecimal.ONE) < 0) {
nqint = BigDecimal.ONE;
}
productQuantities.put(prodId, nqint);
}
httpRequest.getSession().setAttribute("_QUICK_REORDER_PRODUCTS_", new HashMap<>(products));
httpRequest.getSession().setAttribute("_QUICK_REORDER_PRODUCT_QUANTITIES_", new HashMap<>(productQuantities));
httpRequest.getSession().setAttribute("_QUICK_REORDER_PRODUCT_OCCURANCES_", new HashMap<>(productOccurances));
} else {
// make a copy since we are going to change them
products = new HashMap<>(products);
productQuantities = new HashMap<>(productQuantities);
productOccurances = new HashMap<>(productOccurances);
}
// remove all products that are already in the cart
ShoppingCart cart = (ShoppingCart) httpRequest.getSession().getAttribute("shoppingCart");
if (UtilValidate.isNotEmpty(cart)) {
for (ShoppingCartItem item : cart) {
String productId = item.getProductId();
products.remove(productId);
productQuantities.remove(productId);
productOccurances.remove(productId);
}
}
// if desired check view allow category
String currentCatalogId = CatalogWorker.getCurrentCatalogId(request);
String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, currentCatalogId);
if (viewProductCategoryId != null) {
for (Map.Entry<String, GenericValue> entry : products.entrySet()) {
String productId = entry.getKey();
if (!CategoryWorker.isProductInCategory(delegator, productId, viewProductCategoryId)) {
products.remove(productId);
productQuantities.remove(productId);
productOccurances.remove(productId);
}
}
}
List<GenericValue> reorderProds = new LinkedList<>();
reorderProds.addAll(products.values());
// sort descending by new metric...
BigDecimal occurancesModifier = BigDecimal.ONE;
BigDecimal quantityModifier = BigDecimal.ONE;
Map<String, Object> newMetric = new HashMap<>();
for (Map.Entry<String, Integer> entry : productOccurances.entrySet()) {
String prodId = entry.getKey();
Integer quantity = entry.getValue();
BigDecimal occs = productQuantities.get(prodId);
// For quantity we should test if we allow to add decimal quantity for this product an productStore : if not then round to 0
if (!ProductWorker.isDecimalQuantityOrderAllowed(delegator, prodId, cart.getProductStoreId())) {
occs = occs.setScale(0, UtilNumber.getRoundingMode("order.rounding"));
} else {
occs = occs.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getRoundingMode("order.rounding"));
}
productQuantities.put(prodId, occs);
BigDecimal nqdbl = quantityModifier.multiply(new BigDecimal(quantity)).add(occs.multiply(occurancesModifier));
newMetric.put(prodId, nqdbl);
}
reorderProds = productOrderByMap(reorderProds, newMetric, true);
// remove extra products - only return 5
while (reorderProds.size() > 5) {
reorderProds.remove(reorderProds.size() - 1);
}
results.put("products", reorderProds);
results.put("quantities", productQuantities);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return results;
}
Aggregations