Search in sources :

Example 16 with ShoppingCart

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

the class ExpressCheckoutEvents method determineCheckoutType.

public static CheckoutType determineCheckoutType(HttpServletRequest request) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
    return determineCheckoutType(delegator, cart.getProductStoreId());
}
Also used : Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart)

Example 17 with ShoppingCart

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

the class PayPalServices method payPalCheckoutUpdate.

public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;
    if (weakCart != null) {
        cart = weakCart.get();
    }
    if (cart == null) {
        Debug.logError("Could locate the ShoppingCart for token " + token, module);
        return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
        return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put("stateProvinceGeoId", parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));
    try {
        GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne();
        inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
        parentTransaction = TransactionUtil.suspend();
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, module);
    }
    try {
        Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
        contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnSuccess();
    }
    try {
        TransactionUtil.commit(beganTransaction);
        if (parentTransaction != null)
            TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");
    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
        BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
        // Check that we have a valid estimate (allowing zero value estimates for now)
        if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
            continue;
        }
        cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
        cart.setAllCarrierPartyId(shipMethod.getString("partyId"));
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            continue;
        }
        String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
        encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
        encoder.add("L_SHIPPINGOPTIONAMOUNT" + line, estimate.setScale(2, RoundingMode.HALF_UP).toPlainString());
        // Just make this first one default for now
        encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
        encoder.add("L_TAXAMT" + line, cart.getTotalSalesTax().setScale(2, RoundingMode.HALF_UP).toPlainString());
        line++;
    }
    String responseMsg = null;
    try {
        responseMsg = encoder.encode();
    } catch (PayPalException e) {
        Debug.logError(e, module);
    }
    if (responseMsg != null) {
        try {
            response.setContentLength(responseMsg.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            Debug.logError(e, module);
        }
        try (Writer writer = response.getWriter()) {
            writer.write(responseMsg);
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }
    // Remove the temporary ship address
    try {
        GenericValue postalAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", contactMechId).queryOne();
        postalAddress.remove();
        GenericValue contactMech = EntityQuery.use(delegator).from("ContactMech").where("contactMechId", contactMechId).queryOne();
        contactMech.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HttpServletResponse(javax.servlet.http.HttpServletResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) PayPalException(com.paypal.sdk.exceptions.PayPalException) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) Transaction(javax.transaction.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ShippingEstimateWrapper(org.apache.ofbiz.order.shoppingcart.shipping.ShippingEstimateWrapper) Writer(java.io.Writer)

Example 18 with ShoppingCart

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

the class PayflowPro method setExpressCheckout.

public static Map<String, Object> setExpressCheckout(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    ShoppingCart cart = (ShoppingCart) context.get("cart");
    Locale locale = cart.getLocale();
    GenericValue payPalPaymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, cart.getProductStoreId(), "EXT_PAYPAL", null, true);
    String paymentGatewayConfigId = payPalPaymentSetting.getString("paymentGatewayConfigId");
    String configString = "payment.properties";
    if (cart == null || cart.items().size() <= 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage("AccountingErrorUiLabels", "AccountingPayPalShoppingCartIsEmpty", locale));
    }
    Map<String, String> data = new HashMap<String, String>();
    data.put("TRXTYPE", "O");
    data.put("TENDER", "P");
    data.put("ACTION", "S");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
        data.put("TOKEN", token);
    }
    data.put("RETURNURL", getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "returnUrl", configString, "payment.verisign.returnUrl"));
    data.put("CANCELURL", getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "cancelReturnUrl", configString, "payment.verisign.cancelReturnUrl"));
    try {
        addCartDetails(data, cart);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayflowErrorRetreivingCartDetails", locale));
    }
    PayflowAPI pfp = init(delegator, paymentGatewayConfigId, null, context);
    // get the base params
    StringBuilder params = makeBaseParams(delegator, paymentGatewayConfigId, null);
    // parse the context parameters
    params.append("&").append(parseContext(data));
    // transmit the request
    if (Debug.verboseOn())
        Debug.logVerbose("Sending to Verisign: " + params.toString(), module);
    String resp;
    if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
        resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
    } else {
        resp = "RESULT=0&TOKEN=" + (new Date()).getTime() + "&RESPMSG=Testing";
    }
    if (Debug.verboseOn())
        Debug.logVerbose("Response from Verisign: " + resp, module);
    Map<String, String> responseMap = parseResponse(resp);
    String result = responseMap.get("RESULT");
    if (!"0".equals(result)) {
        String respMsg = responseMap.get("RESPMSG");
        Debug.logError("A problem occurred while requesting an express checkout token from paypal: Result = " + result + ", Message = " + respMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage("AccountingErrorUiLabels", "AccountingPayPalCommunicationError", locale));
    }
    token = responseMap.get("TOKEN");
    cart.setAttribute("payPalCheckoutToken", token);
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) PayflowAPI(paypal.payflow.PayflowAPI) Date(java.util.Date)

