Search in sources :

Example 56 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class ContentWorker method getContentAssocsWithId.

public static List<GenericValue> getContentAssocsWithId(Delegator delegator, String contentId, Timestamp fromDate, Timestamp thruDate, String direction, List<String> assocTypes) throws GenericEntityException {
    List<EntityCondition> exprList = new LinkedList<EntityCondition>();
    EntityExpr joinExpr = null;
    if (direction != null && "From".equalsIgnoreCase(direction)) {
        joinExpr = EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId);
    } else {
        joinExpr = EntityCondition.makeCondition("contentId", EntityOperator.EQUALS, contentId);
    }
    exprList.add(joinExpr);
    if (UtilValidate.isNotEmpty(assocTypes)) {
        exprList.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, assocTypes));
    }
    if (fromDate != null) {
        EntityExpr fromExpr = EntityCondition.makeCondition("fromDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate);
        exprList.add(fromExpr);
    }
    if (thruDate != null) {
        List<EntityExpr> thruList = new LinkedList<EntityExpr>();
        EntityExpr thruExpr = EntityCondition.makeCondition("thruDate", EntityOperator.LESS_THAN, thruDate);
        thruList.add(thruExpr);
        EntityExpr thruExpr2 = EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null);
        thruList.add(thruExpr2);
        EntityConditionList<EntityExpr> thruExprList = EntityCondition.makeCondition(thruList, EntityOperator.OR);
        exprList.add(thruExprList);
    } else if (fromDate != null) {
        List<EntityExpr> thruList = new LinkedList<EntityExpr>();
        EntityExpr thruExpr = EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN, fromDate);
        thruList.add(thruExpr);
        EntityExpr thruExpr2 = EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null);
        thruList.add(thruExpr2);
        EntityConditionList<EntityExpr> thruExprList = EntityCondition.makeCondition(thruList, EntityOperator.OR);
        exprList.add(thruExprList);
    } else {
        EntityExpr thruExpr2 = EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null);
        exprList.add(thruExpr2);
    }
    return EntityQuery.use(delegator).from("ContentAssoc").where(exprList).orderBy("-fromDate").queryList();
}
Also used : EntityConditionList(org.apache.ofbiz.entity.condition.EntityConditionList) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityConditionList(org.apache.ofbiz.entity.condition.EntityConditionList) LinkedList(java.util.LinkedList) List(java.util.List) LinkedList(java.util.LinkedList) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 57 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class ShoppingCartEvents method addToCart.

/**
 * Event to add an item to the shopping cart.
 */
