Search in sources :

Example 1 with CartShipInfo

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

the class PayPalServices method getExpressCheckout.

public static Map<String, Object> getExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
        encoder.add("TOKEN", token);
    } else {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale));
    }
    NVPDecoder decoder;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
        cart.addOrderNote(decoder.get("NOTE"));
    }
    if (cart.getUserLogin() == null) {
        try {
            GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "anonymous").queryOne();
            try {
                cart.setUserLogin(userLogin, dispatcher);
            } catch (CartItemModifyException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
        // Check nothing has been set on the anon userLogin either
        partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
        cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
        GenericValue party = null;
        try {
            party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (party == null) {
            partyId = null;
        }
    }
    Map<String, Object> inMap = new HashMap<String, Object>();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
        newParty = true;
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("personalTitle", decoder.get("SALUTATION"));
        inMap.put("firstName", decoder.get("FIRSTNAME"));
        inMap.put("middleName", decoder.get("MIDDLENAME"));
        inMap.put("lastName", decoder.get("LASTNAME"));
        inMap.put("suffix", decoder.get("SUFFIX"));
        try {
            outMap = dispatcher.runSync("createPerson", inMap);
            partyId = (String) outMap.get("partyId");
            cart.setOrderPartyId(partyId);
            cart.getUserLogin().setString("partyId", partyId);
            inMap.clear();
            inMap.put("userLogin", cart.getUserLogin());
            inMap.put("partyId", partyId);
            inMap.put("roleTypeId", "CUSTOMER");
            dispatcher.runSync("createPartyRole", inMap);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")), EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityComparisonOperator.EQUALS, EntityFunction.UPPER(emailAddress))));
        try {
            GenericValue matchingEmail = EntityQuery.use(delegator).from("PartyAndContactMech").where(cond).orderBy("fromDate").filterByDate().queryFirst();
            if (matchingEmail != null) {
                emailContactMechId = matchingEmail.getString("contactMechId");
            } else {
                // No email found so we'll need to create one but first check if it should be PRIMARY or just BILLING
                long primaryEmails = EntityQuery.use(delegator).from("PartyContactWithPurpose").where("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS", "contactMechPurposeTypeId", "PRIMARY_EMAIL").filterByDate("contactFromDate", "contactThruDate", "purposeFromDate", "purposeThruDate").queryCount();
                if (primaryEmails > 0)
                    emailContactPurposeTypeId = "BILLING_EMAIL";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (emailContactMechId == null) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
        inMap.put("emailAddress", emailAddress);
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        // Going to assume PayPal has taken care of this for us
        inMap.put("verified", "Y");
        inMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
            emailContactMechId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);
    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
        inMap.clear();
        if (phoneNumber.startsWith("+")) {
            // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
            String[] phoneNumbers = phoneNumber.split(" ");
            inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
            inMap.put("contactNumber", phoneNumbers[1]);
        } else {
            // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
            inMap.put("countryCode", "1");
            String[] phoneNumbers = phoneNumber.split("-");
            inMap.put("areaCode", phoneNumbers[0]);
            inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
        }
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        try {
            outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
            phoneContactId = (String) outMap.get("contactMechId");
            cart.addContactMech("PHONE_BILLING", phoneContactId);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
        }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = new HashMap<String, Object>();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"), delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put("stateProvinceGeoId", parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
        // We want an exact match only
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(postalMap), EntityCondition.makeCondition(UtilMisc.toMap("attnName", null, "directions", null, "postalCodeExt", null, "postalCodeGeoId", null)), EntityCondition.makeCondition("partyId", partyId)));
        try {
            GenericValue postalMatch = EntityQuery.use(delegator).from("PartyAndPostalAddress").where(cond).orderBy("fromDate").filterByDate().queryFirst();
            if (postalMatch != null) {
                postalContactId = postalMatch.getString("contactMechId");
                List<GenericValue> postalPurposes = EntityQuery.use(delegator).from("PartyContactMechPurpose").where("partyId", partyId, "contactMechId", postalContactId).filterByDate().queryList();
                List<Object> purposeStrings = EntityUtil.getFieldListFromEntityList(postalPurposes, "contactMechPurposeTypeId", false);
                if (UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("SHIPPING_LOCATION")) {
                    needsShippingPurpose = false;
                }
                if (needsBillingPurpose && UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("BILLING_LOCATION")) {
                    needsBillingPurpose = false;
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (postalContactId == null) {
        postalMap.put("userLogin", cart.getUserLogin());
        postalMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
            postalContactId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechId", postalContactId);
        inMap.put("partyId", partyId);
        try {
            if (needsShippingPurpose) {
                inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
            if (needsBillingPurpose) {
                inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
        } catch (GenericServiceException e) {
            // Not the end of the world, we'll carry on
            Debug.logInfo(e.getMessage(), module);
        }
    }
    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    if ("Calculated Offline".equals(shipMethod)) {
        cart.setAllCarrierPartyId("_NA_");
        cart.setAllShipmentMethodTypeId("NO_SHIPPING");
    } else {
        String[] shipMethodSplit = shipMethod.split(" - ");
        cart.setAllCarrierPartyId(shipMethodSplit[0]);
        String shippingMethodTypeDesc = StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
        try {
            GenericValue shipmentMethod = EntityQuery.use(delegator).from("ProductStoreShipmentMethView").where("productStoreId", cart.getProductStoreId(), "partyId", shipMethodSplit[0], "roleTypeId", "CARRIER", "description", shippingMethodTypeDesc).queryFirst();
            cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
        } catch (GenericEntityException e1) {
            Debug.logError(e1, module);
        }
    }
    // Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
        Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
        for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
            cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
        }
    }
    cart.cleanUpShipGroups();
    cart.setAllShippingContactMechId(postalContactId);
    Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
        return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }
    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
        shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
        cho.calcAndAddTax();
    } catch (GeneralException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));
    try {
        outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");
    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, RoundingMode.HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) CartShipInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) PayPalException(com.paypal.sdk.exceptions.PayPalException) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) 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) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Example 2 with CartShipInfo

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

