Search in sources :

Example 16 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class ProductSearchSession method getCountForListPriceRange.

/**
 * This method returns count of products within a given price range, the constraint being
 * applied on current ProductSearchConstraint list in session.
 * @param priceLow The low price.
 * @param priceHigh The high price.
 * @param session Current session.
 * @param delegator The delegator object.
 * @return The long value of count of products.
 */
public static long getCountForListPriceRange(BigDecimal priceLow, BigDecimal priceHigh, HttpSession session, Delegator delegator) {
    String visitId = VisitHandler.getVisitId(session);
    ProductSearchContext productSearchContext = new ProductSearchContext(delegator, visitId);
    List<ProductSearchConstraint> productSearchConstraintList = ProductSearchOptions.getConstraintList(session);
    if (UtilValidate.isNotEmpty(productSearchConstraintList)) {
        productSearchContext.addProductSearchConstraints(productSearchConstraintList);
    }
    productSearchContext.finishKeywordConstraints();
    productSearchContext.finishCategoryAndFeatureConstraints();
    DynamicViewEntity dynamicViewEntity = productSearchContext.dynamicViewEntity;
    List<EntityCondition> entityConditionList = productSearchContext.entityConditionList;
    List<String> fieldsToSelect = new LinkedList<>();
    dynamicViewEntity.addMemberEntity("PPC", "ProductPrice");
    dynamicViewEntity.addAlias("PPC", "ppcProductPriceTypeId", "productPriceTypeId", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "ppcFromDate", "fromDate", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "ppcThruDate", "thruDate", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "ppcPrice", "price", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "priceRangeCount", "productId", null, null, null, "count-distinct");
    dynamicViewEntity.addViewLink("PROD", "PPC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("productId"));
    fieldsToSelect.add("priceRangeCount");
    entityConditionList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("ppcThruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("ppcThruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp())));
    entityConditionList.add(EntityCondition.makeCondition("ppcFromDate", EntityOperator.LESS_THAN, UtilDateTime.nowTimestamp()));
    entityConditionList.add(EntityCondition.makeCondition("ppcPrice", EntityOperator.GREATER_THAN_EQUAL_TO, priceLow));
    entityConditionList.add(EntityCondition.makeCondition("ppcPrice", EntityOperator.LESS_THAN_EQUAL_TO, priceHigh));
    entityConditionList.add(EntityCondition.makeCondition("ppcProductPriceTypeId", EntityOperator.EQUALS, "LIST_PRICE"));
    Long priceRangeCount = Long.valueOf(0);
    EntityQuery eq = EntityQuery.use(delegator).select(UtilMisc.toSet(fieldsToSelect)).from(dynamicViewEntity).where(entityConditionList).orderBy(productSearchContext.orderByList).cursorScrollInsensitive();
    try (EntityListIterator eli = eq.queryIterator()) {
        GenericValue searchResult = null;
        while ((searchResult = eli.next()) != null) {
            priceRangeCount = searchResult.getLong("priceRangeCount");
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error in product search", module);
    }
    return priceRangeCount;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ProductSearchContext(org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)

Example 17 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class CategoryServices method getProductCategoryAndLimitedMembers.

public static Map<String, Object> getProductCategoryAndLimitedMembers(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String productCategoryId = (String) context.get("productCategoryId");
    boolean limitView = ((Boolean) context.get("limitView")).booleanValue();
    int defaultViewSize = ((Integer) context.get("defaultViewSize")).intValue();
    Timestamp introductionDateLimit = (Timestamp) context.get("introductionDateLimit");
    Timestamp releaseDateLimit = (Timestamp) context.get("releaseDateLimit");
    List<String> orderByFields = UtilGenerics.checkList(context.get("orderByFields"));
    if (orderByFields == null)
        orderByFields = new LinkedList<String>();
    String entityName = getCategoryFindEntityName(delegator, orderByFields, introductionDateLimit, releaseDateLimit);
    String prodCatalogId = (String) context.get("prodCatalogId");
    boolean useCacheForMembers = (context.get("useCacheForMembers") == null || ((Boolean) context.get("useCacheForMembers")).booleanValue());
    boolean activeOnly = (context.get("activeOnly") == null || ((Boolean) context.get("activeOnly")).booleanValue());
    // checkViewAllow defaults to false, must be set to true and pass the prodCatalogId to enable
    boolean checkViewAllow = (prodCatalogId != null && context.get("checkViewAllow") != null && ((Boolean) context.get("checkViewAllow")).booleanValue());
    String viewProductCategoryId = null;
    if (checkViewAllow) {
        viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, prodCatalogId);
    }
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    int viewIndex = 0;
    try {
        viewIndex = Integer.parseInt((String) context.get("viewIndexString"));
    } catch (Exception e) {
        viewIndex = 0;
    }
    int viewSize = defaultViewSize;
    try {
        viewSize = Integer.parseInt((String) context.get("viewSizeString"));
    } catch (NumberFormatException e) {
        Debug.logError(e.getMessage(), module);
    }
    GenericValue productCategory = null;
    try {
        productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).cache().queryOne();
    } catch (GenericEntityException e) {
        Debug.logWarning(e.getMessage(), module);
        productCategory = null;
    }
    int listSize = 0;
    int lowIndex = 0;
    int highIndex = 0;
    if (limitView) {
        // get the indexes for the partial list
        lowIndex = ((viewIndex * viewSize) + 1);
        highIndex = (viewIndex + 1) * viewSize;
    } else {
        lowIndex = 0;
        highIndex = 0;
    }
    boolean filterOutOfStock = false;
    try {
        String productStoreId = (String) context.get("productStoreId");
        if (UtilValidate.isNotEmpty(productStoreId)) {
            GenericValue productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).queryOne();
            if (productStore != null && "N".equals(productStore.getString("showOutOfStockProducts"))) {
                filterOutOfStock = true;
            }
        }
    } catch (GenericEntityException e) {
        Debug.logWarning(e.getMessage(), module);
    }
    List<GenericValue> productCategoryMembers = null;
    if (productCategory != null) {
        try {
            if (useCacheForMembers) {
                productCategoryMembers = EntityQuery.use(delegator).from(entityName).where("productCategoryId", productCategoryId).orderBy(orderByFields).cache(true).queryList();
                if (activeOnly) {
                    productCategoryMembers = EntityUtil.filterByDate(productCategoryMembers, true);
                }
                List<EntityCondition> filterConditions = new LinkedList<EntityCondition>();
                if (introductionDateLimit != null) {
                    EntityCondition condition = EntityCondition.makeCondition(EntityCondition.makeCondition("introductionDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("introductionDate", EntityOperator.LESS_THAN_EQUAL_TO, introductionDateLimit));
                    filterConditions.add(condition);
                }
                if (releaseDateLimit != null) {
                    EntityCondition condition = EntityCondition.makeCondition(EntityCondition.makeCondition("releaseDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("releaseDate", EntityOperator.LESS_THAN_EQUAL_TO, releaseDateLimit));
                    filterConditions.add(condition);
                }
                if (!filterConditions.isEmpty()) {
                    productCategoryMembers = EntityUtil.filterByCondition(productCategoryMembers, EntityCondition.makeCondition(filterConditions, EntityOperator.AND));
                }
                // filter out of stock products
                if (filterOutOfStock) {
                    try {
                        productCategoryMembers = ProductWorker.filterOutOfStockProducts(productCategoryMembers, dispatcher, delegator);
                    } catch (GeneralException e) {
                        Debug.logWarning("Problem filtering out of stock products :" + e.getMessage(), module);
                    }
                }
                // filter out the view allow before getting the sublist
                if (UtilValidate.isNotEmpty(viewProductCategoryId)) {
                    productCategoryMembers = CategoryWorker.filterProductsInCategory(delegator, productCategoryMembers, viewProductCategoryId);
                }
                // set the index and size
                listSize = productCategoryMembers.size();
                if (limitView) {
                    // limit high index to (filtered) listSize
                    if (highIndex > listSize) {
                        highIndex = listSize;
                    }
                    // if lowIndex > listSize, the input is wrong => reset to first page
                    if (lowIndex > listSize) {
                        viewIndex = 0;
                        lowIndex = 1;
                        highIndex = Math.min(viewSize, highIndex);
                    }
                    // get only between low and high indexes
                    if (UtilValidate.isNotEmpty(productCategoryMembers)) {
                        productCategoryMembers = productCategoryMembers.subList(lowIndex - 1, highIndex);
                    }
                } else {
                    lowIndex = 1;
                    highIndex = listSize;
                }
            } else {
                List<EntityCondition> mainCondList = new LinkedList<EntityCondition>();
                mainCondList.add(EntityCondition.makeCondition("productCategoryId", EntityOperator.EQUALS, productCategory.getString("productCategoryId")));
                if (activeOnly) {
                    mainCondList.add(EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp));
                    mainCondList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN, nowTimestamp)));
                }
                if (introductionDateLimit != null) {
                    mainCondList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("introductionDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("introductionDate", EntityOperator.LESS_THAN_EQUAL_TO, introductionDateLimit)));
                }
                if (releaseDateLimit != null) {
                    mainCondList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("releaseDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("releaseDate", EntityOperator.LESS_THAN_EQUAL_TO, releaseDateLimit)));
                }
                EntityCondition mainCond = EntityCondition.makeCondition(mainCondList, EntityOperator.AND);
                // set distinct on using list iterator
                EntityQuery eq = EntityQuery.use(delegator).from(entityName).where(mainCond).orderBy(orderByFields).cursorScrollInsensitive().maxRows(highIndex);
                try (EntityListIterator pli = eq.queryIterator()) {
                    // get the partial list for this page
                    if (limitView) {
                        if (viewProductCategoryId != null) {
                            // do manual checking to filter view allow
                            productCategoryMembers = new LinkedList<GenericValue>();
                            GenericValue nextValue;
                            int chunkSize = 0;
                            listSize = 0;
                            while ((nextValue = pli.next()) != null) {
                                String productId = nextValue.getString("productId");
                                if (CategoryWorker.isProductInCategory(delegator, productId, viewProductCategoryId)) {
                                    if (listSize + 1 >= lowIndex && chunkSize < viewSize) {
                                        productCategoryMembers.add(nextValue);
                                        chunkSize++;
                                    }
                                    listSize++;
                                }
                            }
                        } else {
                            productCategoryMembers = pli.getPartialList(lowIndex, viewSize);
                            listSize = pli.getResultsSizeAfterPartialList();
                        }
                    } else {
                        productCategoryMembers = pli.getCompleteList();
                        if (UtilValidate.isNotEmpty(viewProductCategoryId)) {
                            // filter out the view allow
                            productCategoryMembers = CategoryWorker.filterProductsInCategory(delegator, productCategoryMembers, viewProductCategoryId);
                        }
                        listSize = productCategoryMembers.size();
                        lowIndex = 1;
                        highIndex = listSize;
                    }
                }
                // filter out of stock products
                if (filterOutOfStock) {
                    try {
                        productCategoryMembers = ProductWorker.filterOutOfStockProducts(productCategoryMembers, dispatcher, delegator);
                        listSize = productCategoryMembers.size();
                    } catch (GeneralException e) {
                        Debug.logWarning("Problem filtering out of stock products :" + e.getMessage(), module);
                    }
                }
                // null safety
                if (productCategoryMembers == null) {
                    productCategoryMembers = new LinkedList<GenericValue>();
                }
                if (highIndex > listSize) {
                    highIndex = listSize;
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("viewIndex", Integer.valueOf(viewIndex));
    result.put("viewSize", Integer.valueOf(viewSize));
    result.put("lowIndex", Integer.valueOf(lowIndex));
    result.put("highIndex", Integer.valueOf(highIndex));
    result.put("listSize", Integer.valueOf(listSize));
    if (productCategory != null)
        result.put("productCategory", productCategory);
    if (productCategoryMembers != null)
        result.put("productCategoryMembers", productCategoryMembers);
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 18 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class OrderServices method createAlsoBoughtProductAssocs.

public static Map<String, Object> createAlsoBoughtProductAssocs(DispatchContext dctx, Map<String, ? extends Object> context) {
    final Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    // All orders with an entryDate > orderEntryFromDateTime will be processed
    Timestamp orderEntryFromDateTime = (Timestamp) context.get("orderEntryFromDateTime");
    // If true all orders ever created will be processed and any pre-existing ALSO_BOUGHT ProductAssocs will be expired
    boolean processAllOrders = context.get("processAllOrders") == null ? false : (Boolean) context.get("processAllOrders");
    if (orderEntryFromDateTime == null && !processAllOrders) {
        // No from date supplied, check to see when this service last ran and use the startDateTime
        // FIXME: This code is unreliable - the JobSandbox value might have been purged. Use another mechanism to persist orderEntryFromDateTime.
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toMap("statusId", "SERVICE_FINISHED", "serviceName", "createAlsoBoughtProductAssocs"));
        EntityFindOptions efo = new EntityFindOptions();
        efo.setMaxRows(1);
        try {
            GenericValue lastRunJobSandbox = EntityUtil.getFirst(delegator.findList("JobSandbox", cond, null, UtilMisc.toList("startDateTime DESC"), efo, false));
            if (lastRunJobSandbox != null) {
                orderEntryFromDateTime = lastRunJobSandbox.getTimestamp("startDateTime");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (orderEntryFromDateTime == null) {
            // Still null, process all orders
            processAllOrders = true;
        }
    }
    if (processAllOrders) {
        // Expire any pre-existing ALSO_BOUGHT ProductAssocs in preparation for reprocessing
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productAssocTypeId", "ALSO_BOUGHT"), EntityCondition.makeConditionDate("fromDate", "thruDate")));
        try {
            delegator.storeByCondition("ProductAssoc", UtilMisc.toMap("thruDate", UtilDateTime.nowTimestamp()), cond);
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    List<EntityExpr> orderCondList = UtilMisc.toList(EntityCondition.makeCondition("orderTypeId", "SALES_ORDER"));
    if (!processAllOrders && orderEntryFromDateTime != null) {
        orderCondList.add(EntityCondition.makeCondition("entryDate", EntityOperator.GREATER_THAN, orderEntryFromDateTime));
    }
    final EntityCondition cond = EntityCondition.makeCondition(orderCondList);
    List<String> orderIds;
    try {
        orderIds = TransactionUtil.doNewTransaction(new Callable<List<String>>() {

            @Override
            public List<String> call() throws Exception {
                List<String> orderIds = new LinkedList<>();
                EntityQuery eq = EntityQuery.use(delegator).select("orderId").from("OrderHeader").where(cond).orderBy("entryDate ASC");
                try (EntityListIterator eli = eq.queryIterator()) {
                    GenericValue orderHeader;
                    while ((orderHeader = eli.next()) != null) {
                        orderIds.add(orderHeader.getString("orderId"));
                    }
                }
                return orderIds;
            }
        }, "getSalesOrderIds", 0, true);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    for (String orderId : orderIds) {
        Map<String, Object> svcIn = new HashMap<>();
        svcIn.put("userLogin", context.get("userLogin"));
        svcIn.put("orderId", orderId);
        try {
            Map<String, Object> serviceResult = dispatcher.runSync("createAlsoBoughtProductAssocsForOrder", svcIn);
            if (ServiceUtil.isError(serviceResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
            }
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) Callable(java.util.concurrent.Callable) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 19 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class CommunicationEventServices method sendEmailToContactList.

public static Map<String, Object> sendEmailToContactList(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<Object> errorMessages = new LinkedList<>();
    String errorCallingUpdateContactListPartyService = UtilProperties.getMessage(resource, "commeventservices.errorCallingUpdateContactListPartyService", locale);
    String errorCallingSendMailService = UtilProperties.getMessage(resource, "commeventservices.errorCallingSendMailService", locale);
    String errorInSendEmailToContactListService = UtilProperties.getMessage(resource, "commeventservices.errorInSendEmailToContactListService", locale);
    String skippingInvalidEmailAddress = UtilProperties.getMessage(resource, "commeventservices.skippingInvalidEmailAddress", locale);
    String contactListId = (String) context.get("contactListId");
    String communicationEventId = (String) context.get("communicationEventId");
    // Any exceptions thrown in this block will cause the service to return error
    try {
        GenericValue communicationEvent = EntityQuery.use(delegator).from("CommunicationEvent").where("communicationEventId", communicationEventId).queryOne();
        GenericValue contactList = EntityQuery.use(delegator).from("ContactList").where("contactListId", contactListId).queryOne();
        Map<String, Object> sendMailParams = new HashMap<>();
        sendMailParams.put("sendFrom", communicationEvent.getRelatedOne("FromContactMech", false).getString("infoString"));
        sendMailParams.put("subject", communicationEvent.getString("subject"));
        sendMailParams.put("contentType", communicationEvent.getString("contentMimeTypeId"));
        sendMailParams.put("userLogin", userLogin);
        // Find a list of distinct email addresses from active, ACCEPTED parties in the contact list
        // using a list iterator (because there can be a large number)
        List<EntityCondition> conditionList = UtilMisc.toList(EntityCondition.makeCondition("contactListId", EntityOperator.EQUALS, contactList.get("contactListId")), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "CLPT_ACCEPTED"), EntityCondition.makeCondition("preferredContactMechId", EntityOperator.NOT_EQUAL, null), EntityUtil.getFilterByDateExpr(), EntityUtil.getFilterByDateExpr("contactFromDate", "contactThruDate"));
        EntityQuery eq = EntityQuery.use(delegator).select("partyId", "preferredContactMechId", "fromDate", "infoString").from("ContactListPartyAndContactMech").where(EntityCondition.makeCondition(conditionList, EntityOperator.AND)).cursorScrollInsensitive().distinct();
        try (EntityListIterator eli = eq.queryIterator()) {
            // loop through the list iterator
            for (GenericValue contactListPartyAndContactMech; (contactListPartyAndContactMech = eli.next()) != null; ) {
                Debug.logInfo("Contact info: " + contactListPartyAndContactMech, module);
                // only be logged and not cause the service to return an error
                try {
                    String emailAddress = contactListPartyAndContactMech.getString("infoString");
                    if (UtilValidate.isEmpty(emailAddress)) {
                        continue;
                    }
                    emailAddress = emailAddress.trim();
                    if (!UtilValidate.isEmail(emailAddress)) {
                        // If validation fails, just log and skip the email address
                        Debug.logError(skippingInvalidEmailAddress + ": " + emailAddress, module);
                        errorMessages.add(skippingInvalidEmailAddress + ": " + emailAddress);
                        continue;
                    }
                    // Because we're retrieving infoString only above (so as not to pollute the distinctness), we
                    // need to retrieve the partyId it's related to. Since this could be multiple parties, get
                    // only the most recent valid one via ContactListPartyAndContactMech.
                    List<EntityCondition> clpConditionList = UtilMisc.makeListWritable(conditionList);
                    clpConditionList.add(EntityCondition.makeCondition("infoString", EntityOperator.EQUALS, emailAddress));
                    GenericValue lastContactListPartyACM = EntityQuery.use(delegator).from("ContactListPartyAndContactMech").where(EntityCondition.makeCondition(clpConditionList, EntityOperator.AND)).orderBy("-fromDate").cache(true).queryFirst();
                    if (lastContactListPartyACM == null) {
                        continue;
                    }
                    String partyId = lastContactListPartyACM.getString("partyId");
                    sendMailParams.put("sendTo", emailAddress);
                    sendMailParams.put("partyId", partyId);
                    // Retrieve a record for this contactMechId from ContactListCommStatus
                    Map<String, String> contactListCommStatusRecordMap = UtilMisc.toMap("contactListId", contactListId, "communicationEventId", communicationEventId, "contactMechId", lastContactListPartyACM.getString("preferredContactMechId"));
                    GenericValue contactListCommStatusRecord = EntityQuery.use(delegator).from("ContactListCommStatus").where(contactListCommStatusRecordMap).queryOne();
                    if (contactListCommStatusRecord == null) {
                        // No attempt has been made previously to send to this address, so create a record to reflect
                        // the beginning of the current attempt
                        Map<String, String> newContactListCommStatusRecordMap = UtilMisc.makeMapWritable(contactListCommStatusRecordMap);
                        newContactListCommStatusRecordMap.put("statusId", "COM_IN_PROGRESS");
                        newContactListCommStatusRecordMap.put("partyId", partyId);
                        contactListCommStatusRecord = delegator.create("ContactListCommStatus", newContactListCommStatusRecordMap);
                    } else if (contactListCommStatusRecord.get("statusId") != null && "COM_COMPLETE".equals(contactListCommStatusRecord.getString("statusId"))) {
                        // There was a successful earlier attempt, so skip this address
                        continue;
                    }
                    // Send e-mail
                    Debug.logInfo("Sending email to contact list [" + contactListId + "] party [" + partyId + "] : " + emailAddress, module);
                    // Make the attempt to send the email to the address
                    Map<String, Object> tmpResult = null;
                    // Retrieve a contact list party status
                    GenericValue contactListPartyStatus = EntityQuery.use(delegator).from("ContactListPartyStatus").where("contactListId", contactListId, "partyId", contactListPartyAndContactMech.getString("partyId"), "fromDate", contactListPartyAndContactMech.getTimestamp("fromDate"), "statusId", "CLPT_ACCEPTED").queryFirst();
                    if (contactListPartyStatus != null) {
                        // prepare body parameters
                        Map<String, Object> bodyParameters = new HashMap<>();
                        bodyParameters.put("contactListId", contactListId);
                        bodyParameters.put("partyId", contactListPartyAndContactMech.getString("partyId"));
                        bodyParameters.put("preferredContactMechId", contactListPartyAndContactMech.getString("preferredContactMechId"));
                        bodyParameters.put("emailAddress", emailAddress);
                        bodyParameters.put("fromDate", contactListPartyAndContactMech.getTimestamp("fromDate"));
                        bodyParameters.put("optInVerifyCode", contactListPartyStatus.getString("optInVerifyCode"));
                        bodyParameters.put("content", communicationEvent.getString("content"));
                        NotificationServices.setBaseUrl(delegator, contactList.getString("verifyEmailWebSiteId"), bodyParameters);
                        GenericValue webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", contactList.getString("verifyEmailWebSiteId")).queryOne();
                        if (webSite != null) {
                            GenericValue productStore = webSite.getRelatedOne("ProductStore", false);
                            if (productStore != null) {
                                List<GenericValue> productStoreEmailSettings = productStore.getRelated("ProductStoreEmailSetting", UtilMisc.toMap("emailType", "CONT_EMAIL_TEMPLATE"), null, false);
                                GenericValue productStoreEmailSetting = EntityUtil.getFirst(productStoreEmailSettings);
                                if (productStoreEmailSetting != null) {
                                    // send e-mail using screen template
                                    sendMailParams.put("bodyScreenUri", productStoreEmailSetting.getString("bodyScreenLocation"));
                                    sendMailParams.put("bodyParameters", bodyParameters);
                                    sendMailParams.remove("body");
                                    tmpResult = dispatcher.runSync("sendMailFromScreen", sendMailParams, 360, true);
                                    if (ServiceUtil.isError(tmpResult)) {
                                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult));
                                    }
                                }
                            }
                        }
                    }
                    // If the e-mail does not be sent then send normal e-mail
                    if (UtilValidate.isEmpty(tmpResult)) {
                        sendMailParams.put("body", communicationEvent.getString("content"));
                        tmpResult = dispatcher.runSync("sendMail", sendMailParams, 360, true);
                        if (ServiceUtil.isError(tmpResult)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult));
                        }
                    }
                    if (tmpResult == null || ServiceUtil.isError(tmpResult)) {
                        if (ServiceUtil.getErrorMessage(tmpResult).startsWith("[ADDRERR]")) {
                            // address error; mark the communication event as BOUNCED
                            contactListCommStatusRecord.set("statusId", "COM_BOUNCED");
                            try {
                                contactListCommStatusRecord.store();
                            } catch (GenericEntityException e) {
                                Debug.logError(e, module);
                                errorMessages.add(e.getMessage());
                            }
                            // deactivate from the contact list
                            try {
                                GenericValue contactListParty = contactListPartyAndContactMech.getRelatedOne("ContactListParty", false);
                                if (contactListParty != null) {
                                    contactListParty.set("statusId", "CLPT_INVALID");
                                    contactListParty.store();
                                }
                            } catch (GenericEntityException e) {
                                Debug.logError(e, module);
                                errorMessages.add(e.getMessage());
                            }
                            continue;
                        }
                        // If the send attempt fails, just log and skip the email address
                        Debug.logError(errorCallingSendMailService + ": " + ServiceUtil.getErrorMessage(tmpResult), module);
                        errorMessages.add(errorCallingSendMailService + ": " + ServiceUtil.getErrorMessage(tmpResult));
                        continue;
                    }
                    // attach the parent communication event to the new event created when sending
                    // the mail
                    String thisCommEventId = (String) tmpResult.get("communicationEventId");
                    GenericValue thisCommEvent = EntityQuery.use(delegator).from("CommunicationEvent").where("communicationEventId", thisCommEventId).queryOne();
                    if (thisCommEvent != null) {
                        thisCommEvent.set("contactListId", contactListId);
                        thisCommEvent.set("parentCommEventId", communicationEventId);
                        thisCommEvent.store();
                    }
                    String messageId = (String) tmpResult.get("messageId");
                    contactListCommStatusRecord.set("messageId", messageId);
                    if ("Y".equals(contactList.get("singleUse"))) {
                        // Expire the ContactListParty if the list is single use and sendEmail finishes successfully
                        tmpResult = dispatcher.runSync("updateContactListParty", UtilMisc.toMap("contactListId", lastContactListPartyACM.get("contactListId"), "partyId", partyId, "fromDate", lastContactListPartyACM.get("fromDate"), "thruDate", UtilDateTime.nowTimestamp(), "userLogin", userLogin));
                        if (ServiceUtil.isError(tmpResult)) {
                            // If the expiry fails, just log and skip the email address
                            Debug.logError(errorCallingUpdateContactListPartyService + ": " + ServiceUtil.getErrorMessage(tmpResult), module);
                            errorMessages.add(errorCallingUpdateContactListPartyService + ": " + ServiceUtil.getErrorMessage(tmpResult));
                            continue;
                        }
                    }
                    // All is successful, so update the ContactListCommStatus record
                    contactListCommStatusRecord.set("statusId", "COM_COMPLETE");
                    delegator.store(contactListCommStatusRecord);
                // Don't return a service error just because of failure for one address - just log the error and continue
                } catch (GenericEntityException nonFatalGEE) {
                    Debug.logError(nonFatalGEE, errorInSendEmailToContactListService, module);
                    errorMessages.add(errorInSendEmailToContactListService + ": " + nonFatalGEE.getMessage());
                } catch (GenericServiceException nonFatalGSE) {
                    Debug.logError(nonFatalGSE, errorInSendEmailToContactListService, module);
                    errorMessages.add(errorInSendEmailToContactListService + ": " + nonFatalGSE.getMessage());
                }
            }
        } catch (GenericEntityException fatalGEE) {
            return ServiceUtil.returnError(fatalGEE.getMessage());
        }
    } catch (GenericEntityException fatalGEE) {
        return ServiceUtil.returnError(fatalGEE.getMessage());
    }
    return errorMessages.size() == 0 ? ServiceUtil.returnSuccess() : ServiceUtil.returnError(errorMessages);
}
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) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 20 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class OrderListState method getOrders.

/**
 * Get the OrderHeaders corresponding to the state.
 */
public List<GenericValue> getOrders(String facilityId, Timestamp filterDate, Delegator delegator) throws GenericEntityException {
    List<EntityCondition> allConditions = new LinkedList<>();
    if (facilityId != null) {
        allConditions.add(EntityCondition.makeCondition("originFacilityId", EntityOperator.EQUALS, facilityId));
    }
    if (filterDate != null) {
        List<EntityCondition> andExprs = new LinkedList<>();
        andExprs.add(EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, UtilDateTime.getDayStart(filterDate)));
        andExprs.add(EntityCondition.makeCondition("orderDate", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.getDayEnd(filterDate)));
        allConditions.add(EntityCondition.makeCondition(andExprs, EntityOperator.AND));
    }
    List<EntityCondition> statusConditions = new LinkedList<>();
    for (String status : orderStatusState.keySet()) {
        if (!hasStatus(status)) {
            continue;
        }
        statusConditions.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, parameterToOrderStatusId.get(status)));
    }
    List<EntityCondition> typeConditions = new LinkedList<>();
    for (String type : orderTypeState.keySet()) {
        if (!hasType(type)) {
            continue;
        }
        typeConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, parameterToOrderTypeId.get(type)));
    }
    EntityCondition statusConditionsList = EntityCondition.makeCondition(statusConditions, EntityOperator.OR);
    EntityCondition typeConditionsList = EntityCondition.makeCondition(typeConditions, EntityOperator.OR);
    if (statusConditions.size() > 0) {
        allConditions.add(statusConditionsList);
    }
    if (typeConditions.size() > 0) {
        allConditions.add(typeConditionsList);
    }
    EntityQuery eq = EntityQuery.use(delegator).from("OrderHeader").where(allConditions).orderBy("orderDate DESC").maxRows(viewSize * (viewIndex + 1)).cursorScrollInsensitive();
    try (EntityListIterator iterator = eq.queryIterator()) {
        // get subset corresponding to pagination state
        List<GenericValue> orders = iterator.getPartialList(viewSize * viewIndex, viewSize);
        orderListSize = iterator.getResultsSizeAfterPartialList();
        return orders;
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)22 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)22 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)20 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)19 LinkedList (java.util.LinkedList)15 Delegator (org.apache.ofbiz.entity.Delegator)15 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)14 Timestamp (java.sql.Timestamp)11 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)11 HashMap (java.util.HashMap)10 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)10 Locale (java.util.Locale)9 Map (java.util.Map)7 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)5 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 ProductSearchConstraint (org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)4 ProductSearchContext (org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext)4 GeneralException (org.apache.ofbiz.base.util.GeneralException)3