public static String addToCart(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ShoppingCart cart = getCartObject(request);
    ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
    String controlDirective = null;
    Map<String, Object> result = null;
    String productId = null;
    String parentProductId = null;
    String itemType = null;
    String itemDescription = null;
    String productCategoryId = null;
    String priceStr = null;
    BigDecimal price = null;
    String quantityStr = null;
    BigDecimal quantity = BigDecimal.ZERO;
    String reservStartStr = null;
    String reservEndStr = null;
    Timestamp reservStart = null;
    Timestamp reservEnd = null;
    String reservLengthStr = null;
    BigDecimal reservLength = null;
    String reservPersonsStr = null;
    BigDecimal reservPersons = null;
    String accommodationMapId = null;
    String accommodationSpotId = null;
    String shipBeforeDateStr = null;
    String shipAfterDateStr = null;
    Timestamp shipBeforeDate = null;
    Timestamp shipAfterDate = null;
    String numberOfDay = null;
    // not used right now: Map attributes = null;
    String catalogId = CatalogWorker.getCurrentCatalogId(request);
    Locale locale = UtilHttp.getLocale(request);
    // Get the parameters as a MAP, remove the productId and quantity params.
    Map<String, Object> paramMap = UtilHttp.getCombinedMap(request);
    String itemGroupNumber = (String) paramMap.get("itemGroupNumber");
    // Get shoppingList info if passed
    String shoppingListId = (String) paramMap.get("shoppingListId");
    String shoppingListItemSeqId = (String) paramMap.get("shoppingListItemSeqId");
    if (paramMap.containsKey("ADD_PRODUCT_ID")) {
        productId = (String) paramMap.remove("ADD_PRODUCT_ID");
    } else if (paramMap.containsKey("add_product_id")) {
        Object object = paramMap.remove("add_product_id");
        try {
            productId = (String) object;
        } catch (ClassCastException e) {
            List<String> productList = UtilGenerics.checkList(object);
            productId = productList.get(0);
        }
    }
    if (paramMap.containsKey("PRODUCT_ID")) {
        parentProductId = (String) paramMap.remove("PRODUCT_ID");
    } else if (paramMap.containsKey("product_id")) {
        parentProductId = (String) paramMap.remove("product_id");
    }
    Debug.logInfo("adding item product " + productId, module);
    Debug.logInfo("adding item parent product " + parentProductId, module);
    if (paramMap.containsKey("ADD_CATEGORY_ID")) {
        productCategoryId = (String) paramMap.remove("ADD_CATEGORY_ID");
    } else if (paramMap.containsKey("add_category_id")) {
        productCategoryId = (String) paramMap.remove("add_category_id");
    }
    if (productCategoryId != null && productCategoryId.length() == 0) {
        productCategoryId = null;
    }
    if (paramMap.containsKey("ADD_ITEM_TYPE")) {
        itemType = (String) paramMap.remove("ADD_ITEM_TYPE");
    } else if (paramMap.containsKey("add_item_type")) {
        itemType = (String) paramMap.remove("add_item_type");
    }
    if (UtilValidate.isEmpty(productId)) {
        // before returning error; check make sure we aren't adding a special item type
        if (UtilValidate.isEmpty(itemType)) {
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.noProductInfoPassed", locale));
            // not critical return to same page
            return "success";
        }
    } else {
        try {
            String pId = ProductWorker.findProductId(delegator, productId);
            if (pId != null) {
                productId = pId;
            }
        } catch (Throwable e) {
            Debug.logWarning(e, module);
        }
    }
    // check for an itemDescription
    if (paramMap.containsKey("ADD_ITEM_DESCRIPTION")) {
        itemDescription = (String) paramMap.remove("ADD_ITEM_DESCRIPTION");
    } else if (paramMap.containsKey("add_item_description")) {
        itemDescription = (String) paramMap.remove("add_item_description");
    }
    if (itemDescription != null && itemDescription.length() == 0) {
        itemDescription = null;
    }
    // Get the ProductConfigWrapper (it's not null only for configurable items)
    ProductConfigWrapper configWrapper = null;
    configWrapper = ProductConfigWorker.getProductConfigWrapper(productId, cart.getCurrency(), request);
    if (configWrapper != null) {
        if (paramMap.containsKey("configId")) {
            try {
                configWrapper.loadConfig(delegator, (String) paramMap.remove("configId"));
            } catch (Exception e) {
                Debug.logWarning(e, "Could not load configuration", module);
            }
        } else {
            // The choices selected by the user are taken from request and set in the wrapper
            ProductConfigWorker.fillProductConfigWrapper(configWrapper, request);
        }
        if (!configWrapper.isCompleted()) {
            // The configuration is not valid
            request.setAttribute("product_id", productId);
            request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.configureProductBeforeAddingToCart", locale));
            return "product";
        }
        // load the Config Id
        ProductConfigWorker.storeProductConfigWrapper(configWrapper, delegator);
    }
    // Check for virtual products
    if (ProductWorker.isVirtual(delegator, productId)) {
        if ("VV_FEATURETREE".equals(ProductWorker.getProductVirtualVariantMethod(delegator, productId))) {
            // get the selected features.
            List<String> selectedFeatures = new LinkedList<>();
            Enumeration<String> paramNames = UtilGenerics.cast(request.getParameterNames());
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                if (paramName.startsWith("FT")) {
                    selectedFeatures.add(request.getParameterValues(paramName)[0]);
                }
            }
            // check if features are selected
            if (UtilValidate.isEmpty(selectedFeatures)) {
                request.setAttribute("paramMap", paramMap);
                request.setAttribute("product_id", productId);
                request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
                return "product";
            }
            String variantProductId = ProductWorker.getVariantFromFeatureTree(productId, selectedFeatures, delegator);
            if (UtilValidate.isNotEmpty(variantProductId)) {
                productId = variantProductId;
            } else {
                request.setAttribute("paramMap", paramMap);
                request.setAttribute("product_id", productId);
                request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.incompatibilityVariantFeature", locale));
                return "product";
            }
        } else {
            request.setAttribute("paramMap", paramMap);
            request.setAttribute("product_id", productId);
            request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
            return "product";
        }
    }
    // get the override price
    if (paramMap.containsKey("PRICE")) {
        priceStr = (String) paramMap.remove("PRICE");
    } else if (paramMap.containsKey("price")) {
        priceStr = (String) paramMap.remove("price");
    }
    if (priceStr == null) {
        // default price is 0
        priceStr = "0";
    }
    if ("ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
        if (paramMap.containsKey("numberOfDay")) {
            numberOfDay = (String) paramMap.remove("numberOfDay");
            reservStart = UtilDateTime.addDaysToTimestamp(UtilDateTime.nowTimestamp(), 1);
            reservEnd = UtilDateTime.addDaysToTimestamp(reservStart, Integer.parseInt(numberOfDay));
        }
    }
    // get the renting data
    if ("ASSET_USAGE".equals(ProductWorker.getProductTypeId(delegator, productId)) || "ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
        if (paramMap.containsKey("reservStart")) {
            reservStartStr = (String) paramMap.remove("reservStart");
            if (reservStartStr.length() == 10) {
                // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
                reservStartStr += " 00:00:00.000000000";
            }
            if (reservStartStr.length() > 0) {
                try {
                    reservStart = java.sql.Timestamp.valueOf(reservStartStr);
                } catch (Exception e) {
                    Debug.logWarning(e, "Problems parsing Reservation start string: " + reservStartStr, module);
                    reservStart = null;
                    request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.rental.startDate", locale));
                    return "error";
                }
            } else {
                reservStart = null;
            }
        }
        if (paramMap.containsKey("reservEnd")) {
            reservEndStr = (String) paramMap.remove("reservEnd");
            if (reservEndStr.length() == 10) {
                // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
                reservEndStr += " 00:00:00.000000000";
            }
            if (reservEndStr.length() > 0) {
                try {
                    reservEnd = java.sql.Timestamp.valueOf(reservEndStr);
                } catch (Exception e) {
                    Debug.logWarning(e, "Problems parsing Reservation end string: " + reservEndStr, module);
                    reservEnd = null;
                    request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.rental.endDate", locale));
                    return "error";
                }
            } else {
                reservEnd = null;
            }
        }
        if (reservStart != null && reservEnd != null) {
            reservLength = new BigDecimal(UtilDateTime.getInterval(reservStart, reservEnd)).divide(new BigDecimal("86400000"), generalRounding);
        }
        if (reservStart != null && paramMap.containsKey("reservLength")) {
            reservLengthStr = (String) paramMap.remove("reservLength");
            // parse the reservation Length
            try {
                reservLength = (BigDecimal) ObjectType.simpleTypeConvert(reservLengthStr, "BigDecimal", null, locale);
            } catch (Exception e) {
                Debug.logWarning(e, "Problems parsing reservation length string: " + reservLengthStr, module);
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderReservationLengthShouldBeAPositiveNumber", locale));
                return "error";
            }
        }
        if (reservStart != null && paramMap.containsKey("reservPersons")) {
            reservPersonsStr = (String) paramMap.remove("reservPersons");
            // parse the number of persons
            try {
                reservPersons = (BigDecimal) ObjectType.simpleTypeConvert(reservPersonsStr, "BigDecimal", null, locale);
            } catch (Exception e) {
                Debug.logWarning(e, "Problems parsing reservation number of persons string: " + reservPersonsStr, module);
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderNumberOfPersonsShouldBeOneOrLarger", locale));
                return "error";
            }
        }
        // check for valid rental parameters
        if (UtilValidate.isEmpty(reservStart) && UtilValidate.isEmpty(reservLength) && UtilValidate.isEmpty(reservPersons)) {
            request.setAttribute("product_id", productId);
            request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.enterBookingInforamtionBeforeAddingToCart", locale));
            return "product";
        }
        // check accommodation for reservations
        if ((paramMap.containsKey("accommodationMapId")) && (paramMap.containsKey("accommodationSpotId"))) {
            accommodationMapId = (String) paramMap.remove("accommodationMapId");
            accommodationSpotId = (String) paramMap.remove("accommodationSpotId");
        }
    }
    // get the quantity
    if (paramMap.containsKey("QUANTITY")) {
        quantityStr = (String) paramMap.remove("QUANTITY");
    } else if (paramMap.containsKey("quantity")) {
        quantityStr = (String) paramMap.remove("quantity");
    }
    if (UtilValidate.isEmpty(quantityStr)) {
        // default quantity is 1
        quantityStr = "1";
    }
    // parse the price
    try {
        price = (BigDecimal) ObjectType.simpleTypeConvert(priceStr, "BigDecimal", null, locale);
    } catch (Exception e) {
        Debug.logWarning(e, "Problems parsing price string: " + priceStr, module);
        price = null;
    }
    // parse the quantity
    try {
        quantity = (BigDecimal) ObjectType.simpleTypeConvert(quantityStr, "BigDecimal", null, locale);
        // if not and if quantity is in decimal format then return error.
        if (!ProductWorker.isDecimalQuantityOrderAllowed(delegator, productId, cart.getProductStoreId())) {
            BigDecimal remainder = quantity.remainder(BigDecimal.ONE);
            if (remainder.compareTo(BigDecimal.ZERO) != 0) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.quantityInDecimalNotAllowed", locale));
                return "error";
            }
            quantity = quantity.setScale(0, UtilNumber.getRoundingMode("order.rounding"));
        } else {
            quantity = quantity.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getRoundingMode("order.rounding"));
        }
    } catch (Exception e) {
        Debug.logWarning(e, "Problems parsing quantity string: " + quantityStr, module);
        quantity = BigDecimal.ONE;
    }
    // get the selected amount
    String selectedAmountStr = null;
    if (paramMap.containsKey("ADD_AMOUNT")) {
        selectedAmountStr = (String) paramMap.remove("ADD_AMOUNT");
    } else if (paramMap.containsKey("add_amount")) {
        selectedAmountStr = (String) paramMap.remove("add_amount");
    }
    // parse the amount
    BigDecimal amount = null;
    if (UtilValidate.isNotEmpty(selectedAmountStr)) {
        try {
            amount = (BigDecimal) ObjectType.simpleTypeConvert(selectedAmountStr, "BigDecimal", null, locale);
        } catch (Exception e) {
            Debug.logWarning(e, "Problem parsing amount string: " + selectedAmountStr, module);
            amount = null;
        }
    } else {
        amount = BigDecimal.ZERO;
    }
    // check for required amount
    if ((ProductWorker.isAmountRequired(delegator, productId)) && (amount == null || amount.doubleValue() == 0.0)) {
        request.setAttribute("product_id", productId);
        request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.enterAmountBeforeAddingToCart", locale));
        return "product";
    }
    // get the ship before date (handles both yyyy-mm-dd input and full timestamp)
    shipBeforeDateStr = (String) paramMap.remove("shipBeforeDate");
    if (UtilValidate.isNotEmpty(shipBeforeDateStr)) {
        if (shipBeforeDateStr.length() == 10) {
            shipBeforeDateStr += " 00:00:00.000";
        }
        try {
            shipBeforeDate = java.sql.Timestamp.valueOf(shipBeforeDateStr);
        } catch (IllegalArgumentException e) {
            Debug.logWarning(e, "Bad shipBeforeDate input: " + e.getMessage(), module);
            shipBeforeDate = null;
        }
    }
    // get the ship after date (handles both yyyy-mm-dd input and full timestamp)
    shipAfterDateStr = (String) paramMap.remove("shipAfterDate");
    if (UtilValidate.isNotEmpty(shipAfterDateStr)) {
        if (shipAfterDateStr.length() == 10) {
            shipAfterDateStr += " 00:00:00.000";
        }
        try {
            shipAfterDate = java.sql.Timestamp.valueOf(shipAfterDateStr);
        } catch (IllegalArgumentException e) {
            Debug.logWarning(e, "Bad shipAfterDate input: " + e.getMessage(), module);
            shipAfterDate = null;
        }
    }
    // check for an add-to cart survey
    List<String> surveyResponses = null;
    if (productId != null) {
        String productStoreId = ProductStoreWorker.getProductStoreId(request);
        List<GenericValue> productSurvey = ProductStoreWorker.getProductSurveys(delegator, productStoreId, productId, "CART_ADD", parentProductId);
        if (UtilValidate.isNotEmpty(productSurvey)) {
            // TODO: implement multiple survey per product
            GenericValue survey = EntityUtil.getFirst(productSurvey);
            String surveyResponseId = (String) request.getAttribute("surveyResponseId");
            if (surveyResponseId != null) {
                surveyResponses = UtilMisc.toList(surveyResponseId);
            } else {
                String origParamMapId = UtilHttp.stashParameterMap(request);
                Map<String, Object> surveyContext = UtilMisc.<String, Object>toMap("_ORIG_PARAM_MAP_ID_", origParamMapId);
                GenericValue userLogin = cart.getUserLogin();
                String partyId = null;
                if (userLogin != null) {
                    partyId = userLogin.getString("partyId");
                }
                String formAction = "/additemsurvey";
                String nextPage = RequestHandler.getOverrideViewUri(request.getPathInfo());
                if (nextPage != null) {
                    formAction = formAction + "/" + nextPage;
                }
                ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(survey, partyId, surveyContext);
                request.setAttribute("surveyWrapper", wrapper);
                // will be used as the form action of the survey
                request.setAttribute("surveyAction", formAction);
                return "survey";
            }
        }
    }
    if (surveyResponses != null) {
        paramMap.put("surveyResponses", surveyResponses);
    }
    GenericValue productStore = ProductStoreWorker.getProductStore(request);
    if (productStore != null) {
        String addToCartRemoveIncompat = productStore.getString("addToCartRemoveIncompat");
        String addToCartReplaceUpsell = productStore.getString("addToCartReplaceUpsell");
        try {
            if ("Y".equals(addToCartRemoveIncompat)) {
                List<GenericValue> productAssocs = null;
                EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityOperator.OR, EntityCondition.makeCondition("productIdTo", EntityOperator.EQUALS, productId)), EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS, "PRODUCT_INCOMPATABLE")), EntityOperator.AND);
                productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where(cond).filterByDate().queryList();
                List<String> productList = new LinkedList<>();
                for (GenericValue productAssoc : productAssocs) {
                    if (productId.equals(productAssoc.getString("productId"))) {
                        productList.add(productAssoc.getString("productIdTo"));
                        continue;
                    }
                    if (productId.equals(productAssoc.getString("productIdTo"))) {
                        productList.add(productAssoc.getString("productId"));
                        continue;
                    }
                }
                for (ShoppingCartItem sci : cart) {
                    if (productList.contains(sci.getProductId())) {
                        try {
                            cart.removeCartItem(sci, dispatcher);
                        } catch (CartItemModifyException e) {
                            Debug.logError(e.getMessage(), module);
                        }
                    }
                }
            }
            if ("Y".equals(addToCartReplaceUpsell)) {
                List<GenericValue> productList = null;
                productList = EntityQuery.use(delegator).select("productId").from("ProductAssoc").where("productIdTo", productId, "productAssocTypeId", "PRODUCT_UPGRADE").queryList();
                if (productList != null) {
                    for (ShoppingCartItem sci : cart) {
                        if (productList.parallelStream().anyMatch(p -> sci.getProductId().equals(p.getString("productId")))) {
                            try {
                                cart.removeCartItem(sci, dispatcher);
                            } catch (CartItemModifyException e) {
                                Debug.logError(e.getMessage(), module);
                            }
                        }
                    }
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e.getMessage(), module);
        }
    }
    // check for alternative packing
    if (ProductWorker.isAlternativePacking(delegator, productId, parentProductId)) {
        GenericValue parentProduct = null;
        try {
            parentProduct = EntityQuery.use(delegator).from("Product").where("productId", parentProductId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error getting parent product", module);
        }
        BigDecimal piecesIncluded = BigDecimal.ZERO;
        if (parentProduct != null) {
            piecesIncluded = new BigDecimal(parentProduct.getLong("piecesIncluded"));
            quantity = quantity.multiply(piecesIncluded);
        }
    }
    // Translate the parameters and add to the cart
    result = cartHelper.addToCart(catalogId, shoppingListId, shoppingListItemSeqId, productId, productCategoryId, itemType, itemDescription, price, amount, quantity, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, shipBeforeDate, shipAfterDate, configWrapper, itemGroupNumber, paramMap, parentProductId);
    controlDirective = processResult(result, request);
    Integer itemId = (Integer) result.get("itemId");
    if (UtilValidate.isNotEmpty(itemId)) {
        request.setAttribute("itemId", itemId);
    }
    try {
        GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
        // Reset shipment method information in cart only if shipping applies on product.
        if (UtilValidate.isNotEmpty(product) && ProductWorker.shippingApplies(product)) {
            for (int shipGroupIndex = 0; shipGroupIndex < cart.getShipGroupSize(); shipGroupIndex++) {
                String shipContactMechId = cart.getShippingContactMechId(shipGroupIndex);
                if (UtilValidate.isNotEmpty(shipContactMechId)) {
                    cart.setShipmentMethodTypeId(shipGroupIndex, null);
                }
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error getting product" + e.getMessage(), module);
    }
    // Determine where to send the browser
    if (controlDirective.equals(ERROR)) {
        return "error";
    }
    if (cart.viewCartOnAdd()) {
        return "viewcart";
    }
    return "success";
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ProductConfigWrapper(org.apache.ofbiz.product.config.ProductConfigWrapper) Timestamp(java.sql.Timestamp) GenericValue(org.apache.ofbiz.entity.GenericValue) BigDecimal(java.math.BigDecimal) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) ProductStoreSurveyWrapper(org.apache.ofbiz.product.store.ProductStoreSurveyWrapper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 58 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class ProductPromoWorker method getProductPromoUseLimit.

/**
 * calculate low use limit for this promo for the current "order", check per order, customer, promo
 */
public static Long getProductPromoUseLimit(GenericValue productPromo, String partyId, Delegator delegator) throws GenericEntityException {
    String productPromoId = productPromo.getString("productPromoId");
    Long candidateUseLimit = null;
    Long useLimitPerOrder = productPromo.getLong("useLimitPerOrder");
    if (useLimitPerOrder != null) {
        candidateUseLimit = useLimitPerOrder;
    }
    Long useLimitPerCustomer = productPromo.getLong("useLimitPerCustomer");
    // check this whether or not there is a party right now
    if (useLimitPerCustomer != null) {
        // if partyId is not empty check previous usage
        long productPromoCustomerUseSize = 0;
        if (UtilValidate.isNotEmpty(partyId)) {
            // check to see how many times this has been used for other orders for this customer, the remainder is the limit for this order
            EntityCondition checkCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productPromoId", EntityOperator.EQUALS, productPromoId), EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED")), EntityOperator.AND);
            productPromoCustomerUseSize = EntityQuery.use(delegator).from("ProductPromoUseCheck").where(checkCondition).queryCount();
        }
        long perCustomerThisOrder = useLimitPerCustomer.longValue() - productPromoCustomerUseSize;
        if (candidateUseLimit == null || candidateUseLimit.longValue() > perCustomerThisOrder) {
            candidateUseLimit = Long.valueOf(perCustomerThisOrder);
        }
    }
    Long useLimitPerPromotion = productPromo.getLong("useLimitPerPromotion");
    if (useLimitPerPromotion != null) {
        // check to see how many times this has been used for other orders for this customer, the remainder is the limit for this order
        EntityCondition checkCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productPromoId", EntityOperator.EQUALS, productPromoId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED")), EntityOperator.AND);
        long productPromoUseSize = EntityQuery.use(delegator).from("ProductPromoUseCheck").where(checkCondition).queryCount();
        long perPromotionThisOrder = useLimitPerPromotion.longValue() - productPromoUseSize;
        if (candidateUseLimit == null || candidateUseLimit.longValue() > perPromotionThisOrder) {
            candidateUseLimit = Long.valueOf(perPromotionThisOrder);
        }
    }
    return candidateUseLimit;
}
Also used : EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition)

