Search in sources :

Example 1 with CheckOutHelper

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

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

the class OrderServices method saveUpdatedCartToOrder.

private static void saveUpdatedCartToOrder(LocalDispatcher dispatcher, Delegator delegator, ShoppingCart cart, Locale locale, GenericValue userLogin, String orderId, Map<String, Object> changeMap, boolean calcTax, boolean deleteItems) throws GeneralException {
    // get/set the shipping estimates. If it's a SALES ORDER, then return an error if there are no ship estimates
    int shipGroupsSize = cart.getShipGroupSize();
    int realShipGroupsSize = (new OrderReadHelper(delegator, orderId)).getOrderItemShipGroups().size();
    // If an empty csi has initially been added to cart.shipInfo by ShoppingCart.setItemShipGroupQty() (called indirectly by ShoppingCart.setUserLogin() and then ProductPromoWorker.doPromotions(), etc.)
    // shipGroupsSize > realShipGroupsSize are different (+1 for shipGroupsSize), then simply bypass the 1st empty csi!
    int origin = realShipGroupsSize == shipGroupsSize ? 0 : 1;
    for (int gi = origin; gi < shipGroupsSize; gi++) {
        String shipmentMethodTypeId = cart.getShipmentMethodTypeId(gi);
        String carrierPartyId = cart.getCarrierPartyId(gi);
        Debug.logInfo("Getting ship estimate for group #" + gi + " [" + shipmentMethodTypeId + " / " + carrierPartyId + "]", module);
        Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, gi);
        if (("SALES_ORDER".equals(cart.getOrderType())) && (ServiceUtil.isError(result))) {
            Debug.logError(ServiceUtil.getErrorMessage(result), module);
            throw new GeneralException(ServiceUtil.getErrorMessage(result));
        }
        BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
        if (shippingTotal == null) {
            shippingTotal = BigDecimal.ZERO;
        }
        cart.setItemShipGroupEstimate(shippingTotal, gi);
    }
    // calc the sales tax
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    if (calcTax) {
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            throw new GeneralException(e.getMessage());
        }
    }
    // get the new orderItems, adjustments, shipping info, payments and order item attributes from the cart
    List<Map<String, Object>> modifiedItems = new LinkedList<>();
    List<Map<String, Object>> newItems = new LinkedList<>();
    List<GenericValue> toStore = new LinkedList<>();
    List<GenericValue> toAddList = new ArrayList<>();
    toAddList.addAll(cart.makeAllAdjustments());
    cart.clearAllPromotionAdjustments();
    ProductPromoWorker.doPromotions(cart, dispatcher);
    // validate the payment methods
    Map<String, Object> validateResp = coh.validatePaymentMethods();
    if (ServiceUtil.isError(validateResp)) {
        throw new GeneralException(ServiceUtil.getErrorMessage(validateResp));
    }
    // handle OrderHeader fields
    String billingAccountId = cart.getBillingAccountId();
    if (UtilValidate.isNotEmpty(billingAccountId)) {
        try {
            GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
            orderHeader.set("billingAccountId", billingAccountId);
            toStore.add(orderHeader);
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            throw new GeneralException(e.getMessage());
        }
    }
    toStore.addAll(cart.makeOrderItems(false, true, dispatcher));
    toStore.addAll(cart.makeAllAdjustments());
    long groupIndex = cart.getShipInfoSize();
    if (!deleteItems) {
        for (long itr = 1; itr <= groupIndex; itr++) {
            List<GenericValue> removeList = new ArrayList<>();
            for (GenericValue stored : toStore) {
                if ("OrderAdjustment".equals(stored.getEntityName())) {
                    if (("SHIPPING_CHARGES".equals(stored.get("orderAdjustmentTypeId")) || "SALES_TAX".equals(stored.get("orderAdjustmentTypeId"))) && stored.get("orderId").equals(orderId)) {
                        // Removing objects from toStore list for old Shipping and Handling Charges Adjustment and Sales Tax Adjustment.
                        removeList.add(stored);
                    }
                    if ("Y".equals(stored.getString("isManual"))) {
                        // Removing objects from toStore list for Manually added Adjustment.
                        removeList.add(stored);
                    }
                }
            }
            toStore.removeAll(removeList);
        }
        for (GenericValue toAdd : toAddList) {
            if ("OrderAdjustment".equals(toAdd.getEntityName())) {
                if ("Y".equals(toAdd.getString("isManual")) && (("PROMOTION_ADJUSTMENT".equals(toAdd.get("orderAdjustmentTypeId"))) || ("SHIPPING_CHARGES".equals(toAdd.get("orderAdjustmentTypeId"))) || ("SALES_TAX".equals(toAdd.get("orderAdjustmentTypeId"))))) {
                    toStore.add(toAdd);
                }
            }
        }
    } else {
        // add all the cart adjustments
        toStore.addAll(toAddList);
    }
    // Creating objects for New Shipping and Handling Charges Adjustment and Sales Tax Adjustment
    toStore.addAll(cart.makeAllShipGroupInfos());
    toStore.addAll(cart.makeAllOrderPaymentInfos(dispatcher));
    toStore.addAll(cart.makeAllOrderItemAttributes(orderId, ShoppingCart.FILLED_ONLY));
    List<GenericValue> toRemove = new LinkedList<>();
    if (deleteItems) {
        // flag to delete existing order items and adjustments
        try {
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItemContactMech").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItemPriceInfo").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItemAttribute").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItemBilling").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItemRole").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItemChange").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderAdjustment").where("orderId", orderId).queryList());
            toRemove.addAll(EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId).queryList());
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    } else {
        // get the empty order item atrributes from the cart and remove them
        toRemove.addAll(cart.makeAllOrderItemAttributes(orderId, ShoppingCart.EMPTY_ONLY));
    }
    // get the promo uses and codes
    for (String promoCodeEntered : cart.getProductPromoCodesEntered()) {
        GenericValue orderProductPromoCode = delegator.makeValue("OrderProductPromoCode");
        orderProductPromoCode.set("orderId", orderId);
        orderProductPromoCode.set("productPromoCodeId", promoCodeEntered);
        toStore.add(orderProductPromoCode);
    }
    for (GenericValue promoUse : cart.makeProductPromoUses()) {
        promoUse.set("orderId", orderId);
        toStore.add(promoUse);
    }
    List<GenericValue> existingPromoCodes = null;
    List<GenericValue> existingPromoUses = null;
    try {
        existingPromoCodes = EntityQuery.use(delegator).from("OrderProductPromoCode").where("orderId", orderId).queryList();
        existingPromoUses = EntityQuery.use(delegator).from("ProductPromoUse").where("orderId", orderId).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    toRemove.addAll(existingPromoCodes);
    toRemove.addAll(existingPromoUses);
    // set the orderId & other information on all new value objects
    // this list will contain the ids of all the ship groups for drop shipments (no reservations)
    List<String> dropShipGroupIds = new LinkedList<>();
    for (GenericValue valueObj : toStore) {
        valueObj.set("orderId", orderId);
        if ("OrderItemShipGroup".equals(valueObj.getEntityName())) {
            // ship group
            if (valueObj.get("carrierRoleTypeId") == null) {
                valueObj.set("carrierRoleTypeId", "CARRIER");
            }
            if (UtilValidate.isNotEmpty(valueObj.get("supplierPartyId"))) {
                dropShipGroupIds.add(valueObj.getString("shipGroupSeqId"));
            }
        } else if ("OrderAdjustment".equals(valueObj.getEntityName())) {
            // shipping / tax adjustment(s)
            if (UtilValidate.isEmpty(valueObj.get("orderItemSeqId"))) {
                valueObj.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
            }
            // in order to avoid duplicate adjustments don't set orderAdjustmentId (which is the pk) if there is already one
            if (UtilValidate.isEmpty(valueObj.getString("orderAdjustmentId"))) {
                valueObj.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
            }
            valueObj.set("createdDate", UtilDateTime.nowTimestamp());
            valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
        } else if ("OrderPaymentPreference".equals(valueObj.getEntityName())) {
            if (valueObj.get("orderPaymentPreferenceId") == null) {
                valueObj.set("orderPaymentPreferenceId", delegator.getNextSeqId("OrderPaymentPreference"));
                valueObj.set("createdDate", UtilDateTime.nowTimestamp());
                valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
            }
            if (valueObj.get("statusId") == null) {
                valueObj.set("statusId", "PAYMENT_NOT_RECEIVED");
            }
        } else if ("OrderItem".equals(valueObj.getEntityName()) && !deleteItems) {
            // ignore promotion items. They are added/canceled automatically
            if ("Y".equals(valueObj.getString("isPromo"))) {
                // Fetching the new promo items and adding it to list so that we can create OrderStatus record for that items.
                Map<String, Object> promoItem = new HashMap<>();
                promoItem.put("orderId", valueObj.getString("orderId"));
                promoItem.put("orderItemSeqId", valueObj.getString("orderItemSeqId"));
                promoItem.put("quantity", valueObj.getBigDecimal("quantity"));
                newItems.add(promoItem);
                continue;
            }
            GenericValue oldOrderItem = null;
            try {
                oldOrderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", valueObj.getString("orderId"), "orderItemSeqId", valueObj.getString("orderItemSeqId")).queryOne();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
                throw new GeneralException(e.getMessage());
            }
            if (oldOrderItem != null) {
                // Existing order item found. Check for modifications and store if any
                String oldItemDescription = oldOrderItem.getString("itemDescription") != null ? oldOrderItem.getString("itemDescription") : "";
                BigDecimal oldQuantity = oldOrderItem.getBigDecimal("quantity") != null ? oldOrderItem.getBigDecimal("quantity") : BigDecimal.ZERO;
                BigDecimal oldUnitPrice = oldOrderItem.getBigDecimal("unitPrice") != null ? oldOrderItem.getBigDecimal("unitPrice") : BigDecimal.ZERO;
                String oldItemComment = oldOrderItem.getString("comments") != null ? oldOrderItem.getString("comments") : "";
                boolean changeFound = false;
                Map<String, Object> modifiedItem = new HashMap<>();
                if (!oldItemDescription.equals(valueObj.getString("itemDescription"))) {
                    modifiedItem.put("itemDescription", oldItemDescription);
                    changeFound = true;
                }
                if (!oldItemComment.equals(valueObj.getString("comments"))) {
                    modifiedItem.put("changeComments", valueObj.getString("comments"));
                    changeFound = true;
                }
                BigDecimal quantityDif = valueObj.getBigDecimal("quantity").subtract(oldQuantity);
                BigDecimal unitPriceDif = valueObj.getBigDecimal("unitPrice").subtract(oldUnitPrice);
                if (quantityDif.compareTo(BigDecimal.ZERO) != 0) {
                    modifiedItem.put("quantity", quantityDif);
                    changeFound = true;
                }
                if (unitPriceDif.compareTo(BigDecimal.ZERO) != 0) {
                    modifiedItem.put("unitPrice", unitPriceDif);
                    changeFound = true;
                }
                if (changeFound) {
                    // found changes to store
                    Map<String, String> itemReasonMap = UtilGenerics.checkMap(changeMap.get("itemReasonMap"));
                    if (UtilValidate.isNotEmpty(itemReasonMap)) {
                        String changeReasonId = itemReasonMap.get(valueObj.getString("orderItemSeqId"));
                        modifiedItem.put("reasonEnumId", changeReasonId);
                    }
                    modifiedItem.put("orderId", valueObj.getString("orderId"));
                    modifiedItem.put("orderItemSeqId", valueObj.getString("orderItemSeqId"));
                    modifiedItem.put("changeTypeEnumId", "ODR_ITM_UPDATE");
                    modifiedItems.add(modifiedItem);
                }
            } else {
                // this is a new item appended to the order
                Map<String, String> itemReasonMap = UtilGenerics.checkMap(changeMap.get("itemReasonMap"));
                Map<String, String> itemCommentMap = UtilGenerics.checkMap(changeMap.get("itemCommentMap"));
                Map<String, Object> appendedItem = new HashMap<>();
                if (UtilValidate.isNotEmpty(itemReasonMap)) {
                    String changeReasonId = itemReasonMap.get("reasonEnumId");
                    appendedItem.put("reasonEnumId", changeReasonId);
                }
                if (UtilValidate.isNotEmpty(itemCommentMap)) {
                    String changeComments = itemCommentMap.get("changeComments");
                    appendedItem.put("changeComments", changeComments);
                }
                appendedItem.put("orderId", valueObj.getString("orderId"));
                appendedItem.put("orderItemSeqId", valueObj.getString("orderItemSeqId"));
                appendedItem.put("quantity", valueObj.getBigDecimal("quantity"));
                appendedItem.put("changeTypeEnumId", "ODR_ITM_APPEND");
                modifiedItems.add(appendedItem);
                newItems.add(appendedItem);
            }
        }
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("To Store Contains: " + toStore, module);
    }
    // remove any order item attributes that were set to empty
    try {
        delegator.removeAll(toRemove);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    // store the new items/adjustments/order item attributes
    try {
        delegator.storeAll(toStore);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    // store the OrderItemChange
    if (UtilValidate.isNotEmpty(modifiedItems)) {
        for (Map<String, Object> modifiendItem : modifiedItems) {
            Map<String, Object> serviceCtx = new HashMap<>();
            serviceCtx.put("orderId", modifiendItem.get("orderId"));
            serviceCtx.put("orderItemSeqId", modifiendItem.get("orderItemSeqId"));
            serviceCtx.put("itemDescription", modifiendItem.get("itemDescription"));
            serviceCtx.put("quantity", modifiendItem.get("quantity"));
            serviceCtx.put("unitPrice", modifiendItem.get("unitPrice"));
            serviceCtx.put("changeTypeEnumId", modifiendItem.get("changeTypeEnumId"));
            serviceCtx.put("reasonEnumId", modifiendItem.get("reasonEnumId"));
            serviceCtx.put("changeComments", modifiendItem.get("changeComments"));
            serviceCtx.put("userLogin", userLogin);
            Map<String, Object> resp = null;
            try {
                resp = dispatcher.runSync("createOrderItemChange", serviceCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                throw new GeneralException(e.getMessage());
            }
            if (ServiceUtil.isError(resp)) {
                throw new GeneralException(ServiceUtil.getErrorMessage(resp));
            }
        }
    }
    // To create record of OrderStatus entity
    if (UtilValidate.isNotEmpty(newItems)) {
        for (Map<String, Object> newItem : newItems) {
            String itemStatusId = delegator.getNextSeqId("OrderStatus");
            GenericValue itemStatus = delegator.makeValue("OrderStatus", UtilMisc.toMap("orderStatusId", itemStatusId));
            itemStatus.put("statusId", "ITEM_CREATED");
            itemStatus.put("orderId", newItem.get("orderId"));
            itemStatus.put("orderItemSeqId", newItem.get("orderItemSeqId"));
            itemStatus.put("statusDatetime", UtilDateTime.nowTimestamp());
            itemStatus.set("statusUserLogin", userLogin.get("userLoginId"));
            delegator.create(itemStatus);
        }
    }
    // make the order item object map & the ship group assoc list
    List<GenericValue> orderItemShipGroupAssoc = new LinkedList<>();
    Map<String, GenericValue> itemValuesBySeqId = new HashMap<>();
    for (GenericValue v : toStore) {
        if ("OrderItem".equals(v.getEntityName())) {
            itemValuesBySeqId.put(v.getString("orderItemSeqId"), v);
        } else if ("OrderItemShipGroupAssoc".equals(v.getEntityName())) {
            orderItemShipGroupAssoc.add(v);
        }
    }
    // reserve the inventory
    String productStoreId = cart.getProductStoreId();
    String orderTypeId = cart.getOrderType();
    List<String> resErrorMessages = new LinkedList<>();
    try {
        Debug.logInfo("Calling reserve inventory...", module);
        reserveInventory(delegator, dispatcher, userLogin, locale, orderItemShipGroupAssoc, dropShipGroupIds, itemValuesBySeqId, orderTypeId, productStoreId, resErrorMessages);
    } catch (GeneralException e) {
        Debug.logError(e, module);
        throw new GeneralException(e.getMessage());
    }
    if (resErrorMessages.size() > 0) {
        throw new GeneralException(ServiceUtil.getErrorMessage(ServiceUtil.returnError(resErrorMessages)));
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with CheckOutHelper

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

the class OrderServices method runSubscriptionAutoReorders.

public static Map<String, Object> runSubscriptionAutoReorders(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");
    int count = 0;
    Map<String, Object> result = null;
    boolean beganTransaction = false;
    List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition("orderId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("productId", EntityOperator.NOT_EQUAL, null));
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, "[Delegator] Could not begin transaction: " + e1.toString(), module);
    }
    try (EntityListIterator eli = EntityQuery.use(delegator).from("Subscription").where(exprs).queryIterator()) {
        if (eli != null) {
            GenericValue subscription;
            while (((subscription = eli.next()) != null)) {
                Calendar endDate = Calendar.getInstance();
                endDate.setTime(UtilDateTime.nowTimestamp());
                // Check if today date + cancel period (if provided) is earlier than the thrudate
                int field = Calendar.MONTH;
                if (subscription.get("canclAutmExtTime") != null && subscription.get("canclAutmExtTimeUomId") != null) {
                    if ("TF_day".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.DAY_OF_YEAR;
                    } else if ("TF_wk".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.WEEK_OF_YEAR;
                    } else if ("TF_mon".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.MONTH;
                    } else if ("TF_yr".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.YEAR;
                    } else {
                        Debug.logWarning("Don't know anything about canclAutmExtTimeUomId [" + subscription.getString("canclAutmExtTimeUomId") + "], defaulting to month", module);
                    }
                    endDate.add(field, Integer.parseInt(subscription.getString("canclAutmExtTime")));
                }
                Calendar endDateSubscription = Calendar.getInstance();
                endDateSubscription.setTime(subscription.getTimestamp("thruDate"));
                if (endDate.before(endDateSubscription)) {
                    // nor expired yet.....
                    continue;
                }
                result = dispatcher.runSync("loadCartFromOrder", UtilMisc.toMap("orderId", subscription.get("orderId"), "userLogin", userLogin));
                if (ServiceUtil.isError(result)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                }
                ShoppingCart cart = (ShoppingCart) result.get("shoppingCart");
                // remove former orderId from cart (would cause duplicate entry).
                // orderId is set by order-creation services (including store-specific prefixes, e.g.)
                cart.setOrderId(null);
                // only keep the orderitem with the related product.
                List<ShoppingCartItem> cartItems = cart.items();
                for (ShoppingCartItem shoppingCartItem : cartItems) {
                    if (!subscription.get("productId").equals(shoppingCartItem.getProductId())) {
                        cart.removeCartItem(shoppingCartItem, dispatcher);
                    }
                }
                CheckOutHelper helper = new CheckOutHelper(dispatcher, delegator, cart);
                // store the order
                Map<String, Object> createResp = helper.createOrder(userLogin);
                if (createResp != null && ServiceUtil.isError(createResp)) {
                    Debug.logError("Cannot create order for shopping list - " + subscription, module);
                } else {
                    String orderId = (String) createResp.get("orderId");
                    // authorize the payments
                    Map<String, Object> payRes = null;
                    try {
                        payRes = helper.processPayment(ProductStoreWorker.getProductStore(cart.getProductStoreId(), delegator), userLogin);
                    } catch (GeneralException e) {
                        Debug.logError(e, module);
                    }
                    if (payRes != null && ServiceUtil.isError(payRes)) {
                        Debug.logError("Payment processing problems with shopping list - " + subscription, module);
                    }
                    // remove the automatic extension flag
                    subscription.put("automaticExtend", "N");
                    subscription.store();
                    // send notification
                    if (orderId != null) {
                        dispatcher.runAsync("sendOrderPayRetryNotification", UtilMisc.toMap("orderId", orderId));
                    }
                    count++;
                }
            }
        }
    } catch (GenericServiceException e) {
        Debug.logError("Could call service to create cart", module);
        return ServiceUtil.returnError(e.toString());
    } catch (CartItemModifyException e) {
        Debug.logError("Could not modify cart: " + e.toString(), module);
        return ServiceUtil.returnError(e.toString());
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error creating subscription auto-reorders", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "[Delegator] Could not rollback transaction: " + e2.toString(), module);
        }
        Debug.logError(e, "Error while creating new shopping list based automatic reorder" + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderShoppingListCreationError", UtilMisc.toMap("errorString", e.toString()), locale));
    } finally {
        try {
            // only commit the transaction if we started one... this will throw an exception if it fails
            TransactionUtil.commit(beganTransaction);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Could not commit transaction for creating new shopping list based automatic reorder", module);
        }
    }
    return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "OrderRunSubscriptionAutoReorders", UtilMisc.toMap("count", count), locale));
}
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) Calendar(com.ibm.icu.util.Calendar) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) 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) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 4 with CheckOutHelper

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

