Search in sources :

Example 16 with OrderReadHelper

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

the class RequirementServices method updateRequirementsToOrdered.

public static Map<String, Object> updateRequirementsToOrdered(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String orderId = (String) context.get("orderId");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    try {
        for (GenericValue orderItem : orh.getOrderItems()) {
            GenericValue orderRequirementCommitment = EntityQuery.use(delegator).from("OrderRequirementCommitment").where(UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.getString("orderItemSeqId"))).queryFirst();
            if (orderRequirementCommitment != null) {
                String requirementId = orderRequirementCommitment.getString("requirementId");
                /* Change status of requirement to ordered */
                Map<String, Object> inputMap = UtilMisc.<String, Object>toMap("userLogin", userLogin, "requirementId", requirementId, "statusId", "REQ_ORDERED", "quantity", orderItem.getBigDecimal("quantity"));
                // TODO: check service result for an error return
                Map<String, Object> results = dispatcher.runSync("updateRequirement", inputMap);
                if (ServiceUtil.isError(results)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results));
                }
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper)

Example 17 with OrderReadHelper

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

the class BOMServices method createShipmentPackages.

// ---------------------------------------------
// Service for the Product (Shipment) component
// 
public static Map<String, Object> createShipmentPackages(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = new HashMap<String, Object>();
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String shipmentId = (String) context.get("shipmentId");
    try {
        List<GenericValue> packages = EntityQuery.use(delegator).from("ShipmentPackage").where("shipmentId", shipmentId).queryList();
        if (UtilValidate.isNotEmpty(packages)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingBomPackageAlreadyFound", locale));
        }
    } catch (GenericEntityException gee) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingBomErrorLoadingShipmentPackages", locale));
    }
    // ShipmentItems are loaded
    List<GenericValue> shipmentItems = null;
    try {
        shipmentItems = EntityQuery.use(delegator).from("ShipmentItem").where("shipmentId", shipmentId).queryList();
    } catch (GenericEntityException gee) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingBomErrorLoadingShipmentItems", locale));
    }
    Map<String, Object> orderReadHelpers = new HashMap<String, Object>();
    Map<String, Object> partyOrderShipments = new HashMap<String, Object>();
    for (GenericValue shipmentItem : shipmentItems) {
        // Get the OrderShipments
        GenericValue orderShipment = null;
        try {
            orderShipment = EntityQuery.use(delegator).from("OrderShipment").where("shipmentId", shipmentId, "shipmentItemSeqId", shipmentItem.get("shipmentItemSeqId")).queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
        }
        if (orderShipment != null && !orderReadHelpers.containsKey(orderShipment.getString("orderId"))) {
            orderReadHelpers.put(orderShipment.getString("orderId"), new OrderReadHelper(delegator, orderShipment.getString("orderId")));
        }
        OrderReadHelper orderReadHelper = (OrderReadHelper) orderReadHelpers.get(orderShipment.getString("orderId"));
        if (orderReadHelper != null) {
            Map<String, Object> orderShipmentReadMap = UtilMisc.toMap("orderShipment", orderShipment, "orderReadHelper", orderReadHelper);
            // FIXME: is it the customer?
            String partyId = (orderReadHelper.getPlacingParty() != null ? orderReadHelper.getPlacingParty().getString("partyId") : null);
            if (partyId != null) {
                if (!partyOrderShipments.containsKey(partyId)) {
                    List<Map<String, Object>> orderShipmentReadMapList = new LinkedList<Map<String, Object>>();
                    partyOrderShipments.put(partyId, orderShipmentReadMapList);
                }
                List<Map<String, Object>> orderShipmentReadMapList = UtilGenerics.checkList(partyOrderShipments.get(partyId));
                orderShipmentReadMapList.add(orderShipmentReadMap);
            }
        }
    }
    // (search for components that needs to be packaged).
    for (Map.Entry<String, Object> partyOrderShipment : partyOrderShipments.entrySet()) {
        List<Map<String, Object>> orderShipmentReadMapList = UtilGenerics.checkList(partyOrderShipment.getValue());
        for (int i = 0; i < orderShipmentReadMapList.size(); i++) {
            Map<String, Object> orderShipmentReadMap = UtilGenerics.checkMap(orderShipmentReadMapList.get(i));
            GenericValue orderShipment = (GenericValue) orderShipmentReadMap.get("orderShipment");
            OrderReadHelper orderReadHelper = (OrderReadHelper) orderShipmentReadMap.get("orderReadHelper");
            GenericValue orderItem = orderReadHelper.getOrderItem(orderShipment.getString("orderItemSeqId"));
            // getProductsInPackages
            Map<String, Object> serviceContext = new HashMap<String, Object>();
            serviceContext.put("productId", orderItem.getString("productId"));
            serviceContext.put("quantity", orderShipment.getBigDecimal("quantity"));
            Map<String, Object> serviceResult = null;
            try {
                serviceResult = dispatcher.runSync("getProductsInPackages", serviceContext);
                if (ServiceUtil.isError(serviceResult)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                }
            } catch (GenericServiceException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
            }
            List<BOMNode> productsInPackages = UtilGenerics.checkList(serviceResult.get("productsInPackages"));
            if (productsInPackages.size() == 1) {
                BOMNode root = productsInPackages.get(0);
                String rootProductId = (root.getSubstitutedNode() != null ? root.getSubstitutedNode().getProduct().getString("productId") : root.getProduct().getString("productId"));
                if (orderItem.getString("productId").equals(rootProductId)) {
                    productsInPackages = null;
                }
            }
            if (productsInPackages != null && productsInPackages.size() == 0) {
                productsInPackages = null;
            }
            if (UtilValidate.isNotEmpty(productsInPackages)) {
                orderShipmentReadMap.put("productsInPackages", productsInPackages);
            }
        }
    }
    // Group together products and components
    // of the same box type.
    Map<String, GenericValue> boxTypes = new HashMap<String, GenericValue>();
    for (Map.Entry<String, Object> partyOrderShipment : partyOrderShipments.entrySet()) {
        Map<String, List<Map<String, Object>>> boxTypeContent = new HashMap<String, List<Map<String, Object>>>();
        List<Map<String, Object>> orderShipmentReadMapList = UtilGenerics.checkList(partyOrderShipment.getValue());
        for (int i = 0; i < orderShipmentReadMapList.size(); i++) {
            Map<String, Object> orderShipmentReadMap = UtilGenerics.checkMap(orderShipmentReadMapList.get(i));
            GenericValue orderShipment = (GenericValue) orderShipmentReadMap.get("orderShipment");
            OrderReadHelper orderReadHelper = (OrderReadHelper) orderShipmentReadMap.get("orderReadHelper");
            List<BOMNode> productsInPackages = UtilGenerics.checkList(orderShipmentReadMap.get("productsInPackages"));
            if (productsInPackages != null) {
                // this is a multi package shipment item
                for (int j = 0; j < productsInPackages.size(); j++) {
                    BOMNode component = productsInPackages.get(j);
                    Map<String, Object> boxTypeContentMap = new HashMap<String, Object>();
                    boxTypeContentMap.put("content", orderShipmentReadMap);
                    boxTypeContentMap.put("componentIndex", Integer.valueOf(j));
                    GenericValue product = component.getProduct();
                    String boxTypeId = product.getString("shipmentBoxTypeId");
                    if (boxTypeId != null) {
                        if (!boxTypes.containsKey(boxTypeId)) {
                            GenericValue boxType = null;
                            try {
                                boxType = EntityQuery.use(delegator).from("ShipmentBoxType").where("shipmentBoxTypeId", boxTypeId).queryOne();
                            } catch (GenericEntityException e) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                            }
                            boxTypes.put(boxTypeId, boxType);
                            List<Map<String, Object>> box = new LinkedList<Map<String, Object>>();
                            boxTypeContent.put(boxTypeId, box);
                        }
                        List<Map<String, Object>> boxTypeContentList = UtilGenerics.checkList(boxTypeContent.get(boxTypeId));
                        boxTypeContentList.add(boxTypeContentMap);
                    }
                }
            } else {
                // no subcomponents, the product has its own package:
                // this is a single package shipment item
                Map<String, Object> boxTypeContentMap = new HashMap<String, Object>();
                boxTypeContentMap.put("content", orderShipmentReadMap);
                GenericValue orderItem = orderReadHelper.getOrderItem(orderShipment.getString("orderItemSeqId"));
                GenericValue product = null;
                try {
                    product = orderItem.getRelatedOne("Product", false);
                } catch (GenericEntityException e) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                }
                String boxTypeId = product.getString("shipmentBoxTypeId");
                if (boxTypeId != null) {
                    if (!boxTypes.containsKey(boxTypeId)) {
                        GenericValue boxType = null;
                        try {
                            boxType = EntityQuery.use(delegator).from("ShipmentBoxType").where("shipmentBoxTypeId", boxTypeId).queryOne();
                        } catch (GenericEntityException e) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                        }
                        boxTypes.put(boxTypeId, boxType);
                        List<Map<String, Object>> box = new LinkedList<Map<String, Object>>();
                        boxTypeContent.put(boxTypeId, box);
                    }
                    List<Map<String, Object>> boxTypeContentList = UtilGenerics.checkList(boxTypeContent.get(boxTypeId));
                    boxTypeContentList.add(boxTypeContentMap);
                }
            }
        }
        // The packages and package contents are created.
        for (Map.Entry<String, List<Map<String, Object>>> boxTypeContentEntry : boxTypeContent.entrySet()) {
            String boxTypeId = boxTypeContentEntry.getKey();
            List<Map<String, Object>> contentList = UtilGenerics.checkList(boxTypeContentEntry.getValue());
            GenericValue boxType = boxTypes.get(boxTypeId);
            BigDecimal boxWidth = boxType.getBigDecimal("boxLength");
            BigDecimal totalWidth = BigDecimal.ZERO;
            if (boxWidth == null) {
                boxWidth = BigDecimal.ZERO;
            }
            String shipmentPackageSeqId = null;
            for (int i = 0; i < contentList.size(); i++) {
                Map<String, Object> contentMap = UtilGenerics.checkMap(contentList.get(i));
                Map<String, Object> content = UtilGenerics.checkMap(contentMap.get("content"));
                OrderReadHelper orderReadHelper = (OrderReadHelper) content.get("orderReadHelper");
                List<BOMNode> productsInPackages = UtilGenerics.checkList(content.get("productsInPackages"));
                GenericValue orderShipment = (GenericValue) content.get("orderShipment");
                GenericValue product = null;
                BigDecimal quantity = BigDecimal.ZERO;
                boolean subProduct = contentMap.containsKey("componentIndex");
                if (subProduct) {
                    // multi package
                    Integer index = (Integer) contentMap.get("componentIndex");
                    BOMNode component = productsInPackages.get(index.intValue());
                    product = component.getProduct();
                    quantity = component.getQuantity();
                } else {
                    // single package
                    GenericValue orderItem = orderReadHelper.getOrderItem(orderShipment.getString("orderItemSeqId"));
                    try {
                        product = orderItem.getRelatedOne("Product", false);
                    } catch (GenericEntityException e) {
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                    }
                    quantity = orderShipment.getBigDecimal("quantity");
                }
                BigDecimal productDepth = product.getBigDecimal("shippingDepth");
                if (productDepth == null) {
                    productDepth = product.getBigDecimal("productDepth");
                }
                if (productDepth == null) {
                    productDepth = BigDecimal.ONE;
                }
                BigDecimal firstMaxNumOfProducts = boxWidth.subtract(totalWidth).divide(productDepth, 0, RoundingMode.FLOOR);
                if (firstMaxNumOfProducts.compareTo(BigDecimal.ZERO) == 0)
                    firstMaxNumOfProducts = BigDecimal.ONE;
                // 
                BigDecimal maxNumOfProducts = boxWidth.divide(productDepth, 0, RoundingMode.FLOOR);
                if (maxNumOfProducts.compareTo(BigDecimal.ZERO) == 0)
                    maxNumOfProducts = BigDecimal.ONE;
                BigDecimal remQuantity = quantity;
                boolean isFirst = true;
                while (remQuantity.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal maxQuantity = BigDecimal.ZERO;
                    if (isFirst) {
                        maxQuantity = firstMaxNumOfProducts;
                        isFirst = false;
                    } else {
                        maxQuantity = maxNumOfProducts;
                    }
                    BigDecimal qty = (remQuantity.compareTo(maxQuantity) < 0 ? remQuantity : maxQuantity);
                    // If needed, create the package
                    if (shipmentPackageSeqId == null) {
                        try {
                            Map<String, Object> serviceResult = dispatcher.runSync("createShipmentPackage", UtilMisc.<String, Object>toMap("shipmentId", orderShipment.getString("shipmentId"), "shipmentBoxTypeId", boxTypeId, "userLogin", userLogin));
                            if (ServiceUtil.isError(serviceResult)) {
                                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                            }
                            shipmentPackageSeqId = (String) serviceResult.get("shipmentPackageSeqId");
                        } catch (GenericServiceException e) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                        }
                        totalWidth = BigDecimal.ZERO;
                    }
                    try {
                        Map<String, Object> inputMap = null;
                        if (subProduct) {
                            inputMap = UtilMisc.toMap("shipmentId", orderShipment.getString("shipmentId"), "shipmentPackageSeqId", shipmentPackageSeqId, "shipmentItemSeqId", orderShipment.getString("shipmentItemSeqId"), "subProductId", product.getString("productId"), "userLogin", userLogin, "subProductQuantity", qty);
                        } else {
                            inputMap = UtilMisc.toMap("shipmentId", orderShipment.getString("shipmentId"), "shipmentPackageSeqId", shipmentPackageSeqId, "shipmentItemSeqId", orderShipment.getString("shipmentItemSeqId"), "userLogin", userLogin, "quantity", qty);
                        }
                        Map<String, Object> serviceResult = dispatcher.runSync("createShipmentPackageContent", inputMap);
                        if (ServiceUtil.isError(serviceResult)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                        }
                    } catch (GenericServiceException e) {
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingPackageConfiguratorError", locale));
                    }
                    totalWidth = totalWidth.add(qty.multiply(productDepth));
                    if (qty.compareTo(maxQuantity) == 0)
                        shipmentPackageSeqId = null;
                    remQuantity = remQuantity.subtract(qty);
                }
            }
        }
    }
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) List(java.util.List) LinkedList(java.util.LinkedList) GenericValue(org.apache.ofbiz.entity.GenericValue) LinkedList(java.util.LinkedList) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 18 with OrderReadHelper

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

