Search in sources :

Example 11 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PriceServices method calculateProductPrice.

/**
 * <p>Calculates the price of a product from pricing rules given the following input, and of course access to the database:</p>
 * <ul>
 *   <li>productId
 *   <li>partyId
 *   <li>prodCatalogId
 *   <li>webSiteId
 *   <li>productStoreId
 *   <li>productStoreGroupId
 *   <li>agreementId
 *   <li>quantity
 *   <li>currencyUomId
 *   <li>checkIncludeVat
 * </ul>
 */
public static Map<String, Object> calculateProductPrice(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> result = new HashMap<String, Object>();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    GenericValue product = (GenericValue) context.get("product");
    String productId = product.getString("productId");
    String prodCatalogId = (String) context.get("prodCatalogId");
    String webSiteId = (String) context.get("webSiteId");
    String checkIncludeVat = (String) context.get("checkIncludeVat");
    String surveyResponseId = (String) context.get("surveyResponseId");
    Map<String, Object> customAttributes = UtilGenerics.checkMap(context.get("customAttributes"));
    String findAllQuantityPricesStr = (String) context.get("findAllQuantityPrices");
    boolean findAllQuantityPrices = "Y".equals(findAllQuantityPricesStr);
    boolean optimizeForLargeRuleSet = "Y".equals(context.get("optimizeForLargeRuleSet"));
    String agreementId = (String) context.get("agreementId");
    String productStoreId = (String) context.get("productStoreId");
    String productStoreGroupId = (String) context.get("productStoreGroupId");
    Locale locale = (Locale) context.get("locale");
    GenericValue productStore = null;
    try {
        // we have a productStoreId, if the corresponding ProductStore.primaryStoreGroupId is not empty, use that
        productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).cache().queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error getting product store info from the database while calculating price" + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveProductStore", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    if (UtilValidate.isEmpty(productStoreGroupId)) {
        if (productStore != null) {
            try {
                if (UtilValidate.isNotEmpty(productStore.getString("primaryStoreGroupId"))) {
                    productStoreGroupId = productStore.getString("primaryStoreGroupId");
                } else {
                    // no ProductStore.primaryStoreGroupId, try ProductStoreGroupMember
                    List<GenericValue> productStoreGroupMemberList = EntityQuery.use(delegator).from("ProductStoreGroupMember").where("productStoreId", productStoreId).orderBy("sequenceNum", "-fromDate").cache(true).queryList();
                    productStoreGroupMemberList = EntityUtil.filterByDate(productStoreGroupMemberList, true);
                    if (productStoreGroupMemberList.size() > 0) {
                        GenericValue productStoreGroupMember = EntityUtil.getFirst(productStoreGroupMemberList);
                        productStoreGroupId = productStoreGroupMember.getString("productStoreGroupId");
                    }
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, "Error getting product store info from the database while calculating price" + e.toString(), module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveProductStore", UtilMisc.toMap("errorString", e.toString()), locale));
            }
        }
        // still empty, default to _NA_
        if (UtilValidate.isEmpty(productStoreGroupId)) {
            productStoreGroupId = "_NA_";
        }
    }
    // if currencyUomId is null get from properties file, if nothing there assume USD (USD: American Dollar) for now
    String currencyDefaultUomId = (String) context.get("currencyUomId");
    String currencyUomIdTo = (String) context.get("currencyUomIdTo");
    if (UtilValidate.isEmpty(currencyDefaultUomId)) {
        if (productStore != null && UtilValidate.isNotEmpty(productStore.getString("defaultCurrencyUomId"))) {
            currencyDefaultUomId = productStore.getString("defaultCurrencyUomId");
        } else {
            currencyDefaultUomId = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
        }
    }
    // productPricePurposeId is null assume "PURCHASE", which is equivalent to what prices were before the purpose concept
    String productPricePurposeId = (String) context.get("productPricePurposeId");
    if (UtilValidate.isEmpty(productPricePurposeId)) {
        productPricePurposeId = "PURCHASE";
    }
    // termUomId, for things like recurring prices specifies the term (time/frequency measure for example) of the recurrence
    // if this is empty it will simply not be used to constrain the selection
    String termUomId = (String) context.get("termUomId");
    // if this product is variant, find the virtual product and apply checks to it as well
    String virtualProductId = null;
    if ("Y".equals(product.getString("isVariant"))) {
        try {
            virtualProductId = ProductWorker.getVariantVirtualId(product);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error getting virtual product id from the database while calculating price" + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveVirtualProductId", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    // get prices for virtual product if one is found; get all ProductPrice entities for this productId and currencyUomId
    List<GenericValue> virtualProductPrices = null;
    if (virtualProductId != null) {
        try {
            virtualProductPrices = EntityQuery.use(delegator).from("ProductPrice").where("productId", virtualProductId, "currencyUomId", currencyDefaultUomId, "productStoreGroupId", productStoreGroupId).orderBy("-fromDate").cache(true).queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, "An error occurred while getting the product prices", module);
        }
        virtualProductPrices = EntityUtil.filterByDate(virtualProductPrices, true);
    }
    // NOTE: partyId CAN be null
    String partyId = (String) context.get("partyId");
    if (UtilValidate.isEmpty(partyId) && context.get("userLogin") != null) {
        GenericValue userLogin = (GenericValue) context.get("userLogin");
        partyId = userLogin.getString("partyId");
    }
    // check for auto-userlogin for price rules
    if (UtilValidate.isEmpty(partyId) && context.get("autoUserLogin") != null) {
        GenericValue userLogin = (GenericValue) context.get("autoUserLogin");
        partyId = userLogin.getString("partyId");
    }
    BigDecimal quantity = (BigDecimal) context.get("quantity");
    if (quantity == null)
        quantity = BigDecimal.ONE;
    BigDecimal amount = (BigDecimal) context.get("amount");
    List<EntityCondition> productPriceEcList = new LinkedList<EntityCondition>();
    productPriceEcList.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
    // this funny statement is for backward compatibility purposes; the productPricePurposeId is a new pk field on the ProductPrice entity and in order databases may not be populated, until the pk is updated and such; this will ease the transition somewhat
    if ("PURCHASE".equals(productPricePurposeId)) {
        productPriceEcList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("productPricePurposeId", EntityOperator.EQUALS, productPricePurposeId), EntityOperator.OR, EntityCondition.makeCondition("productPricePurposeId", EntityOperator.EQUALS, null)));
    } else {
        productPriceEcList.add(EntityCondition.makeCondition("productPricePurposeId", EntityOperator.EQUALS, productPricePurposeId));
    }
    productPriceEcList.add(EntityCondition.makeCondition("currencyUomId", EntityOperator.EQUALS, currencyDefaultUomId));
    productPriceEcList.add(EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS, productStoreGroupId));
    if (UtilValidate.isNotEmpty(termUomId)) {
        productPriceEcList.add(EntityCondition.makeCondition("termUomId", EntityOperator.EQUALS, termUomId));
    }
    EntityCondition productPriceEc = EntityCondition.makeCondition(productPriceEcList, EntityOperator.AND);
    // for prices, get all ProductPrice entities for this productId and currencyUomId
    List<GenericValue> productPrices = null;
    try {
        productPrices = EntityQuery.use(delegator).from("ProductPrice").where(productPriceEc).orderBy("-fromDate").cache(true).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "An error occurred while getting the product prices", module);
    }
    productPrices = EntityUtil.filterByDate(productPrices, true);
    // ===== get the prices we need: list, default, average cost, promo, min, max =====
    // if any of these prices is missing and this product is a variant, default to the corresponding price on the virtual product
    GenericValue listPriceValue = getPriceValueForType("LIST_PRICE", productPrices, virtualProductPrices);
    GenericValue defaultPriceValue = getPriceValueForType("DEFAULT_PRICE", productPrices, virtualProductPrices);
    // ProductPrice entity.
    if (UtilValidate.isNotEmpty(agreementId)) {
        try {
            GenericValue agreementPriceValue = EntityQuery.use(delegator).from("AgreementItemAndProductAppl").where("agreementId", agreementId, "productId", productId, "currencyUomId", currencyDefaultUomId).queryFirst();
            if (agreementPriceValue != null && agreementPriceValue.get("price") != null) {
                defaultPriceValue = agreementPriceValue;
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error getting agreement info from the database while calculating price" + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveAgreementInfo", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    GenericValue competitivePriceValue = getPriceValueForType("COMPETITIVE_PRICE", productPrices, virtualProductPrices);
    GenericValue averageCostValue = getPriceValueForType("AVERAGE_COST", productPrices, virtualProductPrices);
    GenericValue promoPriceValue = getPriceValueForType("PROMO_PRICE", productPrices, virtualProductPrices);
    GenericValue minimumPriceValue = getPriceValueForType("MINIMUM_PRICE", productPrices, virtualProductPrices);
    GenericValue maximumPriceValue = getPriceValueForType("MAXIMUM_PRICE", productPrices, virtualProductPrices);
    GenericValue wholesalePriceValue = getPriceValueForType("WHOLESALE_PRICE", productPrices, virtualProductPrices);
    GenericValue specialPromoPriceValue = getPriceValueForType("SPECIAL_PROMO_PRICE", productPrices, virtualProductPrices);
    // now if this is a virtual product check each price type, if doesn't exist get from variant with lowest DEFAULT_PRICE
    if ("Y".equals(product.getString("isVirtual"))) {
        // only do this if there is no default price, consider the others optional for performance reasons
        if (defaultPriceValue == null) {
            // use the cache to find the variant with the lowest default price
            try {
                List<GenericValue> variantAssocList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", product.get("productId"), "productAssocTypeId", "PRODUCT_VARIANT").orderBy("-fromDate").cache(true).filterByDate().queryList();
                BigDecimal minDefaultPrice = null;
                List<GenericValue> variantProductPrices = null;
                for (GenericValue variantAssoc : variantAssocList) {
                    String curVariantProductId = variantAssoc.getString("productIdTo");
                    List<GenericValue> curVariantPriceList = EntityQuery.use(delegator).from("ProductPrice").where("productId", curVariantProductId).orderBy("-fromDate").cache(true).filterByDate(nowTimestamp).queryList();
                    List<GenericValue> tempDefaultPriceList = EntityUtil.filterByAnd(curVariantPriceList, UtilMisc.toMap("productPriceTypeId", "DEFAULT_PRICE"));
                    GenericValue curDefaultPriceValue = EntityUtil.getFirst(tempDefaultPriceList);
                    if (curDefaultPriceValue != null) {
                        BigDecimal curDefaultPrice = curDefaultPriceValue.getBigDecimal("price");
                        if (minDefaultPrice == null || curDefaultPrice.compareTo(minDefaultPrice) < 0) {
                            // check to see if the product is discontinued for sale before considering it the lowest price
                            GenericValue curVariantProduct = EntityQuery.use(delegator).from("Product").where("productId", curVariantProductId).cache().queryOne();
                            if (curVariantProduct != null) {
                                Timestamp salesDiscontinuationDate = curVariantProduct.getTimestamp("salesDiscontinuationDate");
                                if (salesDiscontinuationDate == null || salesDiscontinuationDate.after(nowTimestamp)) {
                                    minDefaultPrice = curDefaultPrice;
                                    variantProductPrices = curVariantPriceList;
                                }
                            }
                        }
                    }
                }
                if (variantProductPrices != null) {
                    // we have some other options, give 'em a go...
                    if (listPriceValue == null) {
                        listPriceValue = getPriceValueForType("LIST_PRICE", variantProductPrices, null);
                    }
                    if (competitivePriceValue == null) {
                        competitivePriceValue = getPriceValueForType("COMPETITIVE_PRICE", variantProductPrices, null);
                    }
                    if (averageCostValue == null) {
                        averageCostValue = getPriceValueForType("AVERAGE_COST", variantProductPrices, null);
                    }
                    if (promoPriceValue == null) {
                        promoPriceValue = getPriceValueForType("PROMO_PRICE", variantProductPrices, null);
                    }
                    if (minimumPriceValue == null) {
                        minimumPriceValue = getPriceValueForType("MINIMUM_PRICE", variantProductPrices, null);
                    }
                    if (maximumPriceValue == null) {
                        maximumPriceValue = getPriceValueForType("MAXIMUM_PRICE", variantProductPrices, null);
                    }
                    if (wholesalePriceValue == null) {
                        wholesalePriceValue = getPriceValueForType("WHOLESALE_PRICE", variantProductPrices, null);
                    }
                    if (specialPromoPriceValue == null) {
                        specialPromoPriceValue = getPriceValueForType("SPECIAL_PROMO_PRICE", variantProductPrices, null);
                    }
                    defaultPriceValue = getPriceValueForType("DEFAULT_PRICE", variantProductPrices, null);
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, "An error occurred while getting the product prices", module);
            }
        }
    }
    BigDecimal promoPrice = BigDecimal.ZERO;
    if (promoPriceValue != null && promoPriceValue.get("price") != null) {
        promoPrice = promoPriceValue.getBigDecimal("price");
    }
    BigDecimal wholesalePrice = BigDecimal.ZERO;
    if (wholesalePriceValue != null && wholesalePriceValue.get("price") != null) {
        wholesalePrice = wholesalePriceValue.getBigDecimal("price");
    }
    boolean validPriceFound = false;
    BigDecimal defaultPrice = BigDecimal.ZERO;
    List<GenericValue> orderItemPriceInfos = new LinkedList<GenericValue>();
    if (defaultPriceValue != null) {
        // If a price calc formula (service) is specified, then use it to get the unit price
        if ("ProductPrice".equals(defaultPriceValue.getEntityName()) && UtilValidate.isNotEmpty(defaultPriceValue.getString("customPriceCalcService"))) {
            GenericValue customMethod = null;
            try {
                customMethod = defaultPriceValue.getRelatedOne("CustomMethod", false);
            } catch (GenericEntityException gee) {
                Debug.logError(gee, "An error occurred while getting the customPriceCalcService", module);
            }
            if (customMethod != null && UtilValidate.isNotEmpty(customMethod.getString("customMethodName"))) {
                Map<String, Object> inMap = UtilMisc.toMap("userLogin", context.get("userLogin"), "product", product);
                inMap.put("initialPrice", defaultPriceValue.getBigDecimal("price"));
                inMap.put("currencyUomId", currencyDefaultUomId);
                inMap.put("quantity", quantity);
                inMap.put("amount", amount);
                if (UtilValidate.isNotEmpty(surveyResponseId)) {
                    inMap.put("surveyResponseId", surveyResponseId);
                }
                if (UtilValidate.isNotEmpty(customAttributes)) {
                    inMap.put("customAttributes", customAttributes);
                }
                try {
                    Map<String, Object> outMap = dispatcher.runSync(customMethod.getString("customMethodName"), inMap);
                    if (ServiceUtil.isSuccess(outMap)) {
                        BigDecimal calculatedDefaultPrice = (BigDecimal) outMap.get("price");
                        orderItemPriceInfos = UtilGenerics.checkList(outMap.get("orderItemPriceInfos"));
                        if (UtilValidate.isNotEmpty(calculatedDefaultPrice)) {
                            defaultPrice = calculatedDefaultPrice;
                            validPriceFound = true;
                        }
                    }
                } catch (GenericServiceException gse) {
                    Debug.logError(gse, "An error occurred while running the customPriceCalcService [" + customMethod.getString("customMethodName") + "]", module);
                }
            }
        }
        if (!validPriceFound && defaultPriceValue.get("price") != null) {
            defaultPrice = defaultPriceValue.getBigDecimal("price");
            validPriceFound = true;
        }
    }
    BigDecimal listPrice = listPriceValue != null ? listPriceValue.getBigDecimal("price") : null;
    if (listPrice == null) {
        // no list price, use defaultPrice for the final price
        // ========= ensure calculated price is not below minSalePrice or above maxSalePrice =========
        BigDecimal maxSellPrice = maximumPriceValue != null ? maximumPriceValue.getBigDecimal("price") : null;
        if (maxSellPrice != null && defaultPrice.compareTo(maxSellPrice) > 0) {
            defaultPrice = maxSellPrice;
        }
        // min price second to override max price, safety net
        BigDecimal minSellPrice = minimumPriceValue != null ? minimumPriceValue.getBigDecimal("price") : null;
        if (minSellPrice != null && defaultPrice.compareTo(minSellPrice) < 0) {
            defaultPrice = minSellPrice;
            // since we have found a minimum price that has overriden a the defaultPrice, even if no valid one was found, we will consider it as if one had been...
            validPriceFound = true;
        }
        result.put("basePrice", defaultPrice);
        result.put("price", defaultPrice);
        result.put("defaultPrice", defaultPrice);
        result.put("competitivePrice", competitivePriceValue != null ? competitivePriceValue.getBigDecimal("price") : null);
        result.put("averageCost", averageCostValue != null ? averageCostValue.getBigDecimal("price") : null);
        result.put("promoPrice", promoPriceValue != null ? promoPriceValue.getBigDecimal("price") : null);
        result.put("specialPromoPrice", specialPromoPriceValue != null ? specialPromoPriceValue.getBigDecimal("price") : null);
        result.put("validPriceFound", Boolean.valueOf(validPriceFound));
        result.put("isSale", Boolean.FALSE);
        result.put("orderItemPriceInfos", orderItemPriceInfos);
        Map<String, Object> errorResult = addGeneralResults(result, competitivePriceValue, specialPromoPriceValue, productStore, checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
        if (errorResult != null)
            return errorResult;
    } else {
        try {
            List<GenericValue> allProductPriceRules = makeProducePriceRuleList(delegator, optimizeForLargeRuleSet, productId, virtualProductId, prodCatalogId, productStoreGroupId, webSiteId, partyId, currencyDefaultUomId);
            allProductPriceRules = EntityUtil.filterByDate(allProductPriceRules, true);
            List<GenericValue> quantityProductPriceRules = null;
            List<GenericValue> nonQuantityProductPriceRules = null;
            if (findAllQuantityPrices) {
                // split into list with quantity conditions and list without, then iterate through each quantity cond one
                quantityProductPriceRules = new LinkedList<GenericValue>();
                nonQuantityProductPriceRules = new LinkedList<GenericValue>();
                for (GenericValue productPriceRule : allProductPriceRules) {
                    List<GenericValue> productPriceCondList = EntityQuery.use(delegator).from("ProductPriceCond").where("productPriceRuleId", productPriceRule.get("productPriceRuleId")).cache(true).queryList();
                    boolean foundQuantityInputParam = false;
                    // only consider a rule if all conditions except the quantity condition are true
                    boolean allExceptQuantTrue = true;
                    for (GenericValue productPriceCond : productPriceCondList) {
                        if ("PRIP_QUANTITY".equals(productPriceCond.getString("inputParamEnumId"))) {
                            foundQuantityInputParam = true;
                        } else {
                            if (!checkPriceCondition(productPriceCond, productId, virtualProductId, prodCatalogId, productStoreGroupId, webSiteId, partyId, quantity, listPrice, currencyDefaultUomId, delegator, nowTimestamp)) {
                                allExceptQuantTrue = false;
                            }
                        }
                    }
                    if (foundQuantityInputParam && allExceptQuantTrue) {
                        quantityProductPriceRules.add(productPriceRule);
                    } else {
                        nonQuantityProductPriceRules.add(productPriceRule);
                    }
                }
            }
            if (findAllQuantityPrices) {
                List<Map<String, Object>> allQuantityPrices = new LinkedList<Map<String, Object>>();
                // foreach create an entry in the out list and eval that rule and all nonQuantityProductPriceRules rather than a single rule
                for (GenericValue quantityProductPriceRule : quantityProductPriceRules) {
                    List<GenericValue> ruleListToUse = new LinkedList<GenericValue>();
                    ruleListToUse.add(quantityProductPriceRule);
                    ruleListToUse.addAll(nonQuantityProductPriceRules);
                    Map<String, Object> quantCalcResults = calcPriceResultFromRules(ruleListToUse, listPrice, defaultPrice, promoPrice, wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, webSiteId, partyId, null, currencyDefaultUomId, delegator, nowTimestamp, locale);
                    Map<String, Object> quantErrorResult = addGeneralResults(quantCalcResults, competitivePriceValue, specialPromoPriceValue, productStore, checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
                    if (quantErrorResult != null)
                        return quantErrorResult;
                    // also add the quantityProductPriceRule to the Map so it can be used for quantity break information
                    quantCalcResults.put("quantityProductPriceRule", quantityProductPriceRule);
                    allQuantityPrices.add(quantCalcResults);
                }
                result.put("allQuantityPrices", allQuantityPrices);
                // use a quantity 1 to get the main price, then fill in the quantity break prices
                Map<String, Object> calcResults = calcPriceResultFromRules(allProductPriceRules, listPrice, defaultPrice, promoPrice, wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, webSiteId, partyId, BigDecimal.ONE, currencyDefaultUomId, delegator, nowTimestamp, locale);
                result.putAll(calcResults);
                // The orderItemPriceInfos out parameter requires a special treatment:
                // the list of OrderItemPriceInfos generated by the price rule is appended to
                // the existing orderItemPriceInfos list and the aggregated list is returned.
                List<GenericValue> orderItemPriceInfosFromRule = UtilGenerics.checkList(calcResults.get("orderItemPriceInfos"));
                if (UtilValidate.isNotEmpty(orderItemPriceInfosFromRule)) {
                    orderItemPriceInfos.addAll(orderItemPriceInfosFromRule);
                }
                result.put("orderItemPriceInfos", orderItemPriceInfos);
                Map<String, Object> errorResult = addGeneralResults(result, competitivePriceValue, specialPromoPriceValue, productStore, checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
                if (errorResult != null)
                    return errorResult;
            } else {
                Map<String, Object> calcResults = calcPriceResultFromRules(allProductPriceRules, listPrice, defaultPrice, promoPrice, wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, webSiteId, partyId, quantity, currencyDefaultUomId, delegator, nowTimestamp, locale);
                result.putAll(calcResults);
                // The orderItemPriceInfos out parameter requires a special treatment:
                // the list of OrderItemPriceInfos generated by the price rule is appended to
                // the existing orderItemPriceInfos list and the aggregated list is returned.
                List<GenericValue> orderItemPriceInfosFromRule = UtilGenerics.checkList(calcResults.get("orderItemPriceInfos"));
                if (UtilValidate.isNotEmpty(orderItemPriceInfosFromRule)) {
                    orderItemPriceInfos.addAll(orderItemPriceInfosFromRule);
                }
                result.put("orderItemPriceInfos", orderItemPriceInfos);
                Map<String, Object> errorResult = addGeneralResults(result, competitivePriceValue, specialPromoPriceValue, productStore, checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
                if (errorResult != null)
                    return errorResult;
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error getting rules from the database while calculating price", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrievePriceRules", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    // Convert the value to the price currency, if required
    if ("true".equals(EntityUtilProperties.getPropertyValue("catalog", "convertProductPriceCurrency", delegator))) {
        if (UtilValidate.isNotEmpty(currencyDefaultUomId) && UtilValidate.isNotEmpty(currencyUomIdTo) && !currencyDefaultUomId.equals(currencyUomIdTo)) {
            if (UtilValidate.isNotEmpty(result)) {
                Map<String, Object> convertPriceMap = new HashMap<String, Object>();
                for (Map.Entry<String, Object> entry : result.entrySet()) {
                    BigDecimal tempPrice = BigDecimal.ZERO;
                    switch(entry.getKey()) {
                        case "basePrice":
                            tempPrice = (BigDecimal) entry.getValue();
                        case "price":
                            tempPrice = (BigDecimal) entry.getValue();
                        case "defaultPrice":
                            tempPrice = (BigDecimal) entry.getValue();
                        case "competitivePrice":
                            tempPrice = (BigDecimal) entry.getValue();
                        case "averageCost":
                            tempPrice = (BigDecimal) entry.getValue();
                        case "promoPrice":
                            tempPrice = (BigDecimal) entry.getValue();
                        case "specialPromoPrice":
                            tempPrice = (BigDecimal) entry.getValue();
                        case "listPrice":
                            tempPrice = (BigDecimal) entry.getValue();
                    }
                    if (tempPrice != null && tempPrice != BigDecimal.ZERO) {
                        Map<String, Object> priceResults = new HashMap<String, Object>();
                        try {
                            priceResults = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", currencyDefaultUomId, "uomIdTo", currencyUomIdTo, "originalValue", tempPrice, "defaultDecimalScale", Long.valueOf(2), "defaultRoundingMode", "HalfUp"));
                            if (ServiceUtil.isError(priceResults) || (priceResults.get("convertedValue") == null)) {
                                Debug.logWarning("Unable to convert " + entry.getKey() + " for product  " + productId, module);
                            }
                        } catch (GenericServiceException e) {
                            Debug.logError(e, module);
                        }
                        convertPriceMap.put(entry.getKey(), priceResults.get("convertedValue"));
                    } else {
                        convertPriceMap.put(entry.getKey(), entry.getValue());
                    }
                }
                if (UtilValidate.isNotEmpty(convertPriceMap)) {
                    convertPriceMap.put("currencyUsed", currencyUomIdTo);
                    result = convertPriceMap;
                }
            }
        }
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) 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 12 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PriceServices method calculatePurchasePrice.

/**
 * Calculates the purchase price of a product
 */
public static Map<String, Object> calculatePurchasePrice(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> result = new HashMap<String, Object>();
    List<GenericValue> orderItemPriceInfos = new LinkedList<GenericValue>();
    boolean validPriceFound = false;
    BigDecimal price = BigDecimal.ZERO;
    GenericValue product = (GenericValue) context.get("product");
    String productId = product.getString("productId");
    String agreementId = (String) context.get("agreementId");
    String currencyUomId = (String) context.get("currencyUomId");
    String partyId = (String) context.get("partyId");
    BigDecimal quantity = (BigDecimal) context.get("quantity");
    Locale locale = (Locale) context.get("locale");
    // a) Get the Price from the Agreement* data model
    if (Debug.infoOn())
        Debug.logInfo("Try to resolve purchase price from agreement " + agreementId, module);
    if (UtilValidate.isNotEmpty(agreementId)) {
        // TODO Search before if agreement is associate to SupplierProduct.
        // confirm that agreement is price application on purchase type and contains a value for the product
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityExpr.makeCondition("agreementId", agreementId), EntityExpr.makeCondition("agreementItemTypeId", "AGREEMENT_PRICING_PR"), EntityExpr.makeCondition("agreementTypeId", "PURCHASE_AGREEMENT"), EntityExpr.makeCondition("productId", productId)));
        try {
            List<GenericValue> agreementPrices = delegator.findList("AgreementItemAndProductAppl", cond, UtilMisc.toSet("price", "currencyUomId"), null, null, true);
            if (UtilValidate.isNotEmpty(agreementPrices)) {
                GenericValue priceFound = null;
                // resolve price on given currency. If not define, try to convert a present price
                priceFound = EntityUtil.getFirst(EntityUtil.filterByAnd(agreementPrices, UtilMisc.toMap("currencyUomId", currencyUomId)));
                if (Debug.infoOn()) {
                    Debug.logInfo("             AgreementItem " + agreementPrices, module);
                    Debug.logInfo("             currencyUomId " + currencyUomId, module);
                    Debug.logInfo("             priceFound " + priceFound, module);
                }
                if (priceFound == null) {
                    priceFound = EntityUtil.getFirst(agreementPrices);
                    try {
                        Map<String, Object> priceConvertMap = UtilMisc.toMap("uomId", priceFound.getString("currencyUomId"), "uomIdTo", currencyUomId, "originalValue", priceFound.getBigDecimal("price"), "defaultDecimalScale", Long.valueOf(2), "defaultRoundingMode", "HalfUp");
                        Map<String, Object> priceResults = dispatcher.runSync("convertUom", priceConvertMap);
                        if (ServiceUtil.isError(priceResults) || (priceResults.get("convertedValue") == null)) {
                            Debug.logWarning("Unable to convert " + priceFound + " for product  " + productId, module);
                        } else {
                            price = (BigDecimal) priceResults.get("convertedValue");
                            validPriceFound = true;
                        }
                    } catch (GenericServiceException e) {
                        Debug.logError(e, module);
                    }
                } else {
                    price = priceFound.getBigDecimal("price");
                    validPriceFound = true;
                }
            }
            if (validPriceFound) {
                GenericValue agreement = delegator.findOne("Agreement", true, UtilMisc.toMap("agreementId", agreementId));
                StringBuilder priceInfoDescription = new StringBuilder();
                priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductAgreementUse", locale));
                priceInfoDescription.append("[");
                priceInfoDescription.append(agreementId);
                priceInfoDescription.append("] ");
                priceInfoDescription.append(agreement.get("description"));
                GenericValue orderItemPriceInfo = delegator.makeValue("OrderItemPriceInfo");
                // make sure description is <= than 250 chars
                String priceInfoDescriptionString = priceInfoDescription.toString();
                if (priceInfoDescriptionString.length() > 250) {
                    priceInfoDescriptionString = priceInfoDescriptionString.substring(0, 250);
                }
                orderItemPriceInfo.set("description", priceInfoDescriptionString);
                orderItemPriceInfos.add(orderItemPriceInfo);
            }
        } catch (GenericEntityException gee) {
            Debug.logError(gee, module);
            return ServiceUtil.returnError(gee.getMessage());
        }
    }
    // b) If no price can be found, get the lastPrice from the SupplierProduct entity
    if (!validPriceFound) {
        Map<String, Object> priceContext = UtilMisc.toMap("currencyUomId", currencyUomId, "partyId", partyId, "productId", productId, "quantity", quantity);
        List<GenericValue> productSuppliers = null;
        try {
            Map<String, Object> priceResult = dispatcher.runSync("getSuppliersForProduct", priceContext);
            if (ServiceUtil.isError(priceResult)) {
                String errMsg = ServiceUtil.getErrorMessage(priceResult);
                Debug.logError(errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
            productSuppliers = UtilGenerics.checkList(priceResult.get("supplierProducts"));
        } catch (GenericServiceException gse) {
            Debug.logError(gse, module);
            return ServiceUtil.returnError(gse.getMessage());
        }
        if (productSuppliers != null) {
            for (GenericValue productSupplier : productSuppliers) {
                if (!validPriceFound) {
                    price = ((BigDecimal) productSupplier.get("lastPrice"));
                    validPriceFound = true;
                }
                // add a orderItemPriceInfo element too, without orderId or orderItemId
                StringBuilder priceInfoDescription = new StringBuilder();
                priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductSupplier", locale));
                priceInfoDescription.append(" [");
                priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductSupplierMinimumOrderQuantity", locale));
                priceInfoDescription.append(productSupplier.getBigDecimal("minimumOrderQuantity"));
                priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductSupplierLastPrice", locale));
                priceInfoDescription.append(productSupplier.getBigDecimal("lastPrice"));
                priceInfoDescription.append("]");
                GenericValue orderItemPriceInfo = delegator.makeValue("OrderItemPriceInfo");
                // make sure description is <= than 250 chars
                String priceInfoDescriptionString = priceInfoDescription.toString();
                if (priceInfoDescriptionString.length() > 250) {
                    priceInfoDescriptionString = priceInfoDescriptionString.substring(0, 250);
                }
                orderItemPriceInfo.set("description", priceInfoDescriptionString);
                orderItemPriceInfos.add(orderItemPriceInfo);
            }
        }
    }
    // c) If no price can be found, get the averageCost from the ProductPrice entity
    if (!validPriceFound) {
        List<GenericValue> prices = null;
        try {
            prices = EntityQuery.use(delegator).from("ProductPrice").where("productId", productId, "productPricePurposeId", "PURCHASE").orderBy("-fromDate").queryList();
            // if no prices are found; find the prices of the parent product
            if (UtilValidate.isEmpty(prices)) {
                GenericValue parentProduct = ProductWorker.getParentProduct(productId, delegator);
                if (parentProduct != null) {
                    String parentProductId = parentProduct.getString("productId");
                    prices = EntityQuery.use(delegator).from("ProductPrice").where("productId", parentProductId, "productPricePurposeId", "PURCHASE").orderBy("-fromDate").queryList();
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
        // filter out the old prices
        prices = EntityUtil.filterByDate(prices);
        // first check for the AVERAGE_COST price type
        List<GenericValue> pricesToUse = EntityUtil.filterByAnd(prices, UtilMisc.toMap("productPriceTypeId", "AVERAGE_COST"));
        if (UtilValidate.isEmpty(pricesToUse)) {
            // next go with default price
            pricesToUse = EntityUtil.filterByAnd(prices, UtilMisc.toMap("productPriceTypeId", "DEFAULT_PRICE"));
            if (UtilValidate.isEmpty(pricesToUse)) {
                // finally use list price
                pricesToUse = EntityUtil.filterByAnd(prices, UtilMisc.toMap("productPriceTypeId", "LIST_PRICE"));
            }
        }
        // use the most current price
        GenericValue thisPrice = EntityUtil.getFirst(pricesToUse);
        if (thisPrice != null) {
            price = thisPrice.getBigDecimal("price");
            validPriceFound = true;
        }
    }
    result.put("price", price);
    result.put("validPriceFound", Boolean.valueOf(validPriceFound));
    result.put("orderItemPriceInfos", orderItemPriceInfos);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) 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)

Example 13 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class ProductPromoContentWrapper method getProductPromoContentAsText.

public static String getProductPromoContentAsText(GenericValue productPromo, String productPromoContentTypeId, HttpServletRequest request, String encoderType) {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    return getProductPromoContentAsText(productPromo, productPromoContentTypeId, UtilHttp.getLocale(request), EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator), null, null, productPromo.getDelegator(), dispatcher, encoderType);
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator)

Example 14 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PromoServices method importPromoCodesFromFile.

public static Map<String, Object> importPromoCodesFromFile(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    // check the uploaded file
    ByteBuffer fileBytes = (ByteBuffer) context.get("uploadedFile");
    if (fileBytes == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportUploadedFileNotValid", locale));
    }
    String encoding = System.getProperty("file.encoding");
    String file = Charset.forName(encoding).decode(fileBytes).toString();
    // get the createProductPromoCode Model
    ModelService promoModel;
    try {
        promoModel = dispatcher.getDispatchContext().getModelService("createProductPromoCode");
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // make a temp context for invocations
    Map<String, Object> invokeCtx = promoModel.makeValid(context, ModelService.IN_PARAM);
    // read the bytes into a reader
    BufferedReader reader = new BufferedReader(new StringReader(file));
    List<Object> errors = new LinkedList<>();
    int lines = 0;
    String line;
    // read the uploaded file and process each line
    try {
        while ((line = reader.readLine()) != null) {
            // check to see if we should ignore this line
            if (line.length() > 0 && !line.startsWith("#")) {
                if (line.length() <= 20) {
                    // valid promo code
                    Map<String, Object> inContext = new HashMap<>();
                    inContext.putAll(invokeCtx);
                    inContext.put("productPromoCodeId", line);
                    Map<String, Object> result = dispatcher.runSync("createProductPromoCode", inContext);
                    if (result != null && ServiceUtil.isError(result)) {
                        errors.add(line + ": " + ServiceUtil.getErrorMessage(result));
                    }
                } else {
                    // not valid ignore and notify
                    errors.add(line + UtilProperties.getMessage(resource, "ProductPromoCodeInvalidCode", locale));
                }
                ++lines;
            }
        }
    } catch (IOException | GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }
    // return errors or success
    if (errors.size() > 0) {
        return ServiceUtil.returnError(errors);
    } else if (lines == 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportEmptyFile", locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) LinkedList(java.util.LinkedList) ModelService(org.apache.ofbiz.service.ModelService) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 15 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PromoServices method importPromoCodeEmailsFromFile.

public static Map<String, Object> importPromoCodeEmailsFromFile(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String productPromoCodeId = (String) context.get("productPromoCodeId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    ByteBuffer bytebufferwrapper = (ByteBuffer) context.get("uploadedFile");
    if (bytebufferwrapper == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportUploadedFileNotValid", locale));
    }
    byte[] wrapper = bytebufferwrapper.array();
    // read the bytes into a reader
    BufferedReader reader = new BufferedReader(new StringReader(new String(wrapper, UtilIO.getUtf8())));
    List<Object> errors = new LinkedList<>();
    int lines = 0;
    String line;
    // read the uploaded file and process each line
    try {
        while ((line = reader.readLine()) != null) {
            if (line.length() > 0 && !line.startsWith("#")) {
                if (UtilValidate.isEmail(line)) {
                    // valid email address
                    Map<String, Object> result = dispatcher.runSync("createProductPromoCodeEmail", UtilMisc.<String, Object>toMap("productPromoCodeId", productPromoCodeId, "emailAddress", line, "userLogin", userLogin));
                    if (result != null && ServiceUtil.isError(result)) {
                        errors.add(line + ": " + ServiceUtil.getErrorMessage(result));
                    }
                } else {
                    // not valid ignore and notify
                    errors.add(line + ": is not a valid email address");
                }
                ++lines;
            }
        }
    } catch (IOException | GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }
    // return errors or success
    if (errors.size() > 0) {
        return ServiceUtil.returnError(errors);
    } else if (lines == 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportEmptyFile", locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) LinkedList(java.util.LinkedList) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)427 GenericValue (org.apache.ofbiz.entity.GenericValue)356 Delegator (org.apache.ofbiz.entity.Delegator)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)321 Locale (java.util.Locale)296 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)270 HashMap (java.util.HashMap)214 BigDecimal (java.math.BigDecimal)135 GeneralException (org.apache.ofbiz.base.util.GeneralException)87 Timestamp (java.sql.Timestamp)81 LinkedList (java.util.LinkedList)79 IOException (java.io.IOException)59 Map (java.util.Map)51 HttpSession (javax.servlet.http.HttpSession)49 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)28 ModelService (org.apache.ofbiz.service.ModelService)28 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)24 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)23 Security (org.apache.ofbiz.security.Security)20 ByteBuffer (java.nio.ByteBuffer)19