Search in sources :

Example 6 with CartItemModifyException

use of org.apache.ofbiz.order.shoppingcart.CartItemModifyException in project ofbiz-framework by apache.

the class ShoppingListEvents method addListToCart.

public static String addListToCart(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart, String prodCatalogId, String shoppingListId, boolean includeChild, boolean setAsListItem, boolean append) throws java.lang.IllegalArgumentException {
    String errMsg = null;
    // no list; no add
    if (shoppingListId == null) {
        errMsg = UtilProperties.getMessage(resource_error, "shoppinglistevents.choose_shopping_list", cart.getLocale());
        throw new IllegalArgumentException(errMsg);
    }
    // get the shopping list
    GenericValue shoppingList = null;
    List<GenericValue> shoppingListItems = null;
    try {
        shoppingList = EntityQuery.use(delegator).from("ShoppingList").where("shoppingListId", shoppingListId).queryOne();
        if (shoppingList == null) {
            errMsg = UtilProperties.getMessage(resource_error, "shoppinglistevents.error_getting_shopping_list_and_items", cart.getLocale());
            throw new IllegalArgumentException(errMsg);
        }
        shoppingListItems = shoppingList.getRelated("ShoppingListItem", null, null, false);
        if (shoppingListItems == null) {
            shoppingListItems = new LinkedList<>();
        }
        // include all items of child lists if flagged to do so
        if (includeChild) {
            List<GenericValue> childShoppingLists = shoppingList.getRelated("ChildShoppingList", null, null, false);
            for (GenericValue v : childShoppingLists) {
                List<GenericValue> items = v.getRelated("ShoppingListItem", null, null, false);
                shoppingListItems.addAll(items);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems getting ShoppingList and ShoppingListItem records", module);
        errMsg = UtilProperties.getMessage(resource_error, "shoppinglistevents.error_getting_shopping_list_and_items", cart.getLocale());
        throw new IllegalArgumentException(errMsg);
    }
    // no items; not an error; just mention that nothing was added
    if (UtilValidate.isEmpty(shoppingListItems)) {
        errMsg = UtilProperties.getMessage(resource_error, "shoppinglistevents.no_items_added", cart.getLocale());
        return errMsg;
    }
    // check if we are to clear the cart first
    if (!append) {
        cart.clear();
        // Prevent the system from creating a new shopping list every time the cart is restored for anonymous user.
        cart.setAutoSaveListId(shoppingListId);
    }
    // get the survey info for all the items
    Map<String, List<String>> shoppingListSurveyInfo = getItemSurveyInfos(shoppingListItems);
    // add the items
    StringBuilder eventMessage = new StringBuilder();
    for (GenericValue shoppingListItem : shoppingListItems) {
        String productId = shoppingListItem.getString("productId");
        BigDecimal quantity = shoppingListItem.getBigDecimal("quantity");
        Timestamp reservStart = shoppingListItem.getTimestamp("reservStart");
        BigDecimal reservLength = shoppingListItem.getBigDecimal("reservLength");
        BigDecimal reservPersons = shoppingListItem.getBigDecimal("reservPersons");
        String configId = shoppingListItem.getString("configId");
        try {
            String listId = shoppingListItem.getString("shoppingListId");
            String itemId = shoppingListItem.getString("shoppingListItemSeqId");
            Map<String, Object> attributes = new HashMap<>();
            // list items are noted in the shopping cart
            if (setAsListItem) {
                attributes.put("shoppingListId", listId);
                attributes.put("shoppingListItemSeqId", itemId);
            }
            // check if we have existing survey responses to append
            if (shoppingListSurveyInfo.containsKey(listId + "." + itemId) && UtilValidate.isNotEmpty(shoppingListSurveyInfo.get(listId + "." + itemId))) {
                attributes.put("surveyResponses", shoppingListSurveyInfo.get(listId + "." + itemId));
            }
            ProductConfigWrapper configWrapper = null;
            if (UtilValidate.isNotEmpty(configId)) {
                configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, configId, productId, cart.getProductStoreId(), prodCatalogId, cart.getWebSiteId(), cart.getCurrency(), cart.getLocale(), cart.getAutoUserLogin());
            }
            // i cannot get the addOrDecrease function to accept a null reservStart field: i get a null pointer exception a null constant works....
            if (reservStart == null) {
                cart.addOrIncreaseItem(productId, null, quantity, null, null, null, null, null, null, attributes, prodCatalogId, configWrapper, null, null, null, dispatcher);
            } else {
                cart.addOrIncreaseItem(productId, null, quantity, reservStart, reservLength, reservPersons, null, null, null, null, null, attributes, prodCatalogId, configWrapper, null, null, null, dispatcher);
            }
            Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId);
            errMsg = UtilProperties.getMessage(resource_error, "shoppinglistevents.added_product_to_cart", messageMap, cart.getLocale());
            eventMessage.append(errMsg).append("\n");
        } catch (CartItemModifyException e) {
            Debug.logWarning(e, UtilProperties.getMessage(resource_error, "OrderProblemsAddingItemFromListToCart", cart.getLocale()));
            Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId);
            errMsg = UtilProperties.getMessage(resource_error, "shoppinglistevents.problem_adding_product_to_cart", messageMap, cart.getLocale());
            eventMessage.append(errMsg).append("\n");
        } catch (ItemNotFoundException e) {
            Debug.logWarning(e, UtilProperties.getMessage(resource_error, "OrderProductNotFound", cart.getLocale()));
            Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId);
            errMsg = UtilProperties.getMessage(resource_error, "shoppinglistevents.problem_adding_product_to_cart", messageMap, cart.getLocale());
            eventMessage.append(errMsg).append("\n");
        }
    }
    if (eventMessage.length() > 0) {
        return eventMessage.toString();
    }
    // no message to return; will simply reply as success
    return "";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) ProductConfigWrapper(org.apache.ofbiz.product.config.ProductConfigWrapper) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) LinkedList(java.util.LinkedList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) ItemNotFoundException(org.apache.ofbiz.order.shoppingcart.ItemNotFoundException)