Example 19 with OrderReadHelper

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

the class ShoppingListServices method makeListFromOrder.

public static Map<String, Object> makeListFromOrder(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    String shoppingListTypeId = (String) context.get("shoppingListTypeId");
    String shoppingListId = (String) context.get("shoppingListId");
    String orderId = (String) context.get("orderId");
    String partyId = (String) context.get("partyId");
    Timestamp startDate = (Timestamp) context.get("startDateTime");
    Timestamp endDate = (Timestamp) context.get("endDateTime");
    Integer frequency = (Integer) context.get("frequency");
    Integer interval = (Integer) context.get("intervalNumber");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        GenericValue orderHeader = null;
        orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
        if (orderHeader == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderUnableToLocateOrder", UtilMisc.toMap("orderId", orderId), locale));
        }
        String productStoreId = orderHeader.getString("productStoreId");
        if (UtilValidate.isEmpty(shoppingListId)) {
            // create a new shopping list
            if (partyId == null) {
                partyId = userLogin.getString("partyId");
            }
            Map<String, Object> serviceCtx = UtilMisc.<String, Object>toMap("userLogin", userLogin, "partyId", partyId, "productStoreId", productStoreId, "listName", "List Created From Order #" + orderId);
            if (UtilValidate.isNotEmpty(shoppingListTypeId)) {
                serviceCtx.put("shoppingListTypeId", shoppingListTypeId);
            }
            Map<String, Object> newListResult = null;
            try {
                newListResult = dispatcher.runSync("createShoppingList", serviceCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problems creating new ShoppingList", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderUnableToCreateNewShoppingList", locale));
            }
            // check for errors
            if (ServiceUtil.isError(newListResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(newListResult));
            }
            // get the new list id
            if (newListResult != null) {
                shoppingListId = (String) newListResult.get("shoppingListId");
            }
        }
        GenericValue shoppingList = null;
        shoppingList = EntityQuery.use(delegator).from("ShoppingList").where("shoppingListId", shoppingListId).queryOne();
        if (shoppingList == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderNoShoppingListAvailable", locale));
        }
        shoppingListTypeId = shoppingList.getString("shoppingListTypeId");
        OrderReadHelper orh;
        try {
            orh = new OrderReadHelper(orderHeader);
        } catch (IllegalArgumentException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderUnableToLoadOrderReadHelper", UtilMisc.toMap("orderId", orderId), locale));
        }
        List<GenericValue> orderItems = orh.getOrderItems();
        for (GenericValue orderItem : orderItems) {
            String productId = orderItem.getString("productId");
            if (UtilValidate.isNotEmpty(productId)) {
                Map<String, Object> ctx = UtilMisc.<String, Object>toMap("userLogin", userLogin, "shoppingListId", shoppingListId, "productId", orderItem.get("productId"), "quantity", orderItem.get("quantity"));
                if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", ProductWorker.getProductTypeId(delegator, productId), "parentTypeId", "AGGREGATED")) {
                    try {
                        GenericValue instanceProduct = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                        String configId = instanceProduct.getString("configId");
                        ctx.put("configId", configId);
                        String aggregatedProductId = ProductWorker.getInstanceAggregatedId(delegator, productId);
                        // override the instance productId with aggregated productId
                        ctx.put("productId", aggregatedProductId);
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                }
                Map<String, Object> serviceResult = null;
                try {
                    serviceResult = dispatcher.runSync("createShoppingListItem", ctx);
                } catch (GenericServiceException e) {
                    Debug.logError(e, module);
                }
                if (serviceResult == null || ServiceUtil.isError(serviceResult)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderUnableToAddItemToShoppingList", UtilMisc.toMap("shoppingListId", shoppingListId), locale));
                }
            }
        }
        if ("SLT_AUTO_REODR".equals(shoppingListTypeId)) {
            GenericValue paymentPref = EntityUtil.getFirst(orh.getPaymentPreferences());
            GenericValue shipGroup = EntityUtil.getFirst(orh.getOrderItemShipGroups());
            Map<String, Object> slCtx = new HashMap<>();
            slCtx.put("shipmentMethodTypeId", shipGroup.get("shipmentMethodTypeId"));
            slCtx.put("carrierRoleTypeId", shipGroup.get("carrierRoleTypeId"));
            slCtx.put("carrierPartyId", shipGroup.get("carrierPartyId"));
            slCtx.put("contactMechId", shipGroup.get("contactMechId"));
            slCtx.put("paymentMethodId", paymentPref.get("paymentMethodId"));
            slCtx.put("currencyUom", orh.getCurrency());
            slCtx.put("startDateTime", startDate);
            slCtx.put("endDateTime", endDate);
            slCtx.put("frequency", frequency);
            slCtx.put("intervalNumber", interval);
            slCtx.put("isActive", "Y");
            slCtx.put("shoppingListId", shoppingListId);
            slCtx.put("userLogin", userLogin);
            Map<String, Object> slUpResp = null;
            try {
                slUpResp = dispatcher.runSync("updateShoppingList", slCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }
            if (slUpResp == null || ServiceUtil.isError(slUpResp)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderUnableToUpdateShoppingListInformation", UtilMisc.toMap("shoppingListId", shoppingListId), locale));
            }
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.put("shoppingListId", shoppingListId);
        return result;
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error making shopping list from order", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "[Delegator] Could not rollback transaction: " + e2.toString(), module);
        }
        String errMsg = UtilProperties.getMessage(resource_error, "OrderErrorWhileCreatingNewShoppingListBasedOnOrder", UtilMisc.toMap("errorString", e.toString()), locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    } 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 on order", module);
        }
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Timestamp(java.sql.Timestamp) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 20 with OrderReadHelper

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