the class OrderServices method checkCreateDropShipPurchaseOrders.

public static Map<String, Object> checkCreateDropShipPurchaseOrders(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    // TODO (use the "system" user)
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String orderId = (String) context.get("orderId");
    Locale locale = (Locale) context.get("locale");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    try {
        // if sales order
        if ("SALES_ORDER".equals(orh.getOrderTypeId())) {
            // get the order's ship groups
            for (GenericValue shipGroup : orh.getOrderItemShipGroups()) {
                if (UtilValidate.isNotEmpty(shipGroup.getString("supplierPartyId"))) {
                    // This ship group is a drop shipment: we create a purchase order for it
                    String supplierPartyId = shipGroup.getString("supplierPartyId");
                    // Set supplier preferred currency for drop-ship (PO) order to support multi currency
                    GenericValue supplierParty = EntityQuery.use(delegator).from("Party").where("partyId", supplierPartyId).queryOne();
                    String currencyUomId = supplierParty.getString("preferredCurrencyUomId");
                    // If supplier currency not found then set currency of sales order
                    if (UtilValidate.isEmpty(currencyUomId)) {
                        currencyUomId = orh.getCurrency();
                    }
                    // create the cart
                    ShoppingCart cart = new ShoppingCart(delegator, orh.getProductStoreId(), null, currencyUomId);
                    cart.setOrderType("PURCHASE_ORDER");
                    // Company
                    cart.setBillToCustomerPartyId(cart.getBillFromVendorPartyId());
                    cart.setBillFromVendorPartyId(supplierPartyId);
                    cart.setOrderPartyId(supplierPartyId);
                    cart.setAgreementId(shipGroup.getString("supplierAgreementId"));
                    // Get the items associated to it and create po
                    List<GenericValue> items = orh.getValidOrderItems(shipGroup.getString("shipGroupSeqId"));
                    if (UtilValidate.isNotEmpty(items)) {
                        for (GenericValue item : items) {
                            try {
                                int itemIndex = cart.addOrIncreaseItem(item.getString("productId"), // amount
                                null, item.getBigDecimal("quantity"), // reserv
                                null, // reserv
                                null, // reserv
                                null, item.getTimestamp("shipBeforeDate"), item.getTimestamp("shipAfterDate"), null, null, null, null, null, null, null, dispatcher);
                                ShoppingCartItem sci = cart.findCartItem(itemIndex);
                                sci.setAssociatedOrderId(orderId);
                                sci.setAssociatedOrderItemSeqId(item.getString("orderItemSeqId"));
                                sci.setOrderItemAssocTypeId("DROP_SHIPMENT");
                            } catch (CartItemModifyException | ItemNotFoundException e) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderOrderCreatingDropShipmentsError", UtilMisc.toMap("orderId", orderId, "errorString", e.getMessage()), locale));
                            }
                        }
                    }
                    // If there are indeed items to drop ship, then create the purchase order
                    if (UtilValidate.isNotEmpty(cart.items())) {
                        // resolve supplier promotion
                        ProductPromoWorker.doPromotions(cart, dispatcher);
                        // set checkout options
                        cart.setDefaultCheckoutOptions(dispatcher);
                        // the shipping address is the one of the customer
                        cart.setAllShippingContactMechId(shipGroup.getString("contactMechId"));
                        // associate ship groups of sales and purchase orders
                        ShoppingCart.CartShipInfo cartShipInfo = cart.getShipGroups().get(0);
                        cartShipInfo.setAssociatedShipGroupSeqId(shipGroup.getString("shipGroupSeqId"));
                        // create the order
                        CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
                        coh.createOrder(userLogin);
                    } else {
                        // if there are no items to drop ship, then clear out the supplier partyId
                        Debug.logWarning("No drop ship items found for order [" + shipGroup.getString("orderId") + "] and ship group [" + shipGroup.getString("shipGroupSeqId") + "] and supplier party [" + shipGroup.getString("supplierPartyId") + "].  Supplier party information will be cleared for this ship group", module);
                        shipGroup.set("supplierPartyId", null);
                        shipGroup.store();
                    }
                }
            }
        }
    } catch (GenericEntityException exc) {
        // TODO: imporve error handling
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderOrderCreatingDropShipmentsError", UtilMisc.toMap("orderId", orderId, "errorString", exc.getMessage()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) 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) ItemNotFoundException(org.apache.ofbiz.order.shoppingcart.ItemNotFoundException)

Example 5 with CheckOutHelper

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

the class OrderTestServices method createTestSalesOrderSingle.

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

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)9 CheckOutHelper (org.apache.ofbiz.order.shoppingcart.CheckOutHelper)9 Delegator (org.apache.ofbiz.entity.Delegator)8 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)8 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)8 Locale (java.util.Locale)6 GeneralException (org.apache.ofbiz.base.util.GeneralException)6 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)6 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)6 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)4 CartItemModifyException (org.apache.ofbiz.order.shoppingcart.CartItemModifyException)4 BigDecimal (java.math.BigDecimal)3 HashMap (java.util.HashMap)3 ShoppingCartItem (org.apache.ofbiz.order.shoppingcart.ShoppingCartItem)3 NVPEncoder (com.paypal.sdk.core.nvp.NVPEncoder)2 PayPalException (com.paypal.sdk.exceptions.PayPalException)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 WeakHashMap (java.util.WeakHashMap)2 Transaction (javax.transaction.Transaction)2