Example 59 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class ProductPromoWorker method checkCanUsePromoCode.

public static String checkCanUsePromoCode(String productPromoCodeId, String partyId, Delegator delegator, ShoppingCart cart, Locale locale) {
    try {
        GenericValue productPromoCode = EntityQuery.use(delegator).from("ProductPromoCode").where("productPromoCodeId", productPromoCodeId).queryOne();
        if (productPromoCode == null) {
            return UtilProperties.getMessage(resource_error, "productpromoworker.promotion_code_not_valid", UtilMisc.toMap("productPromoCodeId", productPromoCodeId), locale);
        }
        if (cart != null) {
            Set<String> promoCodes = ProductPromoWorker.getStoreProductPromoCodes(cart);
            if (UtilValidate.isEmpty(promoCodes) || !promoCodes.contains(productPromoCodeId)) {
                return UtilProperties.getMessage(resource_error, "productpromoworker.promotion_code_not_valid", UtilMisc.toMap("productPromoCodeId", productPromoCodeId), locale);
            }
        }
        Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
        Timestamp thruDate = productPromoCode.getTimestamp("thruDate");
        if (thruDate != null) {
            if (nowTimestamp.after(thruDate)) {
                return UtilProperties.getMessage(resource_error, "productpromoworker.promotion_code_is_expired_at", UtilMisc.toMap("productPromoCodeId", productPromoCodeId, "thruDate", thruDate), locale);
            }
        }
        Timestamp fromDate = productPromoCode.getTimestamp("fromDate");
        if (fromDate != null) {
            if (nowTimestamp.before(fromDate)) {
                return UtilProperties.getMessage(resource_error, "productpromoworker.promotion_code_will_be_activated_at", UtilMisc.toMap("productPromoCodeId", productPromoCodeId, "fromDate", fromDate), locale);
            }
        }
        if ("Y".equals(productPromoCode.getString("requireEmailOrParty"))) {
            boolean hasEmailOrParty = false;
            // check partyId
            if (UtilValidate.isNotEmpty(partyId)) {
                if (EntityQuery.use(delegator).from("ProductPromoCodeParty").where("productPromoCodeId", productPromoCodeId, "partyId", partyId).queryOne() != null) {
                    // found party associated with the code, looks good...
                    return null;
                }
                // check email address in ProductPromoCodeEmail
                List<EntityCondition> validEmailCondList = new LinkedList<>();
                validEmailCondList.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId));
                validEmailCondList.add(EntityCondition.makeCondition("productPromoCodeId", EntityOperator.EQUALS, productPromoCodeId));
                validEmailCondList.add(EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp));
                validEmailCondList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null)));
                long validEmailCount = EntityQuery.use(delegator).from("ProductPromoCodeEmailParty").where(validEmailCondList).queryCount();
                if (validEmailCount > 0) {
                    // there was an email in the list, looks good...
                    return null;
                }
            }
            if (!hasEmailOrParty) {
                return UtilProperties.getMessage(resource_error, "productpromoworker.promotion_code_no_account_or_email", UtilMisc.toMap("productPromoCodeId", productPromoCodeId), locale);
            }
        }
        // check per customer and per promotion code use limits
        Long useLimit = getProductPromoCodeUseLimit(productPromoCode, partyId, delegator);
        if (useLimit != null && useLimit.longValue() <= 0) {
            return UtilProperties.getMessage(resource_error, "productpromoworker.promotion_code_maximum_limit", UtilMisc.toMap("productPromoCodeId", productPromoCodeId), locale);
        }
        return null;
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error looking up ProductPromoCode", module);
        return UtilProperties.getMessage(resource_error, "productpromoworker.promotion_code_error_lookup", UtilMisc.toMap("productPromoCodeId", productPromoCodeId, "errorMsg", e.toString()), locale);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList)

