Search in sources :

Example 51 with EntityListIterator

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

the class InventoryServices method getProductInventoryAndFacilitySummary.

public static Map<String, Object> getProductInventoryAndFacilitySummary(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Timestamp checkTime = (Timestamp) context.get("checkTime");
    String facilityId = (String) context.get("facilityId");
    String productId = (String) context.get("productId");
    BigDecimal minimumStock = (BigDecimal) context.get("minimumStock");
    String statusId = (String) context.get("statusId");
    Map<String, Object> result = new HashMap<>();
    Map<String, Object> resultOutput = new HashMap<>();
    Map<String, String> contextInput = UtilMisc.toMap("productId", productId, "facilityId", facilityId, "statusId", statusId);
    GenericValue product = null;
    try {
        product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (product != null) {
        if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG")) {
            try {
                resultOutput = dispatcher.runSync("getMktgPackagesAvailable", contextInput);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }
        } else {
            try {
                resultOutput = dispatcher.runSync("getInventoryAvailableByFacility", contextInput);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }
        }
        // filter for quantities
        minimumStock = minimumStock != null ? minimumStock : BigDecimal.ZERO;
        BigDecimal quantityOnHandTotal = BigDecimal.ZERO;
        if (resultOutput.get("quantityOnHandTotal") != null) {
            quantityOnHandTotal = (BigDecimal) resultOutput.get("quantityOnHandTotal");
        }
        BigDecimal offsetQOHQtyAvailable = quantityOnHandTotal.subtract(minimumStock);
        BigDecimal availableToPromiseTotal = BigDecimal.ZERO;
        if (resultOutput.get("availableToPromiseTotal") != null) {
            availableToPromiseTotal = (BigDecimal) resultOutput.get("availableToPromiseTotal");
        }
        BigDecimal offsetATPQtyAvailable = availableToPromiseTotal.subtract(minimumStock);
        BigDecimal quantityOnOrder = InventoryWorker.getOutstandingPurchasedQuantity(productId, delegator);
        result.put("totalQuantityOnHand", resultOutput.get("quantityOnHandTotal"));
        result.put("totalAvailableToPromise", resultOutput.get("availableToPromiseTotal"));
        result.put("quantityOnOrder", quantityOnOrder);
        result.put("quantityUomId", product.getString("quantityUomId"));
        result.put("offsetQOHQtyAvailable", offsetQOHQtyAvailable);
        result.put("offsetATPQtyAvailable", offsetATPQtyAvailable);
    }
    List<GenericValue> productPrices = null;
    try {
        productPrices = EntityQuery.use(delegator).from("ProductPrice").where("productId", productId).orderBy("-fromDate").cache(true).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    // change this for product price
    if (productPrices != null) {
        for (GenericValue onePrice : productPrices) {
            if ("DEFAULT_PRICE".equals(onePrice.getString("productPriceTypeId"))) {
                // defaultPrice
                result.put("defaultPrice", onePrice.getBigDecimal("price"));
            } else if ("WHOLESALE_PRICE".equals(onePrice.getString("productPriceTypeId"))) {
                // 
                result.put("wholeSalePrice", onePrice.getBigDecimal("price"));
            } else if ("LIST_PRICE".equals(onePrice.getString("productPriceTypeId"))) {
                // listPrice
                result.put("listPrice", onePrice.getBigDecimal("price"));
            } else {
                result.put("defaultPrice", onePrice.getBigDecimal("price"));
                result.put("listPrice", onePrice.getBigDecimal("price"));
                result.put("wholeSalePrice", onePrice.getBigDecimal("price"));
            }
        }
    }
    DynamicViewEntity salesUsageViewEntity = new DynamicViewEntity();
    DynamicViewEntity productionUsageViewEntity = new DynamicViewEntity();
    if (!UtilValidate.isEmpty(checkTime)) {
        // Construct a dynamic view entity to search against for sales usage quantities
        salesUsageViewEntity.addMemberEntity("OI", "OrderItem");
        salesUsageViewEntity.addMemberEntity("OH", "OrderHeader");
        salesUsageViewEntity.addMemberEntity("ItIss", "ItemIssuance");
        salesUsageViewEntity.addMemberEntity("InvIt", "InventoryItem");
        salesUsageViewEntity.addViewLink("OI", "OH", Boolean.valueOf(false), ModelKeyMap.makeKeyMapList("orderId"));
        salesUsageViewEntity.addViewLink("OI", "ItIss", Boolean.valueOf(false), ModelKeyMap.makeKeyMapList("orderId", "orderId", "orderItemSeqId", "orderItemSeqId"));
        salesUsageViewEntity.addViewLink("ItIss", "InvIt", Boolean.valueOf(false), ModelKeyMap.makeKeyMapList("inventoryItemId"));
        salesUsageViewEntity.addAlias("OI", "productId");
        salesUsageViewEntity.addAlias("OH", "statusId");
        salesUsageViewEntity.addAlias("OH", "orderTypeId");
        salesUsageViewEntity.addAlias("OH", "orderDate");
        salesUsageViewEntity.addAlias("ItIss", "inventoryItemId");
        salesUsageViewEntity.addAlias("ItIss", "quantity");
        salesUsageViewEntity.addAlias("InvIt", "facilityId");
        // Construct a dynamic view entity to search against for production usage quantities
        productionUsageViewEntity.addMemberEntity("WEIA", "WorkEffortInventoryAssign");
        productionUsageViewEntity.addMemberEntity("WE", "WorkEffort");
        productionUsageViewEntity.addMemberEntity("II", "InventoryItem");
        productionUsageViewEntity.addViewLink("WEIA", "WE", Boolean.valueOf(false), ModelKeyMap.makeKeyMapList("workEffortId"));
        productionUsageViewEntity.addViewLink("WEIA", "II", Boolean.valueOf(false), ModelKeyMap.makeKeyMapList("inventoryItemId"));
        productionUsageViewEntity.addAlias("WEIA", "quantity");
        productionUsageViewEntity.addAlias("WE", "actualCompletionDate");
        productionUsageViewEntity.addAlias("WE", "workEffortTypeId");
        productionUsageViewEntity.addAlias("II", "facilityId");
        productionUsageViewEntity.addAlias("II", "productId");
        // Make a query against the sales usage view entity
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("ORDER_COMPLETED", "ORDER_APPROVED", "ORDER_HELD")), EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"), EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, checkTime)), EntityOperator.AND);
        try (EntityListIterator salesUsageIt = EntityQuery.use(delegator).from(salesUsageViewEntity).where(cond).queryIterator()) {
            // Sum the sales usage quantities found
            BigDecimal salesUsageQuantity = BigDecimal.ZERO;
            GenericValue salesUsageItem = null;
            while ((salesUsageItem = salesUsageIt.next()) != null) {
                if (salesUsageItem.get("quantity") != null) {
                    salesUsageQuantity = salesUsageQuantity.add(salesUsageItem.getBigDecimal("quantity"));
                }
            }
            // Make a query against the production usage view entity
            EntityCondition conditions = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityCondition.makeCondition("workEffortTypeId", EntityOperator.EQUALS, "PROD_ORDER_TASK"), EntityCondition.makeCondition("actualCompletionDate", EntityOperator.GREATER_THAN_EQUAL_TO, checkTime)), EntityOperator.AND);
            try (EntityListIterator productionUsageIt = EntityQuery.use(delegator).from(productionUsageViewEntity).where(conditions).queryIterator()) {
                // Sum the production usage quantities found
                BigDecimal productionUsageQuantity = BigDecimal.ZERO;
                GenericValue productionUsageItem = null;
                while ((productionUsageItem = productionUsageIt.next()) != null) {
                    if (productionUsageItem.get("quantity") != null) {
                        productionUsageQuantity = productionUsageQuantity.add(productionUsageItem.getBigDecimal("quantity"));
                    }
                }
                result.put("usageQuantity", salesUsageQuantity.add(productionUsageQuantity));
            } catch (GeneralException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        } catch (GeneralException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    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) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) 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 52 with EntityListIterator

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