Example 19 with ShoppingCart

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

the class OrderServices method loadCartForUpdate.

/*
     *  Warning: loadCartForUpdate(...) and saveUpdatedCartToOrder(...) must always
     *           be used together in this sequence.
     *           In fact loadCartForUpdate(...) will remove or cancel data associated to the order,
     *           before returning the ShoppingCart object; for this reason, the cart
     *           must be stored back using the method saveUpdatedCartToOrder(...),
     *           because that method will recreate the data.
     */
private static ShoppingCart loadCartForUpdate(LocalDispatcher dispatcher, Delegator delegator, GenericValue userLogin, String orderId) throws GeneralException {
    // load the order into a shopping cart
    Map<String, Object> loadCartResp = null;
    try {
        loadCartResp = dispatcher.runSync("loadCartFromOrder", UtilMisc.<String, Object>toMap("orderId", orderId, // the items are already reserved, no need to check again
        "skipInventoryChecks", // the items are already reserved, no need to check again
        Boolean.TRUE, // the products are already in the order, no need to check their validity now
        "skipProductChecks", // the products are already in the order, no need to check their validity now
        Boolean.TRUE, "userLogin", userLogin));
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    if (ServiceUtil.isError(loadCartResp)) {
        throw new GeneralException(ServiceUtil.getErrorMessage(loadCartResp));
    }
    ShoppingCart cart = (ShoppingCart) loadCartResp.get("shoppingCart");
    if (cart == null) {
        throw new GeneralException("Error loading shopping cart from order [" + orderId + "]");
    }
    cart.setOrderId(orderId);
    // Now that the cart is loaded, all the data that will be re-created
    // when the method saveUpdatedCartToOrder(...) will be called, are
    // removed and cancelled:
    // - inventory reservations are cancelled
    // - promotional items are cancelled
    // - order payments are released (cancelled)
    // - offline non received payments are cancelled
    // - promotional, shipping and tax adjustments are removed
    // Inventory reservations
    // find ship group associations
    List<GenericValue> shipGroupAssocs = null;
    try {
        shipGroupAssocs = EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("orderId", orderId).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    // cancel existing inventory reservations
    if (shipGroupAssocs != null) {
        for (GenericValue shipGroupAssoc : shipGroupAssocs) {
            String orderItemSeqId = shipGroupAssoc.getString("orderItemSeqId");
            String shipGroupSeqId = shipGroupAssoc.getString("shipGroupSeqId");
            Map<String, Object> cancelCtx = UtilMisc.<String, Object>toMap("userLogin", userLogin, "orderId", orderId);
            cancelCtx.put("orderItemSeqId", orderItemSeqId);
            cancelCtx.put("shipGroupSeqId", shipGroupSeqId);
            Map<String, Object> cancelResp = null;
            try {
                cancelResp = dispatcher.runSync("cancelOrderInventoryReservation", cancelCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                throw new GeneralException(e.getMessage());
            }
            if (ServiceUtil.isError(cancelResp)) {
                throw new GeneralException(ServiceUtil.getErrorMessage(cancelResp));
            }
        }
    }
    // cancel promo items -- if the promo still qualifies it will be added by the cart
    List<GenericValue> promoItems = null;
    try {
        promoItems = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "isPromo", "Y").queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    if (promoItems != null) {
        for (GenericValue promoItem : promoItems) {
            // Skip if the promo is already cancelled
            if ("ITEM_CANCELLED".equals(promoItem.get("statusId"))) {
                continue;
            }
            Map<String, Object> cancelPromoCtx = UtilMisc.<String, Object>toMap("orderId", orderId);
            cancelPromoCtx.put("orderItemSeqId", promoItem.getString("orderItemSeqId"));
            cancelPromoCtx.put("userLogin", userLogin);
            Map<String, Object> cancelResp = null;
            try {
                cancelResp = dispatcher.runSync("cancelOrderItemNoActions", cancelPromoCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                throw new GeneralException(e.getMessage());
            }
            if (ServiceUtil.isError(cancelResp)) {
                throw new GeneralException(ServiceUtil.getErrorMessage(cancelResp));
            }
        }
    }
    // cancel exiting authorizations
    Map<String, Object> releaseResp = null;
    try {
        releaseResp = dispatcher.runSync("releaseOrderPayments", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    if (ServiceUtil.isError(releaseResp)) {
        throw new GeneralException(ServiceUtil.getErrorMessage(releaseResp));
    }
    // cancel other (non-completed and non-cancelled) payments
    List<GenericValue> paymentPrefsToCancel = null;
    try {
        List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
        exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_RECEIVED"));
        exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
        exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_DECLINED"));
        exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_SETTLED"));
        exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_REFUNDED"));
        paymentPrefsToCancel = EntityQuery.use(delegator).from("OrderPaymentPreference").where(exprs).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    if (paymentPrefsToCancel != null) {
        for (GenericValue opp : paymentPrefsToCancel) {
            try {
                opp.set("statusId", "PAYMENT_CANCELLED");
                opp.store();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
                throw new GeneralException(e.getMessage());
            }
        }
    }
    // remove the adjustments
    try {
        List<EntityCondition> adjExprs = new LinkedList<>();
        adjExprs.add(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
        List<EntityCondition> exprs = new LinkedList<>();
        exprs.add(EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "PROMOTION_ADJUSTMENT"));
        exprs.add(EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "SHIPPING_CHARGES"));
        exprs.add(EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "SALES_TAX"));
        exprs.add(EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "VAT_TAX"));
        exprs.add(EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "VAT_PRICE_CORRECT"));
        adjExprs.add(EntityCondition.makeCondition(exprs, EntityOperator.OR));
        EntityCondition cond = EntityCondition.makeCondition(adjExprs, EntityOperator.AND);
        List<GenericValue> orderAdjustmentsToDelete = EntityQuery.use(delegator).from("OrderAdjustment").where(cond).queryList();
        List<GenericValue> orderAdjustmentsToStore = new LinkedList<>();
        List<GenericValue> orderAdjustmentsToRemove = new LinkedList<>();
        if (UtilValidate.isNotEmpty(orderAdjustmentsToDelete)) {
            for (GenericValue orderAdjustment : orderAdjustmentsToDelete) {
                // check if the adjustment has a related entry in entity OrderAdjustmentBilling
                List<GenericValue> oaBilling = orderAdjustment.getRelated("OrderAdjustmentBilling", null, null, false);
                if (UtilValidate.isNotEmpty(oaBilling)) {
                    orderAdjustmentsToRemove.add(orderAdjustment);
                    if ("SALES_TAX".equals(orderAdjustment.get("orderAdjustmentTypeId"))) {
                        // if the orderAdjustment is  a sale tax, set the amount to 0 to avoid amount addition
                        orderAdjustmentsToStore.add(orderAdjustment);
                    }
                }
            }
        }
        // then remove order Adjustment of the list
        if (UtilValidate.isNotEmpty(orderAdjustmentsToDelete)) {
            orderAdjustmentsToDelete.removeAll(orderAdjustmentsToRemove);
            delegator.removeAll(orderAdjustmentsToDelete);
        }
        if (UtilValidate.isNotEmpty(orderAdjustmentsToStore)) {
            for (GenericValue orderAdjustment : orderAdjustmentsToStore) {
                orderAdjustment.set("amount", BigDecimal.ZERO);
            }
            delegator.storeAll(orderAdjustmentsToStore);
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    return cart;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 20 with ShoppingCart

use of org.apache.ofbiz.order.shoppingcart.ShoppingCart 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)

Aggregations

ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)37 Delegator (org.apache.ofbiz.entity.Delegator)28 GenericValue (org.apache.ofbiz.entity.GenericValue)28 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)23 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)18 Locale (java.util.Locale)17 GeneralException (org.apache.ofbiz.base.util.GeneralException)14 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)13 BigDecimal (java.math.BigDecimal)9 CartItemModifyException (org.apache.ofbiz.order.shoppingcart.CartItemModifyException)9 HashMap (java.util.HashMap)8 CheckOutHelper (org.apache.ofbiz.order.shoppingcart.CheckOutHelper)8 ShoppingCartItem (org.apache.ofbiz.order.shoppingcart.ShoppingCartItem)7 Timestamp (java.sql.Timestamp)6 LinkedList (java.util.LinkedList)5 ItemNotFoundException (org.apache.ofbiz.order.shoppingcart.ItemNotFoundException)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)4 NVPEncoder (com.paypal.sdk.core.nvp.NVPEncoder)3 PayPalException (com.paypal.sdk.exceptions.PayPalException)3