the class ShoppingCartServices method loadCartFromQuote.

public static Map<String, Object> loadCartFromQuote(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String quoteId = (String) context.get("quoteId");
    String applyQuoteAdjustmentsString = (String) context.get("applyQuoteAdjustments");
    Locale locale = (Locale) context.get("locale");
    boolean applyQuoteAdjustments = applyQuoteAdjustmentsString == null || "true".equals(applyQuoteAdjustmentsString);
    // get the quote header
    GenericValue quote = null;
    try {
        quote = EntityQuery.use(delegator).from("Quote").where("quoteId", quoteId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // initial require cart info
    String productStoreId = quote.getString("productStoreId");
    String currency = quote.getString("currencyUomId");
    // create the cart
    ShoppingCart cart = new ShoppingCart(delegator, productStoreId, locale, currency);
    // set shopping cart type
    if ("PURCHASE_QUOTE".equals(quote.getString("quoteTypeId"))) {
        cart.setOrderType("PURCHASE_ORDER");
        cart.setBillFromVendorPartyId(quote.getString("partyId"));
    }
    try {
        cart.setUserLogin(userLogin, dispatcher);
    } catch (CartItemModifyException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    cart.setQuoteId(quoteId);
    cart.setOrderName(quote.getString("quoteName"));
    cart.setChannelType(quote.getString("salesChannelEnumId"));
    List<GenericValue> quoteItems = null;
    List<GenericValue> quoteAdjs = null;
    List<GenericValue> quoteRoles = null;
    List<GenericValue> quoteAttributes = null;
    List<GenericValue> quoteTerms = null;
    try {
        quoteItems = quote.getRelated("QuoteItem", null, UtilMisc.toList("quoteItemSeqId"), false);
        quoteAdjs = quote.getRelated("QuoteAdjustment", null, null, false);
        quoteRoles = quote.getRelated("QuoteRole", null, null, false);
        quoteAttributes = quote.getRelated("QuoteAttribute", null, null, false);
        quoteTerms = quote.getRelated("QuoteTerm", null, null, false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // set the role information
    cart.setOrderPartyId(quote.getString("partyId"));
    if (UtilValidate.isNotEmpty(quoteRoles)) {
        for (GenericValue quoteRole : quoteRoles) {
            String quoteRoleTypeId = quoteRole.getString("roleTypeId");
            String quoteRolePartyId = quoteRole.getString("partyId");
            if ("PLACING_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setPlacingCustomerPartyId(quoteRolePartyId);
            } else if ("BILL_TO_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setBillToCustomerPartyId(quoteRolePartyId);
            } else if ("SHIP_TO_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setShipToCustomerPartyId(quoteRolePartyId);
            } else if ("END_USER_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setEndUserCustomerPartyId(quoteRolePartyId);
            } else if ("BILL_FROM_VENDOR".equals(quoteRoleTypeId)) {
                cart.setBillFromVendorPartyId(quoteRolePartyId);
            } else {
                cart.addAdditionalPartyRole(quoteRolePartyId, quoteRoleTypeId);
            }
        }
    }
    // set the order term
    if (UtilValidate.isNotEmpty(quoteTerms)) {
        // create order term from quote term
        for (GenericValue quoteTerm : quoteTerms) {
            BigDecimal termValue = BigDecimal.ZERO;
            if (UtilValidate.isNotEmpty(quoteTerm.getString("termValue"))) {
                termValue = new BigDecimal(quoteTerm.getString("termValue"));
            }
            long termDays = 0;
            if (UtilValidate.isNotEmpty(quoteTerm.getString("termDays"))) {
                termDays = Long.parseLong(quoteTerm.getString("termDays").trim());
            }
            String orderItemSeqId = quoteTerm.getString("quoteItemSeqId");
            cart.addOrderTerm(quoteTerm.getString("termTypeId"), orderItemSeqId, termValue, termDays, quoteTerm.getString("textValue"), quoteTerm.getString("description"));
        }
    }
    // set the attribute information
    if (UtilValidate.isNotEmpty(quoteAttributes)) {
        for (GenericValue quoteAttribute : quoteAttributes) {
            cart.setOrderAttribute(quoteAttribute.getString("attrName"), quoteAttribute.getString("attrValue"));
        }
    }
    // Convert the quote adjustment to order header adjustments and
    // put them in a map: the key/values pairs are quoteItemSeqId/List of adjs
    Map<String, List<GenericValue>> orderAdjsMap = new HashMap<>();
    for (GenericValue quoteAdj : quoteAdjs) {
        List<GenericValue> orderAdjs = orderAdjsMap.get(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId")) ? quoteAdj.getString("quoteItemSeqId") : quoteId);
        if (orderAdjs == null) {
            orderAdjs = new LinkedList<>();
            orderAdjsMap.put(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId")) ? quoteAdj.getString("quoteItemSeqId") : quoteId, orderAdjs);
        }
        // convert quote adjustments to order adjustments
        GenericValue orderAdj = delegator.makeValue("OrderAdjustment");
        orderAdj.put("orderAdjustmentId", quoteAdj.get("quoteAdjustmentId"));
        orderAdj.put("orderAdjustmentTypeId", quoteAdj.get("quoteAdjustmentTypeId"));
        orderAdj.put("orderItemSeqId", quoteAdj.get("quoteItemSeqId"));
        orderAdj.put("comments", quoteAdj.get("comments"));
        orderAdj.put("description", quoteAdj.get("description"));
        orderAdj.put("amount", quoteAdj.get("amount"));
        orderAdj.put("productPromoId", quoteAdj.get("productPromoId"));
        orderAdj.put("productPromoRuleId", quoteAdj.get("productPromoRuleId"));
        orderAdj.put("productPromoActionSeqId", quoteAdj.get("productPromoActionSeqId"));
        orderAdj.put("productFeatureId", quoteAdj.get("productFeatureId"));
        orderAdj.put("correspondingProductId", quoteAdj.get("correspondingProductId"));
        orderAdj.put("sourceReferenceId", quoteAdj.get("sourceReferenceId"));
        orderAdj.put("sourcePercentage", quoteAdj.get("sourcePercentage"));
        orderAdj.put("customerReferenceId", quoteAdj.get("customerReferenceId"));
        orderAdj.put("primaryGeoId", quoteAdj.get("primaryGeoId"));
        orderAdj.put("secondaryGeoId", quoteAdj.get("secondaryGeoId"));
        orderAdj.put("exemptAmount", quoteAdj.get("exemptAmount"));
        orderAdj.put("taxAuthGeoId", quoteAdj.get("taxAuthGeoId"));
        orderAdj.put("taxAuthPartyId", quoteAdj.get("taxAuthPartyId"));
        orderAdj.put("overrideGlAccountId", quoteAdj.get("overrideGlAccountId"));
        orderAdj.put("includeInTax", quoteAdj.get("includeInTax"));
        orderAdj.put("includeInShipping", quoteAdj.get("includeInShipping"));
        orderAdj.put("createdDate", quoteAdj.get("createdDate"));
        orderAdj.put("createdByUserLogin", quoteAdj.get("createdByUserLogin"));
        orderAdjs.add(orderAdj);
    }
    long nextItemSeq = 0;
    if (UtilValidate.isNotEmpty(quoteItems)) {
        Pattern pattern = Pattern.compile("\\P{Digit}");
        for (GenericValue quoteItem : quoteItems) {
            // get the next item sequence id
            String orderItemSeqId = quoteItem.getString("quoteItemSeqId");
            Matcher pmatcher = pattern.matcher(orderItemSeqId);
            orderItemSeqId = pmatcher.replaceAll("");
            try {
                long seq = Long.parseLong(orderItemSeqId);
                if (seq > nextItemSeq) {
                    nextItemSeq = seq;
                }
            } catch (NumberFormatException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
            boolean isPromo = quoteItem.get("isPromo") != null && "Y".equals(quoteItem.getString("isPromo"));
            if (isPromo && !applyQuoteAdjustments) {
                // do not include PROMO items
                continue;
            }
            // not a promo item; go ahead and add it in
            BigDecimal amount = quoteItem.getBigDecimal("selectedAmount");
            if (amount == null) {
                amount = BigDecimal.ZERO;
            }
            BigDecimal quantity = quoteItem.getBigDecimal("quantity");
            if (quantity == null) {
                quantity = BigDecimal.ZERO;
            }
            BigDecimal quoteUnitPrice = quoteItem.getBigDecimal("quoteUnitPrice");
            if (quoteUnitPrice == null) {
                quoteUnitPrice = BigDecimal.ZERO;
            }
            if (amount.compareTo(BigDecimal.ZERO) > 0) {
                // If, in the quote, an amount is set, we need to
                // pass to the cart the quoteUnitPrice/amount value.
                quoteUnitPrice = quoteUnitPrice.divide(amount, generalRounding);
            }
            // rental product data
            Timestamp reservStart = quoteItem.getTimestamp("reservStart");
            BigDecimal reservLength = quoteItem.getBigDecimal("reservLength");
            BigDecimal reservPersons = quoteItem.getBigDecimal("reservPersons");
            int itemIndex = -1;
            if (quoteItem.get("productId") == null) {
                // non-product item
                String desc = quoteItem.getString("comments");
                try {
                    // note that passing in null for itemGroupNumber as there is no real grouping concept in the quotes right now
                    itemIndex = cart.addNonProductItem(null, desc, null, null, quantity, null, null, null, dispatcher);
                } catch (CartItemModifyException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                }
            } else {
                // product item
                String productId = quoteItem.getString("productId");
                ProductConfigWrapper configWrapper = null;
                if (UtilValidate.isNotEmpty(quoteItem.getString("configId"))) {
                    configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, quoteItem.getString("configId"), productId, productStoreId, null, null, currency, locale, userLogin);
                }
                try {
                    itemIndex = cart.addItemToEnd(productId, amount, quantity, quoteUnitPrice, reservStart, reservLength, reservPersons, null, null, null, null, null, configWrapper, null, dispatcher, Boolean.valueOf(!applyQuoteAdjustments), Boolean.valueOf(quoteUnitPrice.compareTo(BigDecimal.ZERO) == 0), Boolean.FALSE, Boolean.FALSE);
                } catch (ItemNotFoundException | CartItemModifyException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                }
            }
            // flag the item w/ the orderItemSeqId so we can reference it
            ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
            cartItem.setOrderItemSeqId(orderItemSeqId);
            // attach additional item information
            cartItem.setItemComment(quoteItem.getString("comments"));
            cartItem.setQuoteId(quoteItem.getString("quoteId"));
            cartItem.setQuoteItemSeqId(quoteItem.getString("quoteItemSeqId"));
            cartItem.setIsPromo(isPromo);
        }
    }
    // If applyQuoteAdjustments is set to false then standard cart adjustments are used.
    if (applyQuoteAdjustments) {
        // The cart adjustments, derived from quote adjustments, are added to the cart
        // Tax adjustments should be added to the shipping group and shipping group item info
        // Other adjustments like promotional price should be added to the cart independent of
        // the ship group.
        // We're creating the cart right now using data from the quote, so there cannot yet be more than one ship group.
        List<GenericValue> cartAdjs = cart.getAdjustments();
        CartShipInfo shipInfo = cart.getShipInfo(0);
        List<GenericValue> adjs = orderAdjsMap.get(quoteId);
        if (adjs != null) {
            for (GenericValue adj : adjs) {
                if (isTaxAdjustment(adj)) {
                    shipInfo.shipTaxAdj.add(adj);
                } else {
                    cartAdjs.add(adj);
                }
            }
        }
        // The cart item adjustments, derived from quote item adjustments, are added to the cart
        if (quoteItems != null) {
            for (ShoppingCartItem item : cart) {
                String orderItemSeqId = item.getOrderItemSeqId();
                if (orderItemSeqId != null) {
                    adjs = orderAdjsMap.get(orderItemSeqId);
                } else {
                    adjs = null;
                }
                if (adjs != null) {
                    for (GenericValue adj : adjs) {
                        if (isTaxAdjustment(adj)) {
                            CartShipItemInfo csii = shipInfo.getShipItemInfo(item);
                            if (csii.itemTaxAdj == null) {
                                shipInfo.setItemInfo(item, UtilMisc.toList(adj));
                            } else {
                                csii.itemTaxAdj.add(adj);
                            }
                        } else {
                            item.addAdjustment(adj);
                        }
                    }
                }
            }
        }
    }
    // set the item seq in the cart
    if (nextItemSeq > 0) {
        try {
            cart.setNextItemSeq(nextItemSeq + 1);
        } catch (GeneralException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shoppingCart", cart);
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ProductConfigWrapper(org.apache.ofbiz.product.config.ProductConfigWrapper) CartShipInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo) Timestamp(java.sql.Timestamp) CartShipItemInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo.CartShipItemInfo) LinkedList(java.util.LinkedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) Pattern(java.util.regex.Pattern) GeneralException(org.apache.ofbiz.base.util.GeneralException) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 3 with CartShipInfo

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

the class ShoppingCartServices method loadCartFromOrder.

public static Map<String, Object> loadCartFromOrder(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String orderId = (String) context.get("orderId");
    Boolean skipInventoryChecks = (Boolean) context.get("skipInventoryChecks");
    Boolean skipProductChecks = (Boolean) context.get("skipProductChecks");
    boolean includePromoItems = Boolean.TRUE.equals(context.get("includePromoItems"));
    Locale locale = (Locale) context.get("locale");
    // FIXME: deepak:Personally I don't like the idea of passing flag but for orderItem quantity calculation we need this flag.
    String createAsNewOrder = (String) context.get("createAsNewOrder");
    List<GenericValue> orderTerms = null;
    List<GenericValue> orderContactMechs = null;
    if (UtilValidate.isEmpty(skipInventoryChecks)) {
        skipInventoryChecks = Boolean.FALSE;
    }
    if (UtilValidate.isEmpty(skipProductChecks)) {
        skipProductChecks = Boolean.FALSE;
    }
    // get the order header
    GenericValue orderHeader = null;
    try {
        orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
        orderTerms = orderHeader.getRelated("OrderTerm", null, null, false);
        orderContactMechs = orderHeader.getRelated("OrderContactMech", null, null, false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // initial require cart info
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    String productStoreId = orh.getProductStoreId();
    String orderTypeId = orh.getOrderTypeId();
    String currency = orh.getCurrency();
    String website = orh.getWebSiteId();
    String currentStatusString = orh.getCurrentStatusString();
    // create the cart
    ShoppingCart cart = new ShoppingCart(delegator, productStoreId, website, locale, currency);
    cart.setDoPromotions(!includePromoItems);
    cart.setOrderType(orderTypeId);
    cart.setChannelType(orderHeader.getString("salesChannelEnumId"));
    cart.setInternalCode(orderHeader.getString("internalCode"));
    if ("Y".equals(createAsNewOrder)) {
        cart.setOrderDate(UtilDateTime.nowTimestamp());
    } else {
        cart.setOrderDate(orderHeader.getTimestamp("orderDate"));
    }
    cart.setOrderId(orderHeader.getString("orderId"));
    cart.setOrderName(orderHeader.getString("orderName"));
    cart.setOrderStatusId(orderHeader.getString("statusId"));
    cart.setOrderStatusString(currentStatusString);
    cart.setFacilityId(orderHeader.getString("originFacilityId"));
    cart.setAgreementId(orderHeader.getString("agreementId"));
    try {
        cart.setUserLogin(userLogin, dispatcher);
    } catch (CartItemModifyException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // set the role information
    GenericValue placingParty = orh.getPlacingParty();
    if (placingParty != null) {
        cart.setPlacingCustomerPartyId(placingParty.getString("partyId"));
    }
    GenericValue billFromParty = orh.getBillFromParty();
    if (billFromParty != null) {
        cart.setBillFromVendorPartyId(billFromParty.getString("partyId"));
    }
    GenericValue billToParty = orh.getBillToParty();
    if (billToParty != null) {
        cart.setBillToCustomerPartyId(billToParty.getString("partyId"));
    }
    GenericValue shipToParty = orh.getShipToParty();
    if (shipToParty != null) {
        cart.setShipToCustomerPartyId(shipToParty.getString("partyId"));
    }
    GenericValue endUserParty = orh.getEndUserParty();
    if (endUserParty != null) {
        cart.setEndUserCustomerPartyId(endUserParty.getString("partyId"));
        cart.setOrderPartyId(endUserParty.getString("partyId"));
    }
    // load order attributes
    List<GenericValue> orderAttributesList = null;
    try {
        orderAttributesList = EntityQuery.use(delegator).from("OrderAttribute").where("orderId", orderId).queryList();
        if (UtilValidate.isNotEmpty(orderAttributesList)) {
            for (GenericValue orderAttr : orderAttributesList) {
                String name = orderAttr.getString("attrName");
                String value = orderAttr.getString("attrValue");
                cart.setOrderAttribute(name, value);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // load the payment infos
    List<GenericValue> orderPaymentPrefs = 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"));
        orderPaymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where(exprs).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (UtilValidate.isNotEmpty(orderPaymentPrefs)) {
        Iterator<GenericValue> oppi = orderPaymentPrefs.iterator();
        while (oppi.hasNext()) {
            GenericValue opp = oppi.next();
            String paymentId = opp.getString("paymentMethodId");
            if (paymentId == null) {
                paymentId = opp.getString("paymentMethodTypeId");
            }
            BigDecimal maxAmount = opp.getBigDecimal("maxAmount");
            String overflow = opp.getString("overflowFlag");
            ShoppingCart.CartPaymentInfo cpi = null;
            if ((overflow == null || !"Y".equals(overflow)) && oppi.hasNext()) {
                cpi = cart.addPaymentAmount(paymentId, maxAmount);
                Debug.logInfo("Added Payment: " + paymentId + " / " + maxAmount, module);
            } else {
                cpi = cart.addPayment(paymentId);
                Debug.logInfo("Added Payment: " + paymentId + " / [no max]", module);
            }
            // for finance account the finAccountId needs to be set
            if ("FIN_ACCOUNT".equals(paymentId)) {
                cpi.finAccountId = opp.getString("finAccountId");
            }
            // set the billing account and amount
            cart.setBillingAccount(orderHeader.getString("billingAccountId"), orh.getBillingAccountMaxAmount());
        }
    } else {
        Debug.logInfo("No payment preferences found for order #" + orderId, module);
    }
    // set the order term
    if (UtilValidate.isNotEmpty(orderTerms)) {
        for (GenericValue orderTerm : orderTerms) {
            BigDecimal termValue = BigDecimal.ZERO;
            if (UtilValidate.isNotEmpty(orderTerm.getString("termValue"))) {
                termValue = new BigDecimal(orderTerm.getString("termValue"));
            }
            long termDays = 0;
            if (UtilValidate.isNotEmpty(orderTerm.getString("termDays"))) {
                termDays = Long.parseLong(orderTerm.getString("termDays").trim());
            }
            String orderItemSeqId = orderTerm.getString("orderItemSeqId");
            cart.addOrderTerm(orderTerm.getString("termTypeId"), orderItemSeqId, termValue, termDays, orderTerm.getString("textValue"), orderTerm.getString("description"));
        }
    }
    if (UtilValidate.isNotEmpty(orderContactMechs)) {
        for (GenericValue orderContactMech : orderContactMechs) {
            cart.addContactMech(orderContactMech.getString("contactMechPurposeTypeId"), orderContactMech.getString("contactMechId"));
        }
    }
    List<GenericValue> orderItemShipGroupList = orh.getOrderItemShipGroups();
    for (GenericValue orderItemShipGroup : orderItemShipGroupList) {
        // should be sorted by shipGroupSeqId
        int newShipInfoIndex = cart.addShipInfo();
        CartShipInfo cartShipInfo = cart.getShipInfo(newShipInfoIndex);
        cartShipInfo.shipAfterDate = orderItemShipGroup.getTimestamp("shipAfterDate");
        cartShipInfo.shipBeforeDate = orderItemShipGroup.getTimestamp("shipByDate");
        cartShipInfo.shipmentMethodTypeId = orderItemShipGroup.getString("shipmentMethodTypeId");
        cartShipInfo.carrierPartyId = orderItemShipGroup.getString("carrierPartyId");
        cartShipInfo.supplierPartyId = orderItemShipGroup.getString("supplierPartyId");
        cartShipInfo.setMaySplit(orderItemShipGroup.getBoolean("maySplit"));
        cartShipInfo.giftMessage = orderItemShipGroup.getString("giftMessage");
        cartShipInfo.setContactMechId(orderItemShipGroup.getString("contactMechId"));
        cartShipInfo.shippingInstructions = orderItemShipGroup.getString("shippingInstructions");
        cartShipInfo.setFacilityId(orderItemShipGroup.getString("facilityId"));
        cartShipInfo.setVendorPartyId(orderItemShipGroup.getString("vendorPartyId"));
        cartShipInfo.setShipGroupSeqId(orderItemShipGroup.getString("shipGroupSeqId"));
        cartShipInfo.shipTaxAdj.addAll(orh.getOrderHeaderAdjustmentsTax(orderItemShipGroup.getString("shipGroupSeqId")));
    }
    List<GenericValue> orderItems = orh.getOrderItems();
    long nextItemSeq = 0;
    if (UtilValidate.isNotEmpty(orderItems)) {
        Pattern pattern = Pattern.compile("\\P{Digit}");
        for (GenericValue item : orderItems) {
            // get the next item sequence id
            String orderItemSeqId = item.getString("orderItemSeqId");
            Matcher pmatcher = pattern.matcher(orderItemSeqId);
            orderItemSeqId = pmatcher.replaceAll("");
            // get product Id
            String productId = item.getString("productId");
            GenericValue product = null;
            // creates survey responses for Gift cards same as last Order created
            Map<String, Object> surveyResponseResult = null;
            try {
                long seq = Long.parseLong(orderItemSeqId);
                if (seq > nextItemSeq) {
                    nextItemSeq = seq;
                }
            } catch (NumberFormatException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
            if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) {
                continue;
            }
            try {
                product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                if ("DIGITAL_GOOD".equals(product.getString("productTypeId"))) {
                    Map<String, Object> surveyResponseMap = new HashMap<>();
                    Map<String, Object> answers = new HashMap<>();
                    List<GenericValue> surveyResponseAndAnswers = EntityQuery.use(delegator).from("SurveyResponseAndAnswer").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
                    if (UtilValidate.isNotEmpty(surveyResponseAndAnswers)) {
                        String surveyId = EntityUtil.getFirst(surveyResponseAndAnswers).getString("surveyId");
                        for (GenericValue surveyResponseAndAnswer : surveyResponseAndAnswers) {
                            answers.put((surveyResponseAndAnswer.get("surveyQuestionId").toString()), surveyResponseAndAnswer.get("textResponse"));
                        }
                        surveyResponseMap.put("answers", answers);
                        surveyResponseMap.put("surveyId", surveyId);
                        surveyResponseResult = dispatcher.runSync("createSurveyResponse", surveyResponseMap);
                        if (ServiceUtil.isError(surveyResponseResult)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(surveyResponseResult));
                        }
                    }
                }
            } catch (GenericEntityException | GenericServiceException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
            // do not include PROMO items
            if (!includePromoItems && item.get("isPromo") != null && "Y".equals(item.getString("isPromo"))) {
                continue;
            }
            // not a promo item; go ahead and add it in
            BigDecimal amount = item.getBigDecimal("selectedAmount");
            if (amount == null) {
                amount = BigDecimal.ZERO;
            }
            // BigDecimal quantity = item.getBigDecimal("quantity");
            BigDecimal quantity = BigDecimal.ZERO;
            if ("ITEM_COMPLETED".equals(item.getString("statusId")) && "N".equals(createAsNewOrder)) {
                quantity = item.getBigDecimal("quantity");
            } else {
                quantity = OrderReadHelper.getOrderItemQuantity(item);
            }
            if (quantity == null) {
                quantity = BigDecimal.ZERO;
            }
            BigDecimal unitPrice = null;
            if ("Y".equals(item.getString("isModifiedPrice"))) {
                unitPrice = item.getBigDecimal("unitPrice");
            }
            int itemIndex = -1;
            if (item.get("productId") == null) {
                // non-product item
                String itemType = item.getString("orderItemTypeId");
                String desc = item.getString("itemDescription");
                try {
                    // TODO: passing in null now for itemGroupNumber, but should reproduce from OrderItemGroup records
                    itemIndex = cart.addNonProductItem(itemType, desc, null, unitPrice, quantity, null, null, null, dispatcher);
                } catch (CartItemModifyException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                }
            } else {
                // product item
                String prodCatalogId = item.getString("prodCatalogId");
                // prepare the rental data
                Timestamp reservStart = null;
                BigDecimal reservLength = null;
                BigDecimal reservPersons = null;
                String accommodationMapId = null;
                String accommodationSpotId = null;
                GenericValue workEffort = null;
                String workEffortId = orh.getCurrentOrderItemWorkEffort(item);
                if (workEffortId != null) {
                    try {
                        workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne();
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                }
                if (workEffort != null && "ASSET_USAGE".equals(workEffort.getString("workEffortTypeId"))) {
                    reservStart = workEffort.getTimestamp("estimatedStartDate");
                    reservLength = OrderReadHelper.getWorkEffortRentalLength(workEffort);
                    reservPersons = workEffort.getBigDecimal("reservPersons");
                    accommodationMapId = workEffort.getString("accommodationMapId");
                    accommodationSpotId = workEffort.getString("accommodationSpotId");
                }
                // end of rental data
                // check for AGGREGATED products
                ProductConfigWrapper configWrapper = null;
                String configId = null;
                try {
                    product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                    if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "AGGREGATED")) {
                        GenericValue productAssoc = EntityQuery.use(delegator).from("ProductAssoc").where("productAssocTypeId", "PRODUCT_CONF", "productIdTo", product.getString("productId")).filterByDate().queryFirst();
                        if (productAssoc != null) {
                            productId = productAssoc.getString("productId");
                            configId = product.getString("configId");
                        }
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
                if (UtilValidate.isNotEmpty(configId)) {
                    configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, configId, productId, productStoreId, prodCatalogId, website, currency, locale, userLogin);
                }
                try {
                    itemIndex = cart.addItemToEnd(productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, null, null, prodCatalogId, configWrapper, item.getString("orderItemTypeId"), dispatcher, null, unitPrice == null ? null : false, skipInventoryChecks, skipProductChecks);
                } catch (ItemNotFoundException | CartItemModifyException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                }
            }
            // flag the item w/ the orderItemSeqId so we can reference it
            ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
            cartItem.setIsPromo(item.get("isPromo") != null && "Y".equals(item.getString("isPromo")));
            cartItem.setOrderItemSeqId(item.getString("orderItemSeqId"));
            try {
                cartItem.setItemGroup(cart.addItemGroup(item.getRelatedOne("OrderItemGroup", true)));
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
            // attach surveyResponseId for each item
            if (UtilValidate.isNotEmpty(surveyResponseResult)) {
                cartItem.setAttribute("surveyResponses", UtilMisc.toList(surveyResponseResult.get("surveyResponseId")));
            }
            // attach addition item information
            cartItem.setStatusId(item.getString("statusId"));
            cartItem.setItemType(item.getString("orderItemTypeId"));
            cartItem.setItemComment(item.getString("comments"));
            cartItem.setQuoteId(item.getString("quoteId"));
            cartItem.setQuoteItemSeqId(item.getString("quoteItemSeqId"));
            cartItem.setProductCategoryId(item.getString("productCategoryId"));
            cartItem.setDesiredDeliveryDate(item.getTimestamp("estimatedDeliveryDate"));
            cartItem.setShipBeforeDate(item.getTimestamp("shipBeforeDate"));
            cartItem.setShipAfterDate(item.getTimestamp("shipAfterDate"));
            cartItem.setShoppingList(item.getString("shoppingListId"), item.getString("shoppingListItemSeqId"));
            cartItem.setIsModifiedPrice("Y".equals(item.getString("isModifiedPrice")));
            cartItem.setName(item.getString("itemDescription"));
            cartItem.setExternalId(item.getString("externalId"));
            cartItem.setListPrice(item.getBigDecimal("unitListPrice"));
            // load order item attributes
            List<GenericValue> orderItemAttributesList = null;
            try {
                orderItemAttributesList = EntityQuery.use(delegator).from("OrderItemAttribute").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
                if (UtilValidate.isNotEmpty(orderItemAttributesList)) {
                    for (GenericValue orderItemAttr : orderItemAttributesList) {
                        String name = orderItemAttr.getString("attrName");
                        String value = orderItemAttr.getString("attrValue");
                        cartItem.setOrderItemAttribute(name, value);
                    }
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
            // load order item contact mechs
            List<GenericValue> orderItemContactMechList = null;
            try {
                orderItemContactMechList = EntityQuery.use(delegator).from("OrderItemContactMech").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
                if (UtilValidate.isNotEmpty(orderItemContactMechList)) {
                    for (GenericValue orderItemContactMech : orderItemContactMechList) {
                        String contactMechPurposeTypeId = orderItemContactMech.getString("contactMechPurposeTypeId");
                        String contactMechId = orderItemContactMech.getString("contactMechId");
                        cartItem.addContactMech(contactMechPurposeTypeId, contactMechId);
                    }
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
            // set the PO number on the cart
            cart.setPoNumber(item.getString("correspondingPoId"));
            // get all item adjustments EXCEPT tax adjustments
            List<GenericValue> itemAdjustments = orh.getOrderItemAdjustments(item);
            if (itemAdjustments != null) {
                for (GenericValue itemAdjustment : itemAdjustments) {
                    if (!isTaxAdjustment(itemAdjustment)) {
                        cartItem.addAdjustment(itemAdjustment);
                    }
                }
            }
        }
        // setup the OrderItemShipGroupAssoc records
        if (UtilValidate.isNotEmpty(orderItems)) {
            int itemIndex = 0;
            for (GenericValue item : orderItems) {
                // if rejected or cancelled ignore, just like above otherwise all indexes will be off by one!
                if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) {
                    continue;
                }
                List<GenericValue> orderItemAdjustments = orh.getOrderItemAdjustments(item);
                // set the item's ship group info
                List<GenericValue> shipGroupAssocs = orh.getOrderItemShipGroupAssocs(item);
                if (UtilValidate.isNotEmpty(shipGroupAssocs)) {
                    shipGroupAssocs = EntityUtil.orderBy(shipGroupAssocs, UtilMisc.toList("-shipGroupSeqId"));
                }
                for (int g = 0; g < shipGroupAssocs.size(); g++) {
                    GenericValue sgAssoc = shipGroupAssocs.get(g);
                    BigDecimal shipGroupQty = OrderReadHelper.getOrderItemShipGroupQuantity(sgAssoc);
                    if (shipGroupQty == null) {
                        shipGroupQty = BigDecimal.ZERO;
                    }
                    String cartShipGroupIndexStr = sgAssoc.getString("shipGroupSeqId");
                    int cartShipGroupIndex = cart.getShipInfoIndex(cartShipGroupIndexStr);
                    if (cartShipGroupIndex > 0) {
                        cart.positionItemToGroup(itemIndex, shipGroupQty, 0, cartShipGroupIndex, false);
                    }
                    // because the ship groups are setup before loading items, and the ShoppingCart.addItemToEnd
                    // method is called when loading items above and it calls ShoppingCart.setItemShipGroupQty,
                    // this may not be necessary here, so check it first as calling it here with 0 quantity and
                    // such ends up removing cart items from the group, which causes problems later with inventory
                    // reservation, tax calculation, etc.
                    ShoppingCart.CartShipInfo csi = cart.getShipInfo(cartShipGroupIndex);
                    ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
                    if (cartItem == null || cartItem.getQuantity() == null || BigDecimal.ZERO.equals(cartItem.getQuantity()) || shipGroupQty.equals(cartItem.getQuantity())) {
                        Debug.logInfo("In loadCartFromOrder not adding item [" + item.getString("orderItemSeqId") + "] to ship group with index [" + itemIndex + "]; group quantity is [" + shipGroupQty + "] item quantity is [" + (cartItem != null ? cartItem.getQuantity() : "no cart item") + "] cartShipGroupIndex is [" + cartShipGroupIndex + "], csi.shipItemInfo.size(): " + (cartShipGroupIndex < 0 ? 0 : csi.shipItemInfo.size()), module);
                    } else {
                        cart.setItemShipGroupQty(itemIndex, shipGroupQty, cartShipGroupIndex);
                    }
                    List<GenericValue> shipGroupItemAdjustments = EntityUtil.filterByAnd(orderItemAdjustments, UtilMisc.toMap("shipGroupSeqId", cartShipGroupIndexStr));
                    if (cartItem == null || cartShipGroupIndex < 0) {
                        Debug.logWarning("In loadCartFromOrder could not find cart item for itemIndex=" + itemIndex + ", for orderId=" + orderId, module);
                    } else {
                        CartShipItemInfo cartShipItemInfo = csi.getShipItemInfo(cartItem);
                        if (cartShipItemInfo == null) {
                            Debug.logWarning("In loadCartFromOrder could not find CartShipItemInfo for itemIndex=" + itemIndex + ", for orderId=" + orderId, module);
                        } else {
                            List<GenericValue> itemTaxAdj = cartShipItemInfo.itemTaxAdj;
                            for (GenericValue shipGroupItemAdjustment : shipGroupItemAdjustments) {
                                if (isTaxAdjustment(shipGroupItemAdjustment)) {
                                    itemTaxAdj.add(shipGroupItemAdjustment);
                                }
                            }
                        }
                    }
                }
                itemIndex++;
            }
        }
        // set the item seq in the cart
        if (nextItemSeq > 0) {
            try {
                cart.setNextItemSeq(nextItemSeq + 1);
            } catch (GeneralException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        }
    }
    if (includePromoItems) {
        for (String productPromoCode : orh.getProductPromoCodesEntered()) {
            cart.addProductPromoCode(productPromoCode, dispatcher);
        }
        for (GenericValue productPromoUse : orh.getProductPromoUse()) {
            cart.addProductPromoUse(productPromoUse.getString("productPromoId"), productPromoUse.getString("productPromoCodeId"), productPromoUse.getBigDecimal("totalDiscountAmount"), productPromoUse.getBigDecimal("quantityLeftInActions"), new HashMap<ShoppingCartItem, BigDecimal>());
        }
    }
    List<GenericValue> adjustments = orh.getOrderHeaderAdjustments();
    // If applyQuoteAdjustments is set to false then standard cart adjustments are used.
    if (!adjustments.isEmpty()) {
        // The cart adjustments are added to the cart
        cart.getAdjustments().addAll(adjustments);
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shoppingCart", cart);
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) CartShipInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo) ProductConfigWrapper(org.apache.ofbiz.product.config.ProductConfigWrapper) CartShipInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo) Timestamp(java.sql.Timestamp) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) CartShipItemInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo.CartShipItemInfo) GenericValue(org.apache.ofbiz.entity.GenericValue) Pattern(java.util.regex.Pattern) GeneralException(org.apache.ofbiz.base.util.GeneralException) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Aggregations

BigDecimal (java.math.BigDecimal)3 HashMap (java.util.HashMap)3 Locale (java.util.Locale)3 GeneralException (org.apache.ofbiz.base.util.GeneralException)3 Delegator (org.apache.ofbiz.entity.Delegator)3 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)3 GenericValue (org.apache.ofbiz.entity.GenericValue)3 CartShipInfo (org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo)3 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)3 Timestamp (java.sql.Timestamp)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 CartShipItemInfo (org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo.CartShipItemInfo)2 ProductConfigWrapper (org.apache.ofbiz.product.config.ProductConfigWrapper)2 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)2 NVPDecoder (com.paypal.sdk.core.nvp.NVPDecoder)1 NVPEncoder (com.paypal.sdk.core.nvp.NVPEncoder)1 PayPalException (com.paypal.sdk.exceptions.PayPalException)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1