the class ParametricSearch method getAllFeaturesByType.

public static Map<String, List<GenericValue>> getAllFeaturesByType(Delegator delegator, int perTypeMaxSize) {
    Map<String, List<GenericValue>> productFeaturesByTypeMap = new HashMap<String, List<GenericValue>>();
    Set<String> typesWithOverflowMessages = new HashSet<String>();
    try (EntityListIterator productFeatureEli = EntityQuery.use(delegator).from("ProductFeature").orderBy("description").queryIterator()) {
        GenericValue productFeature = null;
        while ((productFeature = productFeatureEli.next()) != null) {
            String productFeatureTypeId = productFeature.getString("productFeatureTypeId");
            List<GenericValue> featuresByType = productFeaturesByTypeMap.get(productFeatureTypeId);
            if (featuresByType == null) {
                featuresByType = new LinkedList<GenericValue>();
                productFeaturesByTypeMap.put(productFeatureTypeId, featuresByType);
            }
            if (featuresByType.size() > perTypeMaxSize) {
                if (!typesWithOverflowMessages.contains(productFeatureTypeId)) {
                    typesWithOverflowMessages.add(productFeatureTypeId);
                // TODO: uh oh, how do we pass this message back? no biggie for now
                }
            } else {
                featuresByType.add(productFeature);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error getting all features", module);
    }
    return productFeaturesByTypeMap;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) List(java.util.List) LinkedList(java.util.LinkedList) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashSet(java.util.HashSet)

Example 53 with EntityListIterator

use of org.apache.ofbiz.entity.util.EntityListIterator 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 54 with EntityListIterator

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

the class ProductUtilServices method clearAllVirtualProductImageNames.

public static Map<String, Object> clearAllVirtualProductImageNames(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    try (EntityListIterator eli = EntityQuery.use(delegator).from("Product").where("isVirtual", "Y").queryIterator()) {
        GenericValue product = null;
        int numSoFar = 0;
        while ((product = eli.next()) != null) {
            product.set("smallImageUrl", null);
            product.set("mediumImageUrl", null);
            product.set("largeImageUrl", null);
            product.set("detailImageUrl", null);
            product.store();
            numSoFar++;
            if (numSoFar % 500 == 0) {
                Debug.logInfo("Image URLs cleared for " + numSoFar + " products.", module);
            }
        }
        Debug.logInfo("Completed - Image URLs set for " + numSoFar + " products.", module);
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_clearAllVirtualProductImageNames", messageMap, locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashMap(java.util.HashMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap)

Example 55 with EntityListIterator

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

the class ProductUtilServices method removeDuplicateOpenEndedCategoryMembers.

public static Map<String, Object> removeDuplicateOpenEndedCategoryMembers(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    DynamicViewEntity dve = new DynamicViewEntity();
    dve.addMemberEntity("PCM", "ProductCategoryMember");
    dve.addAlias("PCM", "productId", null, null, null, Boolean.TRUE, null);
    dve.addAlias("PCM", "productCategoryId", null, null, null, Boolean.TRUE, null);
    dve.addAlias("PCM", "fromDate", null, null, null, null, null);
    dve.addAlias("PCM", "thruDate", null, null, null, null, null);
    dve.addAlias("PCM", "productIdCount", "productId", null, null, null, "count");
    EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN, nowTimestamp), EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null)), EntityOperator.AND);
    EntityCondition havingCond = EntityCondition.makeCondition("productIdCount", EntityOperator.GREATER_THAN, Long.valueOf(1));
    try (EntityListIterator eli = EntityQuery.use(delegator).select("productId", "productCategoryId", "productIdCount").from(dve).where(condition).having(havingCond).queryIterator()) {
        GenericValue pcm = null;
        int numSoFar = 0;
        while ((pcm = eli.next()) != null) {
            List<GenericValue> productCategoryMemberList = EntityQuery.use(delegator).from("ProductCategoryMember").where("productId", pcm.get("productId"), "productCategoryId", pcm.get("productCategoryId")).queryList();
            if (productCategoryMemberList.size() > 1) {
                // remove all except the first...
                productCategoryMemberList.remove(0);
                for (GenericValue productCategoryMember : productCategoryMemberList) {
                    productCategoryMember.remove();
                }
                numSoFar++;
                if (numSoFar % 500 == 0) {
                    Debug.logInfo("Removed category members for " + numSoFar + " products with duplicate category members.", module);
                }
            }
        }
        Debug.logInfo("Completed - Removed category members for " + numSoFar + " products with duplicate category members.", module);
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_removeDuplicateOpenEndedCategoryMembers", messageMap, locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) Timestamp(java.sql.Timestamp) HashMap(java.util.HashMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap)

Aggregations

EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)65 GenericValue (org.apache.ofbiz.entity.GenericValue)59 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)57 Delegator (org.apache.ofbiz.entity.Delegator)33 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)29 LinkedList (java.util.LinkedList)25 HashMap (java.util.HashMap)24 Timestamp (java.sql.Timestamp)23 Locale (java.util.Locale)21 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)19 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)18 Map (java.util.Map)16 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)13 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)12 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)8 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)8 GeneralException (org.apache.ofbiz.base.util.GeneralException)7 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)7 ArrayList (java.util.ArrayList)6 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)6