Example 7 with CartItemModifyException

use of org.apache.ofbiz.order.shoppingcart.CartItemModifyException in project ofbiz-framework by apache.

the class OrderTestServices method createTestSalesOrderSingle.

public static Map<String, Object> createTestSalesOrderSingle(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String productCategoryId = (String) context.get("productCategoryId");
    String productStoreId = (String) context.get("productStoreId");
    String currencyUomId = (String) context.get("currencyUomId");
    String partyId = (String) context.get("partyId");
    String productId = (String) context.get("productId");
    Integer numberOfProductsPerOrder = (Integer) context.get("numberOfProductsPerOrder");
    String salesChannel = (String) context.get("salesChannel");
    if (UtilValidate.isEmpty(salesChannel)) {
        salesChannel = "WEB_SALES_CHANNEL";
    }
    List<String> productsList = new LinkedList<String>();
    try {
        if (UtilValidate.isNotEmpty(productId)) {
            productsList.add(productId);
            numberOfProductsPerOrder = 1;
        } else {
            Map<String, Object> result = dispatcher.runSync("getProductCategoryMembers", UtilMisc.toMap("categoryId", productCategoryId));
            if (ServiceUtil.isError(result)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
            }
            if (result.get("categoryMembers") != null) {
                List<GenericValue> productCategoryMembers = UtilGenerics.checkList(result.get("categoryMembers"));
                if (productCategoryMembers != null) {
                    for (GenericValue prodCatMemb : productCategoryMembers) {
                        if (prodCatMemb != null) {
                            productsList.add(prodCatMemb.getString("productId"));
                        }
                    }
                }
            }
        }
    } catch (GenericServiceException gse) {
        return ServiceUtil.returnError(gse.getMessage());
    } catch (Exception e) {
        return ServiceUtil.returnError(e.getMessage());
    }
    if (productsList.size() == 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage("OrderUiLabels", "OrderCreateTestSalesOrderSingleError", UtilMisc.toMap("productCategoryId", productCategoryId), locale));
    }
    Random r = new Random();
    ShoppingCart cart = new ShoppingCart(delegator, productStoreId, locale, currencyUomId);
    cart.setOrderType("SALES_ORDER");
    cart.setChannelType(salesChannel);
    cart.setProductStoreId(productStoreId);
    cart.setBillToCustomerPartyId(partyId);
    cart.setPlacingCustomerPartyId(partyId);
    cart.setShipToCustomerPartyId(partyId);
    cart.setEndUserCustomerPartyId(partyId);
    try {
        cart.setUserLogin(userLogin, dispatcher);
    } catch (Exception exc) {
        Debug.logWarning("Error setting userLogin in the cart: " + exc.getMessage(), module);
    }
    int numberOfProductsPerOrderInt = numberOfProductsPerOrder.intValue();
    for (int j = 1; j <= numberOfProductsPerOrderInt; j++) {
        // get a product
        int k = r.nextInt(productsList.size());
        try {
            cart.addOrIncreaseItem(productsList.get(k), null, BigDecimal.ONE, null, null, null, null, null, null, null, null, /*catalogId*/
            null, null, /*itemType*/
            null, /*itemGroupNumber*/
            null, dispatcher);
        } catch (CartItemModifyException | ItemNotFoundException exc) {
            Debug.logWarning("Error adding product with id " + productsList.get(k) + " to the cart: " + exc.getMessage(), module);
        }
    }
    cart.setDefaultCheckoutOptions(dispatcher);
    CheckOutHelper checkout = new CheckOutHelper(dispatcher, delegator, cart);
    Map<String, Object> orderCreateResult = checkout.createOrder(userLogin);
    String orderId = (String) orderCreateResult.get("orderId");
    Map<String, Object> resultMap = ServiceUtil.returnSuccess();
    // approve the order
    if (UtilValidate.isNotEmpty(orderId)) {
        Debug.logInfo("Created test order with id: " + orderId, module);
        boolean approved = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        Debug.logInfo("Test order with id: " + orderId + " has been approved: " + approved, module);
        resultMap.put("orderId", orderId);
    }
    Boolean shipOrder = (Boolean) context.get("shipOrder");
    if (shipOrder.booleanValue() && UtilValidate.isNotEmpty(orderId)) {
        try {
            Map<String, Object> result = dispatcher.runSync("quickShipEntireOrder", UtilMisc.toMap("orderId", orderId, "userLogin", userLogin));
            if (ServiceUtil.isError(result)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
            }
            Debug.logInfo("Test sales order with id [" + orderId + "] has been shipped", module);
        } catch (GenericServiceException gse) {
            Debug.logWarning("Unable to quick ship test sales order with id [" + orderId + "] with error: " + gse.getMessage(), module);
        } catch (Exception exc) {
            Debug.logWarning("Unable to quick ship test sales order with id [" + orderId + "] with error: " + exc.getMessage(), module);
        }
    }
    return resultMap;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) LinkedList(java.util.LinkedList) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ItemNotFoundException(org.apache.ofbiz.order.shoppingcart.ItemNotFoundException) Delegator(org.apache.ofbiz.entity.Delegator) Random(java.util.Random) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ItemNotFoundException(org.apache.ofbiz.order.shoppingcart.ItemNotFoundException)