Example 60 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class ShippingEvents method getShippingOriginContactMech.

/**
 * Attempts to get the supplier's shipping origin address and failing that, the general location.
 */
public static GenericValue getShippingOriginContactMech(Delegator delegator, String supplierPartyId) throws GeneralException {
    List<EntityCondition> conditions = UtilMisc.toList(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, supplierPartyId), EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "POSTAL_ADDRESS"), EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.IN, UtilMisc.toList("SHIP_ORIG_LOCATION", "GENERAL_LOCATION")), EntityUtil.getFilterByDateExpr("contactFromDate", "contactThruDate"), EntityUtil.getFilterByDateExpr("purposeFromDate", "purposeThruDate"));
    EntityConditionList<EntityCondition> ecl = EntityCondition.makeCondition(conditions, EntityOperator.AND);
    List<GenericValue> addresses = delegator.findList("PartyContactWithPurpose", ecl, null, UtilMisc.toList("contactMechPurposeTypeId DESC"), null, false);
    GenericValue generalAddress = null;
    GenericValue originAddress = null;
    for (GenericValue address : addresses) {
        if ("GENERAL_LOCATION".equals(address.get("contactMechPurposeTypeId")))
            generalAddress = address;
        else if ("SHIP_ORIG_LOCATION".equals(address.get("contactMechPurposeTypeId")))
            originAddress = address;
    }
    return originAddress != null ? originAddress : generalAddress;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition)

Aggregations

EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)118 GenericValue (org.apache.ofbiz.entity.GenericValue)96 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)78 Delegator (org.apache.ofbiz.entity.Delegator)60 LinkedList (java.util.LinkedList)58 Locale (java.util.Locale)43 Timestamp (java.sql.Timestamp)40 HashMap (java.util.HashMap)32 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)29 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)26 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)24 Map (java.util.Map)22 BigDecimal (java.math.BigDecimal)21 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)18 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)14 GeneralException (org.apache.ofbiz.base.util.GeneralException)12 ArrayList (java.util.ArrayList)11 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)9 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)8 HashSet (java.util.HashSet)7