the class PayPalServices method doAuthorization.

public static Map<String, Object> doAuthorization(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE);
    Locale locale = (Locale) context.get("locale");
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoAuthorization");
    encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId"));
    encoder.add("AMT", processAmount.setScale(2, RoundingMode.HALF_UP).toPlainString());
    encoder.add("TRANSACTIONENTITY", "Order");
    String currency = (String) context.get("currency");
    if (currency == null) {
        currency = orh.getCurrency();
    }
    encoder.add("CURRENCYCODE", currency);
    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("authResult", false);
        result.put("authRefNum", "N/A");
        result.put("processAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("authCode", error.getKey());
            result.put("authMessage", error.getValue());
        } else {
            result.put("authMessage", "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("authResult", true);
        result.put("processAmount", new BigDecimal(decoder.get("AMT")));
        result.put("authRefNum", decoder.get("TRANSACTIONID"));
    }
    // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) PayPalException(com.paypal.sdk.exceptions.PayPalException) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) Delegator(org.apache.ofbiz.entity.Delegator) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)32 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)32 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)30 Delegator (org.apache.ofbiz.entity.Delegator)28 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)28 BigDecimal (java.math.BigDecimal)24 Locale (java.util.Locale)24 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)24 HashMap (java.util.HashMap)22 Timestamp (java.sql.Timestamp)7 Map (java.util.Map)5 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 LinkedList (java.util.LinkedList)4 ModelService (org.apache.ofbiz.service.ModelService)3 NVPDecoder (com.paypal.sdk.core.nvp.NVPDecoder)2 NVPEncoder (com.paypal.sdk.core.nvp.NVPEncoder)2 PayPalException (com.paypal.sdk.exceptions.PayPalException)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 List (java.util.List)2