Example 8 with CartItemModifyException

use of org.apache.ofbiz.order.shoppingcart.CartItemModifyException 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;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashSet(java.util.HashSet) ItemNotFoundException(org.apache.ofbiz.order.shoppingcart.ItemNotFoundException)

Example 9 with CartItemModifyException

use of org.apache.ofbiz.order.shoppingcart.CartItemModifyException in project ofbiz-framework by apache.

the class OrderServices method createSimpleNonProductSalesOrder.

// create simple non-product order
public static Map<String, Object> createSimpleNonProductSalesOrder(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 paymentMethodId = (String) context.get("paymentMethodId");
    String productStoreId = (String) context.get("productStoreId");
    String currency = (String) context.get("currency");
    String partyId = (String) context.get("partyId");
    Map<String, BigDecimal> itemMap = UtilGenerics.checkMap(context.get("itemMap"));
    ShoppingCart cart = new ShoppingCart(delegator, productStoreId, null, locale, currency);
    try {
        cart.setUserLogin(userLogin, dispatcher);
    } catch (CartItemModifyException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    cart.setOrderType("SALES_ORDER");
    cart.setOrderPartyId(partyId);
    for (String item : itemMap.keySet()) {
        BigDecimal price = itemMap.get(item);
        try {
            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());
        }
    }
    // set the payment method
    try {
        cart.addPayment(paymentMethodId);
    } catch (IllegalArgumentException e) {
        return ServiceUtil.returnError(e.getMessage());
    }
    // save the order (new tx)
    Map<String, Object> createResp;
    try {
        createResp = dispatcher.runSync("createOrderFromShoppingCart", UtilMisc.toMap("shoppingCart", cart), 90, true);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(createResp)) {
        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResp));
    }
    // auth the order (new tx)
    Map<String, Object> authResp;
    try {
        authResp = dispatcher.runSync("callProcessOrderPayments", UtilMisc.toMap("shoppingCart", cart), 180, true);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(authResp)) {
        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(authResp));
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("orderId", createResp.get("orderId"));
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 10 with CartItemModifyException

use of org.apache.ofbiz.order.shoppingcart.CartItemModifyException 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;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Timestamp(java.sql.Timestamp) HashSet(java.util.HashSet) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

CartItemModifyException (org.apache.ofbiz.order.shoppingcart.CartItemModifyException)12 GenericValue (org.apache.ofbiz.entity.GenericValue)11 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)9 BigDecimal (java.math.BigDecimal)8 Locale (java.util.Locale)8 Delegator (org.apache.ofbiz.entity.Delegator)8 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)8 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)7 ShoppingCartItem (org.apache.ofbiz.order.shoppingcart.ShoppingCartItem)7 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)7 ItemNotFoundException (org.apache.ofbiz.order.shoppingcart.ItemNotFoundException)6 Timestamp (java.sql.Timestamp)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 GeneralException (org.apache.ofbiz.base.util.GeneralException)4 CheckOutHelper (org.apache.ofbiz.order.shoppingcart.CheckOutHelper)4 HashSet (java.util.HashSet)3 LinkedList (java.util.LinkedList)3 List (java.util.List)2 ProductConfigWrapper (org.apache.ofbiz.product.config.ProductConfigWrapper)2