Search in sources :

Example 1 with EntityCondition

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

the class FedexConnectException method fedexSubscriptionRequest.

/*
    * Register a Fedex account for shipping by obtaining the meter number
    */
public static Map<String, Object> fedexSubscriptionRequest(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");
    List<Object> errorList = new LinkedList<Object>();
    Boolean replaceMeterNumber = (Boolean) context.get("replaceMeterNumber");
    if (!replaceMeterNumber.booleanValue()) {
        String meterNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessMeterNumber", resource, "shipment.fedex.access.meterNumber");
        if (UtilValidate.isNotEmpty(meterNumber)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexMeterNumberAlreadyExists", UtilMisc.toMap("meterNumber", meterNumber), locale));
        }
    }
    String companyPartyId = (String) context.get("companyPartyId");
    String contactPartyName = (String) context.get("contactPartyName");
    Map<String, Object> result = new HashMap<String, Object>();
    String accountNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessAccountNbr", resource, "shipment.fedex.access.accountNbr");
    if (UtilValidate.isEmpty(accountNumber)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexAccountNumberNotFound", locale));
    }
    if (UtilValidate.isEmpty(contactPartyName)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexContactNameCannotBeEmpty", locale));
    }
    String companyName = null;
    GenericValue postalAddress = null;
    String phoneNumber = null;
    String faxNumber = null;
    String emailAddress = null;
    try {
        // Make sure the company exists
        GenericValue companyParty = EntityQuery.use(delegator).from("Party").where("partyId", companyPartyId).cache().queryOne();
        if (companyParty == null) {
            String errorMessage = "Party with partyId " + companyPartyId + " does not exist";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyDoesNotExists", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        // Get the company name (required by Fedex)
        companyName = PartyHelper.getPartyName(companyParty);
        if (UtilValidate.isEmpty(companyName)) {
            String errorMessage = "Party with partyId " + companyPartyId + " has no name";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyHasNoName", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        // Get the contact information for the company
        List<GenericValue> partyContactDetails = EntityQuery.use(delegator).from("PartyContactDetailByPurpose").where("partyId", companyPartyId).filterByDate(UtilDateTime.nowTimestamp(), "fromDate", "thruDate", "purposeFromDate", "purposeThruDate").queryList();
        // Get the first valid postal address (address1, city, postalCode and countryGeoId are required by Fedex)
        List<EntityCondition> postalAddressConditions = new LinkedList<EntityCondition>();
        postalAddressConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "POSTAL_ADDRESS"));
        postalAddressConditions.add(EntityCondition.makeCondition("address1", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("address1", EntityOperator.NOT_EQUAL, ""));
        postalAddressConditions.add(EntityCondition.makeCondition("city", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("city", EntityOperator.NOT_EQUAL, ""));
        postalAddressConditions.add(EntityCondition.makeCondition("postalCode", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("postalCode", EntityOperator.NOT_EQUAL, ""));
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> postalAddresses = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(postalAddressConditions, EntityOperator.AND));
        // Fedex requires USA or Canada addresses to have a state/province ID, so filter out the ones without
        postalAddressConditions.clear();
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.IN, UtilMisc.toList("CAN", "USA")));
        postalAddressConditions.add(EntityCondition.makeCondition("stateProvinceGeoId", EntityOperator.EQUALS, null));
        postalAddresses = EntityUtil.filterOutByCondition(postalAddresses, EntityCondition.makeCondition(postalAddressConditions, EntityOperator.AND));
        postalAddressConditions.clear();
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.IN, UtilMisc.toList("CAN", "USA")));
        postalAddressConditions.add(EntityCondition.makeCondition("stateProvinceGeoId", EntityOperator.EQUALS, ""));
        postalAddresses = EntityUtil.filterOutByCondition(postalAddresses, EntityCondition.makeCondition(postalAddressConditions, EntityOperator.AND));
        postalAddress = EntityUtil.getFirst(postalAddresses);
        if (UtilValidate.isEmpty(postalAddress)) {
            String errorMessage = "Party with partyId " + companyPartyId + " does not have a current, fully populated postal address";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyHasNotPostalAddress", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        GenericValue countryGeo = EntityQuery.use(delegator).from("Geo").where("geoId", postalAddress.getString("countryGeoId")).cache().queryOne();
        String countryCode = countryGeo.getString("geoCode");
        String stateOrProvinceCode = null;
        // Only add the StateOrProvinceCode element if the address is in USA or Canada
        if ("CA".equals(countryCode) || "US".equals(countryCode)) {
            GenericValue stateProvinceGeo = EntityQuery.use(delegator).from("Geo").where("geoId", postalAddress.getString("stateProvinceGeoId")).cache().queryOne();
            stateOrProvinceCode = stateProvinceGeo.getString("geoCode");
        }
        // Get the first valid primary phone number (required by Fedex)
        List<EntityCondition> phoneNumberConditions = new LinkedList<EntityCondition>();
        phoneNumberConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "TELECOM_NUMBER"));
        phoneNumberConditions.add(EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.EQUALS, "PRIMARY_PHONE"));
        phoneNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, null));
        phoneNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, ""));
        phoneNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, null));
        phoneNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> phoneNumbers = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(phoneNumberConditions, EntityOperator.AND));
        GenericValue phoneNumberValue = EntityUtil.getFirst(phoneNumbers);
        if (UtilValidate.isEmpty(phoneNumberValue)) {
            String errorMessage = "Party with partyId " + companyPartyId + " does not have a current, fully populated primary phone number";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyHasNotPrimaryPhoneNumber", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        phoneNumber = phoneNumberValue.getString("areaCode") + phoneNumberValue.getString("contactNumber");
        // Fedex doesn't want the North American country code
        if (UtilValidate.isNotEmpty(phoneNumberValue.getString("countryCode")) && !("CA".equals(countryCode) || "US".equals(countryCode))) {
            phoneNumber = phoneNumberValue.getString("countryCode") + phoneNumber;
        }
        phoneNumber = phoneNumber.replaceAll("[^+\\d]", "");
        // Get the first valid fax number
        List<EntityCondition> faxNumberConditions = new LinkedList<EntityCondition>();
        faxNumberConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "TELECOM_NUMBER"));
        faxNumberConditions.add(EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.EQUALS, "FAX_NUMBER"));
        faxNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, null));
        faxNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, ""));
        faxNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, null));
        faxNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> faxNumbers = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(faxNumberConditions, EntityOperator.AND));
        GenericValue faxNumberValue = EntityUtil.getFirst(faxNumbers);
        if (!UtilValidate.isEmpty(faxNumberValue)) {
            faxNumber = faxNumberValue.getString("areaCode") + faxNumberValue.getString("contactNumber");
            // Fedex doesn't want the North American country code
            if (UtilValidate.isNotEmpty(faxNumberValue.getString("countryCode")) && !("CA".equals(countryCode) || "US".equals(countryCode))) {
                faxNumber = faxNumberValue.getString("countryCode") + faxNumber;
            }
            faxNumber = faxNumber.replaceAll("[^+\\d]", "");
        }
        // Get the first valid email address
        List<EntityCondition> emailConditions = new LinkedList<EntityCondition>();
        emailConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "EMAIL_ADDRESS"));
        emailConditions.add(EntityCondition.makeCondition("infoString", EntityOperator.NOT_EQUAL, null));
        emailConditions.add(EntityCondition.makeCondition("infoString", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> emailAddresses = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(emailConditions, EntityOperator.AND));
        GenericValue emailAddressValue = EntityUtil.getFirst(emailAddresses);
        if (!UtilValidate.isEmpty(emailAddressValue)) {
            emailAddress = emailAddressValue.getString("infoString");
        }
        // Get the location of the Freemarker (XML) template for the FDXSubscriptionRequest
        String templateLocation = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "templateSubscription", resource, "shipment.fedex.template.subscription.location");
        if (UtilValidate.isEmpty(templateLocation)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateLocationNotFound", UtilMisc.toMap("templateLocation", templateLocation), locale));
        }
        // Populate the Freemarker context
        Map<String, Object> subscriptionRequestContext = new HashMap<String, Object>();
        subscriptionRequestContext.put("AccountNumber", accountNumber);
        subscriptionRequestContext.put("PersonName", contactPartyName);
        subscriptionRequestContext.put("CompanyName", companyName);
        subscriptionRequestContext.put("PhoneNumber", phoneNumber);
        if (UtilValidate.isNotEmpty(faxNumber)) {
            subscriptionRequestContext.put("FaxNumber", faxNumber);
        }
        if (UtilValidate.isNotEmpty(emailAddress)) {
            subscriptionRequestContext.put("EMailAddress", emailAddress);
        }
        subscriptionRequestContext.put("Line1", postalAddress.getString("address1"));
        if (UtilValidate.isNotEmpty(postalAddress.getString("address2"))) {
            subscriptionRequestContext.put("Line2", postalAddress.getString("address2"));
        }
        subscriptionRequestContext.put("City", postalAddress.getString("city"));
        if (UtilValidate.isNotEmpty(stateOrProvinceCode)) {
            subscriptionRequestContext.put("StateOrProvinceCode", stateOrProvinceCode);
        }
        subscriptionRequestContext.put("PostalCode", postalAddress.getString("postalCode"));
        subscriptionRequestContext.put("CountryCode", countryCode);
        StringWriter outWriter = new StringWriter();
        try {
            FreeMarkerWorker.renderTemplate(templateLocation, subscriptionRequestContext, outWriter);
        } catch (Exception e) {
            String errorMessage = "Cannot send Fedex subscription request: Failed to render Fedex XML Subscription Request Template [" + templateLocation + "].";
            Debug.logError(e, errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateError", UtilMisc.toMap("templateLocation", templateLocation, "errorString", e.getMessage()), locale));
        }
        String fDXSubscriptionRequestString = outWriter.toString();
        // Send the request
        String fDXSubscriptionReplyString = null;
        try {
            fDXSubscriptionReplyString = sendFedexRequest(fDXSubscriptionRequestString, delegator, shipmentGatewayConfigId, resource, locale);
            Debug.logInfo("Fedex response for FDXSubscriptionRequest:" + fDXSubscriptionReplyString, module);
        } catch (FedexConnectException e) {
            String errorMessage = "Error sending Fedex request for FDXSubscriptionRequest: " + e.toString();
            Debug.logError(e, errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateSendingError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        Document fDXSubscriptionReplyDocument = null;
        try {
            fDXSubscriptionReplyDocument = UtilXml.readXmlDocument(fDXSubscriptionReplyString, false);
            Debug.logInfo("Fedex response for FDXSubscriptionRequest:" + fDXSubscriptionReplyString, module);
        } catch (SAXException | ParserConfigurationException | IOException e) {
            String errorMessage = "Error parsing the FDXSubscriptionRequest response: " + e.toString();
            Debug.logError(e, errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateParsingError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        Element fedexSubscriptionReplyElement = fDXSubscriptionReplyDocument.getDocumentElement();
        handleErrors(fedexSubscriptionReplyElement, errorList, locale);
        if (UtilValidate.isNotEmpty(errorList)) {
            return ServiceUtil.returnError(errorList);
        }
        String meterNumber = UtilXml.childElementValue(fedexSubscriptionReplyElement, "MeterNumber");
        result.put("meterNumber", meterNumber);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) LinkedList(java.util.LinkedList) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 2 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition 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 3 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition 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 4 with EntityCondition

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

the class InventoryWorker method getOutstandingProductQuantities.

/**
 * Gets the quanitty of each product in the order that is outstanding across all orders of the given input type.
 * Uses the OrderItemQuantityReportGroupByProduct view entity.
 *
 * @param   productIds  Collection of disticnt productIds in an order. Use OrderReadHelper.getOrderProductIds()
 * @param   orderTypeId Either "SALES_ORDER" or "PURCHASE_ORDER"
 * @param   delegator   The delegator to use
 * @return  Map of productIds to quantities outstanding.
 */
public static Map<String, BigDecimal> getOutstandingProductQuantities(Collection<String> productIds, String orderTypeId, Delegator delegator) {
    Set<String> fieldsToSelect = UtilMisc.toSet("productId", "quantityOpen");
    List<EntityCondition> condList = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, orderTypeId), EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"), EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"), EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED"));
    if (productIds.size() > 0) {
        condList.add(EntityCondition.makeCondition("productId", EntityOperator.IN, productIds));
    }
    condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"));
    condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
    condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"));
    EntityConditionList<EntityCondition> conditions = EntityCondition.makeCondition(condList, EntityOperator.AND);
    Map<String, BigDecimal> results = new HashMap<>();
    try {
        List<GenericValue> orderedProducts = EntityQuery.use(delegator).select(fieldsToSelect).from("OrderItemQuantityReportGroupByProduct").where(conditions).queryList();
        for (GenericValue value : orderedProducts) {
            results.put(value.getString("productId"), value.getBigDecimal("quantityOpen"));
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    return results;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) BigDecimal(java.math.BigDecimal)

Example 5 with EntityCondition

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

the class ProductEvents method updateAllKeywords.

/**
 * Updates/adds keywords for all products
 *
 * @param request HTTPRequest object for the current request
 * @param response HTTPResponse object for the current request
 * @return String specifying the exit status of this event
 */
public static String updateAllKeywords(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Security security = (Security) request.getAttribute("security");
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    String updateMode = "CREATE";
    String errMsg = null;
    String doAll = request.getParameter("doAll");
    // check permissions before moving on...
    if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
        errMsg = UtilProperties.getMessage(resource, "productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    EntityCondition condition = null;
    if (!"Y".equals(doAll)) {
        List<EntityCondition> condList = new LinkedList<>();
        condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N")));
        if ("true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore.variants", delegator))) {
            condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("isVariant", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("isVariant", EntityOperator.NOT_EQUAL, "Y")));
        }
        if ("true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore.discontinued.sales", delegator))) {
            condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp)));
        }
        condition = EntityCondition.makeCondition(condList, EntityOperator.AND);
    } else {
        condition = EntityCondition.makeCondition(EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N"));
    }
    int numProds = 0;
    int errProds = 0;
    boolean beganTx = false;
    try {
        // begin the transaction
        beganTx = TransactionUtil.begin(7200);
    } catch (GenericTransactionException gte) {
        Debug.logError(gte, "Unable to begin transaction", module);
    }
    try (EntityListIterator entityListIterator = EntityQuery.use(delegator).from("Product").where(condition).queryIterator()) {
        try {
            if (Debug.infoOn()) {
                long count = EntityQuery.use(delegator).from("Product").where(condition).queryCount();
                Debug.logInfo("========== Found " + count + " products to index ==========", module);
            }
        } catch (GenericEntityException gee) {
            Debug.logWarning(gee, gee.getMessage(), module);
            Map<String, String> messageMap = UtilMisc.toMap("gee", gee.toString());
            errMsg = UtilProperties.getMessage(resource, "productevents.error_getting_product_list", messageMap, UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        GenericValue product;
        while ((product = entityListIterator.next()) != null) {
            try {
                KeywordIndex.indexKeywords(product, "Y".equals(doAll));
            } catch (GenericEntityException e) {
                Debug.logWarning("[ProductEvents.updateAllKeywords] Could not create product-keyword (write error); message: " + e.getMessage(), module);
                errProds++;
            }
            numProds++;
            if (numProds % 500 == 0) {
                Debug.logInfo("Keywords indexed for " + numProds + " so far", module);
            }
        }
    } catch (GenericEntityException e) {
        try {
            TransactionUtil.rollback(beganTx, e.getMessage(), e);
        } catch (GenericTransactionException e1) {
            Debug.logError(e1, module);
        }
        return "error";
    } catch (Throwable t) {
        Debug.logError(t, module);
        request.setAttribute("_ERROR_MESSAGE_", t.getMessage());
        try {
            TransactionUtil.rollback(beganTx, t.getMessage(), t);
        } catch (GenericTransactionException e2) {
            Debug.logError(e2, module);
        }
        return "error";
    }
    // commit the transaction
    try {
        TransactionUtil.commit(beganTx);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    if (errProds == 0) {
        Map<String, String> messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
        errMsg = UtilProperties.getMessage(resource, "productevents.keyword_creation_complete_for_products", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
        return "success";
    } else {
        Map<String, String> messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
        messageMap.put("errProds", Integer.toString(errProds));
        errMsg = UtilProperties.getMessage(resource, "productevents.keyword_creation_complete_for_products_with_errors", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashMap(java.util.HashMap) Map(java.util.Map)

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