Search in sources :

Example 46 with EntityCondition

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

the class ProductionRunServices method setEstimatedDeliveryDates.

public static Map<String, Object> setEstimatedDeliveryDates(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    Timestamp now = UtilDateTime.nowTimestamp();
    Locale locale = (Locale) context.get("locale");
    Map<String, TreeMap<Timestamp, Object>> products = new HashMap<String, TreeMap<Timestamp, Object>>();
    try {
        List<GenericValue> resultList = EntityQuery.use(delegator).from("WorkEffortAndGoods").where("workEffortGoodStdTypeId", "PRUN_PROD_DELIV", "statusId", "WEGS_CREATED", "workEffortTypeId", "PROD_ORDER_HEADER").queryList();
        for (GenericValue genericResult : resultList) {
            if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId")) || "PRUN_CREATED".equals(genericResult.getString("currentStatusId"))) {
                continue;
            }
            BigDecimal qtyToProduce = genericResult.getBigDecimal("quantityToProduce");
            if (qtyToProduce == null) {
                qtyToProduce = BigDecimal.ZERO;
            }
            BigDecimal qtyProduced = genericResult.getBigDecimal("quantityProduced");
            if (qtyProduced == null) {
                qtyProduced = BigDecimal.ZERO;
            }
            if (qtyProduced.compareTo(qtyToProduce) >= 0) {
                continue;
            }
            BigDecimal qtyDiff = qtyToProduce.subtract(qtyProduced);
            String productId = genericResult.getString("productId");
            Timestamp estimatedShipDate = genericResult.getTimestamp("estimatedCompletionDate");
            if (estimatedShipDate == null) {
                estimatedShipDate = now;
            }
            if (!products.containsKey(productId)) {
                products.put(productId, new TreeMap<Timestamp, Object>());
            }
            TreeMap<Timestamp, Object> productMap = products.get(productId);
            if (!productMap.containsKey(estimatedShipDate)) {
                productMap.put(estimatedShipDate, UtilMisc.<String, Object>toMap("remainingQty", BigDecimal.ZERO, "reservations", new LinkedList()));
            }
            Map<String, Object> dateMap = UtilGenerics.checkMap(productMap.get(estimatedShipDate));
            BigDecimal remainingQty = (BigDecimal) dateMap.get("remainingQty");
            remainingQty = remainingQty.add(qtyDiff);
            dateMap.put("remainingQty", remainingQty);
        }
        // Approved purchase orders
        resultList = EntityQuery.use(delegator).from("OrderHeaderAndItems").where("orderTypeId", "PURCHASE_ORDER", "itemStatusId", "ITEM_APPROVED").orderBy("orderId").queryList();
        String orderId = null;
        GenericValue orderDeliverySchedule = null;
        for (GenericValue genericResult : resultList) {
            String newOrderId = genericResult.getString("orderId");
            if (!newOrderId.equals(orderId)) {
                orderDeliverySchedule = null;
                orderId = newOrderId;
                orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne();
            }
            String productId = genericResult.getString("productId");
            BigDecimal orderQuantity = genericResult.getBigDecimal("quantity");
            GenericValue orderItemDeliverySchedule = null;
            orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryOne();
            Timestamp estimatedShipDate = null;
            if (orderItemDeliverySchedule != null && orderItemDeliverySchedule.get("estimatedReadyDate") != null) {
                estimatedShipDate = orderItemDeliverySchedule.getTimestamp("estimatedReadyDate");
            } else if (orderDeliverySchedule != null && orderDeliverySchedule.get("estimatedReadyDate") != null) {
                estimatedShipDate = orderDeliverySchedule.getTimestamp("estimatedReadyDate");
            } else {
                estimatedShipDate = genericResult.getTimestamp("estimatedDeliveryDate");
            }
            if (estimatedShipDate == null) {
                estimatedShipDate = now;
            }
            if (!products.containsKey(productId)) {
                products.put(productId, new TreeMap<Timestamp, Object>());
            }
            TreeMap<Timestamp, Object> productMap = products.get(productId);
            if (!productMap.containsKey(estimatedShipDate)) {
                productMap.put(estimatedShipDate, UtilMisc.toMap("remainingQty", BigDecimal.ZERO, "reservations", new LinkedList()));
            }
            Map<String, Object> dateMap = UtilGenerics.checkMap(productMap.get(estimatedShipDate));
            BigDecimal remainingQty = (BigDecimal) dateMap.get("remainingQty");
            remainingQty = remainingQty.add(orderQuantity);
            dateMap.put("remainingQty", remainingQty);
        }
        // backorders
        List<EntityCondition> backordersCondList = new LinkedList<EntityCondition>();
        backordersCondList.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.NOT_EQUAL, null));
        backordersCondList.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.GREATER_THAN, BigDecimal.ZERO));
        List<GenericValue> backorders = EntityQuery.use(delegator).from("OrderItemAndShipGrpInvResAndItem").where(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.GREATER_THAN, BigDecimal.ZERO)).orderBy("shipBeforeDate").queryList();
        for (GenericValue genericResult : backorders) {
            String productId = genericResult.getString("productId");
            GenericValue orderItemShipGroup = EntityQuery.use(delegator).from("OrderItemShipGroup").where("orderId", genericResult.get("orderId"), "shipGroupSeqId", genericResult.get("shipGroupSeqId")).queryOne();
            Timestamp requiredByDate = orderItemShipGroup.getTimestamp("shipByDate");
            BigDecimal quantityNotAvailable = genericResult.getBigDecimal("quantityNotAvailable");
            BigDecimal quantityNotAvailableRem = quantityNotAvailable;
            if (requiredByDate == null) {
                // If shipByDate is not set, 'now' is assumed.
                requiredByDate = now;
            }
            if (!products.containsKey(productId)) {
                continue;
            }
            TreeMap<Timestamp, Object> productMap = products.get(productId);
            SortedMap<Timestamp, Object> subsetMap = productMap.headMap(requiredByDate);
            // iterate and 'reserve'
            for (Timestamp currentDate : subsetMap.keySet()) {
                Map<String, Object> currentDateMap = UtilGenerics.checkMap(subsetMap.get(currentDate));
                BigDecimal remainingQty = (BigDecimal) currentDateMap.get("remainingQty");
                if (remainingQty.compareTo(ZERO) == 0) {
                    continue;
                }
                if (remainingQty.compareTo(quantityNotAvailableRem) >= 0) {
                    remainingQty = remainingQty.subtract(quantityNotAvailableRem);
                    currentDateMap.put("remainingQty", remainingQty);
                    GenericValue orderItemShipGrpInvRes = EntityQuery.use(delegator).from("OrderItemShipGrpInvRes").where("orderId", genericResult.get("orderId"), "shipGroupSeqId", genericResult.get("shipGroupSeqId"), "orderItemSeqId", genericResult.get("orderItemSeqId"), "inventoryItemId", genericResult.get("inventoryItemId")).queryOne();
                    orderItemShipGrpInvRes.set("promisedDatetime", currentDate);
                    orderItemShipGrpInvRes.store();
                    // TODO: set the reservation
                    break;
                } else {
                    quantityNotAvailableRem = quantityNotAvailableRem.subtract(remainingQty);
                    remainingQty = BigDecimal.ZERO;
                    currentDateMap.put("remainingQty", remainingQty);
                }
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunErrorRunningSetEstimatedDeliveryDates", locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) TreeMap(java.util.TreeMap) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 47 with EntityCondition

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

the class OrderServices method cancelFlaggedSalesOrders.

public static Map<String, Object> cancelFlaggedSalesOrders(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    List<GenericValue> ordersToCheck = null;
    // create the query expressions
    List<EntityCondition> exprs = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"));
    // get the orders
    try {
        ordersToCheck = EntityQuery.use(delegator).from("OrderHeader").where(exprs).orderBy("orderDate").queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting order headers", module);
    }
    if (UtilValidate.isEmpty(ordersToCheck)) {
        Debug.logInfo("No orders to check, finished", module);
        return ServiceUtil.returnSuccess();
    }
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    for (GenericValue orderHeader : ordersToCheck) {
        String orderId = orderHeader.getString("orderId");
        String orderStatus = orderHeader.getString("statusId");
        if ("ORDER_CREATED".equals(orderStatus)) {
            // first check for un-paid orders
            Timestamp orderDate = orderHeader.getTimestamp("entryDate");
            // need the store for the order
            GenericValue productStore = null;
            try {
                productStore = orderHeader.getRelatedOne("ProductStore", false);
            } catch (GenericEntityException e) {
                Debug.logError(e, "Unable to get ProductStore from OrderHeader", module);
            }
            // default days to cancel
            int daysTillCancel = 30;
            // get the value from the store
            if (productStore != null && productStore.get("daysToCancelNonPay") != null) {
                daysTillCancel = productStore.getLong("daysToCancelNonPay").intValue();
            }
            if (daysTillCancel > 0) {
                // 0 days means do not auto-cancel
                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(orderDate.getTime());
                cal.add(Calendar.DAY_OF_YEAR, daysTillCancel);
                Date cancelDate = cal.getTime();
                Date nowDate = new Date();
                if (cancelDate.equals(nowDate) || nowDate.after(cancelDate)) {
                    // cancel the order item(s)
                    Map<String, Object> svcCtx = UtilMisc.<String, Object>toMap("orderId", orderId, "statusId", "ITEM_CANCELLED", "userLogin", userLogin);
                    try {
                        // TODO: looks like result is ignored here, but we should be looking for errors
                        Map<String, Object> serviceResult = dispatcher.runSync("changeOrderItemStatus", svcCtx);
                        if (ServiceUtil.isError(serviceResult)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                        }
                    } catch (GenericServiceException e) {
                        Debug.logError(e, "Problem calling change item status service : " + svcCtx, module);
                    }
                }
            }
        } else {
            // check for auto-cancel items
            List<EntityCondition> itemsExprs = new ArrayList<>();
            // create the query expressions
            itemsExprs.add(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
            itemsExprs.add(EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_CREATED"), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_APPROVED")), EntityOperator.OR));
            itemsExprs.add(EntityCondition.makeCondition("dontCancelSetUserLogin", EntityOperator.EQUALS, GenericEntity.NULL_FIELD));
            itemsExprs.add(EntityCondition.makeCondition("dontCancelSetDate", EntityOperator.EQUALS, GenericEntity.NULL_FIELD));
            itemsExprs.add(EntityCondition.makeCondition("autoCancelDate", EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD));
            List<GenericValue> orderItems = null;
            try {
                orderItems = EntityQuery.use(delegator).from("OrderItem").where(itemsExprs).queryList();
            } catch (GenericEntityException e) {
                Debug.logError(e, "Problem getting order item records", module);
            }
            if (UtilValidate.isNotEmpty(orderItems)) {
                for (GenericValue orderItem : orderItems) {
                    String orderItemSeqId = orderItem.getString("orderItemSeqId");
                    Timestamp autoCancelDate = orderItem.getTimestamp("autoCancelDate");
                    if (autoCancelDate != null) {
                        if (nowTimestamp.equals(autoCancelDate) || nowTimestamp.after(autoCancelDate)) {
                            // cancel the order item
                            Map<String, Object> svcCtx = UtilMisc.<String, Object>toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "statusId", "ITEM_CANCELLED", "userLogin", userLogin);
                            try {
                                // TODO: check service result for an error return
                                Map<String, Object> serviceResult = dispatcher.runSync("changeOrderItemStatus", svcCtx);
                                if (ServiceUtil.isError(serviceResult)) {
                                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                                }
                            } catch (GenericServiceException e) {
                                Debug.logError(e, "Problem calling change item status service : " + svcCtx, module);
                            }
                        }
                    }
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) Date(java.util.Date) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 48 with EntityCondition

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

the class OrderServices method createAlsoBoughtProductAssocsForOrder.

public static Map<String, Object> createAlsoBoughtProductAssocsForOrder(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    List<GenericValue> orderItems = orh.getOrderItems();
    Map<String, Object> serviceResult = new HashMap<String, Object>();
    // In order to improve efficiency a little bit, we will always create the ProductAssoc records
    // with productId < productIdTo when the two are compared.  This way when checking for an existing
    // record we don't have to check both possible combinations of productIds
    Set<String> productIdSet = new TreeSet<>();
    if (orderItems != null) {
        for (GenericValue orderItem : orderItems) {
            String productId = orderItem.getString("productId");
            if (productId != null) {
                GenericValue parentProduct = ProductWorker.getParentProduct(productId, delegator);
                if (parentProduct != null) {
                    productId = parentProduct.getString("productId");
                }
                productIdSet.add(productId);
            }
        }
    }
    Set<String> productIdToSet = new TreeSet<>(productIdSet);
    for (String productId : productIdSet) {
        productIdToSet.remove(productId);
        for (String productIdTo : productIdToSet) {
            EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productId", productId), EntityCondition.makeCondition("productIdTo", productIdTo), EntityCondition.makeCondition("productAssocTypeId", "ALSO_BOUGHT"), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("thruDate", null)));
            GenericValue existingProductAssoc = null;
            try {
                // No point in using the cache because of the filterByDateExpr
                existingProductAssoc = EntityQuery.use(delegator).from("ProductAssoc").where(cond).orderBy("fromDate DESC").queryFirst();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            try {
                if (existingProductAssoc != null) {
                    BigDecimal newQuantity = existingProductAssoc.getBigDecimal("quantity");
                    if (newQuantity == null || newQuantity.compareTo(BigDecimal.ZERO) < 0) {
                        newQuantity = BigDecimal.ZERO;
                    }
                    newQuantity = newQuantity.add(BigDecimal.ONE);
                    ModelService updateProductAssoc = dctx.getModelService("updateProductAssoc");
                    Map<String, Object> updateCtx = updateProductAssoc.makeValid(context, ModelService.IN_PARAM, true, null);
                    updateCtx.putAll(updateProductAssoc.makeValid(existingProductAssoc, ModelService.IN_PARAM));
                    updateCtx.put("quantity", newQuantity);
                    serviceResult = dispatcher.runSync("updateProductAssoc", updateCtx);
                    if (ServiceUtil.isError(serviceResult)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                    }
                } else {
                    Map<String, Object> createCtx = new HashMap<>();
                    createCtx.put("userLogin", context.get("userLogin"));
                    createCtx.put("productId", productId);
                    createCtx.put("productIdTo", productIdTo);
                    createCtx.put("productAssocTypeId", "ALSO_BOUGHT");
                    createCtx.put("fromDate", UtilDateTime.nowTimestamp());
                    createCtx.put("quantity", BigDecimal.ONE);
                    serviceResult = dispatcher.runSync("createProductAssoc", createCtx);
                    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) BigDecimal(java.math.BigDecimal) ModelService(org.apache.ofbiz.service.ModelService) Delegator(org.apache.ofbiz.entity.Delegator) TreeSet(java.util.TreeSet) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 49 with EntityCondition

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

the class RequirementServices method getRequirementsForSupplier.

public static Map<String, Object> getRequirementsForSupplier(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    EntityCondition requirementConditions = (EntityCondition) context.get("requirementConditions");
    String partyId = (String) context.get("partyId");
    String unassignedRequirements = (String) context.get("unassignedRequirements");
    List<String> statusIds = UtilGenerics.checkList(context.get("statusIds"));
    // TODO currencyUomId still not used
    try {
        List<EntityCondition> conditions = UtilMisc.toList(EntityCondition.makeCondition("requirementTypeId", EntityOperator.EQUALS, "PRODUCT_REQUIREMENT"), EntityUtil.getFilterByDateExpr());
        if (UtilValidate.isNotEmpty(statusIds)) {
            conditions.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, statusIds));
        } else {
            conditions.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "REQ_APPROVED"));
        }
        if (requirementConditions != null)
            conditions.add(requirementConditions);
        // we're either getting the requirements for a given supplier, unassigned requirements, or requirements for all suppliers
        if (UtilValidate.isNotEmpty(partyId)) {
            conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId));
            conditions.add(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SUPPLIER"));
        } else if (UtilValidate.isNotEmpty(unassignedRequirements)) {
            conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, null));
        } else {
            conditions.add(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SUPPLIER"));
        }
        List<GenericValue> requirementAndRoles = EntityQuery.use(delegator).from("RequirementAndRole").where(conditions).orderBy("partyId", "requirementId").queryList();
        // maps to cache the associated suppliers and products data, so we don't do redundant DB and service requests
        Map<String, GenericValue> suppliers = new HashMap<String, GenericValue>();
        Map<String, GenericValue> gids = new HashMap<String, GenericValue>();
        Map<String, Map<String, Object>> inventories = new HashMap<String, Map<String, Object>>();
        Map<String, BigDecimal> productsSold = new HashMap<String, BigDecimal>();
        // to count quantity, running total, and distinct products in list
        BigDecimal quantity = BigDecimal.ZERO;
        BigDecimal amountTotal = BigDecimal.ZERO;
        Set<String> products = new HashSet<String>();
        // time period to count products ordered from, six months ago and the 1st of that month
        Timestamp timePeriodStart = UtilDateTime.getMonthStart(UtilDateTime.nowTimestamp(), 0, -6);
        // join in fields with extra data about the suppliers and products
        List<Map<String, Object>> requirements = new LinkedList<Map<String, Object>>();
        for (GenericValue requirement : requirementAndRoles) {
            Map<String, Object> union = new HashMap<String, Object>();
            String productId = requirement.getString("productId");
            partyId = requirement.getString("partyId");
            String facilityId = requirement.getString("facilityId");
            BigDecimal requiredQuantity = requirement.getBigDecimal("quantity");
            // get an available supplier product, preferably the one with the smallest minimum quantity to order, followed by price
            String supplierKey = partyId + "^" + productId;
            GenericValue supplierProduct = suppliers.get(supplierKey);
            if (supplierProduct == null) {
                // TODO: it is possible to restrict to quantity > minimumOrderQuantity, but then the entire requirement must be skipped
                supplierProduct = EntityQuery.use(delegator).from("SupplierProduct").where("partyId", partyId, "productId", productId).orderBy("minimumOrderQuantity", "lastPrice").filterByDate("availableFromDate", "availableThruDate").queryFirst();
                suppliers.put(supplierKey, supplierProduct);
            }
            // add our supplier product and cost of this line to the data
            if (supplierProduct != null) {
                union.putAll(supplierProduct.getAllFields());
                BigDecimal lastPrice = supplierProduct.getBigDecimal("lastPrice");
                amountTotal = amountTotal.add(lastPrice.multiply(requiredQuantity));
            }
            // for good identification, get the UPCA type (UPC code)
            GenericValue gid = gids.get(productId);
            if (gid == null) {
                gid = EntityQuery.use(delegator).from("GoodIdentification").where("goodIdentificationTypeId", "UPCA", "productId", requirement.get("productId")).queryOne();
                gids.put(productId, gid);
            }
            if (gid != null)
                union.put("idValue", gid.get("idValue"));
            // the ATP and QOH quantities
            if (UtilValidate.isNotEmpty(facilityId)) {
                String inventoryKey = facilityId + "^" + productId;
                Map<String, Object> inventory = inventories.get(inventoryKey);
                if (inventory == null) {
                    inventory = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", facilityId));
                    if (ServiceUtil.isError(inventory)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(inventory));
                    }
                    inventories.put(inventoryKey, inventory);
                }
                if (inventory != null) {
                    union.put("qoh", inventory.get("quantityOnHandTotal"));
                    union.put("atp", inventory.get("availableToPromiseTotal"));
                }
            }
            // how many of the products were sold (note this is for a fixed time period across all product stores)
            BigDecimal sold = productsSold.get(productId);
            if (sold == null) {
                EntityCondition prodConditions = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"), EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_IN, UtilMisc.toList("ORDER_REJECTED", "ORDER_CANCELLED")), EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_IN, UtilMisc.toList("ITEM_REJECTED", "ITEM_CANCELLED")), EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, timePeriodStart)), EntityOperator.AND);
                GenericValue count = EntityQuery.use(delegator).select("quantityOrdered").from("OrderItemQuantityReportGroupByProduct").where(prodConditions).queryFirst();
                if (count != null) {
                    sold = count.getBigDecimal("quantityOrdered");
                    if (sold != null)
                        productsSold.put(productId, sold);
                }
            }
            if (sold != null) {
                union.put("qtySold", sold);
            }
            // default quantity = 1
            if (requirement.getBigDecimal("quantity") == null)
                requirement.put("quantity", BigDecimal.ONE);
            quantity = quantity.add(requiredQuantity);
            products.add(productId);
            // add all the requirement fields last, to overwrite any conflicting fields
            union.putAll(requirement.getAllFields());
            requirements.add(union);
        }
        Map<String, Object> results = ServiceUtil.returnSuccess();
        results.put("requirementsForSupplier", requirements);
        results.put("distinctProductCount", Integer.valueOf(products.size()));
        results.put("quantityTotal", quantity);
        results.put("amountTotal", amountTotal);
        return results;
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderServiceExceptionSeeLogs", locale));
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderEntityExceptionSeeLogs", locale));
    }
}
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) HashSet(java.util.HashSet)

Example 50 with EntityCondition

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

the class OrderReadHelper method getItemReceivedQuantity.

public BigDecimal getItemReceivedQuantity(GenericValue orderItem) {
    BigDecimal totalReceived = BigDecimal.ZERO;
    try {
        if (orderItem != null) {
            EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("orderId", orderItem.getString("orderId")), EntityCondition.makeCondition("quantityAccepted", EntityOperator.GREATER_THAN, BigDecimal.ZERO), EntityCondition.makeCondition("orderItemSeqId", orderItem.getString("orderItemSeqId"))));
            Delegator delegator = orderItem.getDelegator();
            List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from("ShipmentReceiptAndItem").where(cond).queryList();
            for (GenericValue shipmentReceipt : shipmentReceipts) {
                if (shipmentReceipt.getBigDecimal("quantityAccepted") != null) {
                    totalReceived = totalReceived.add(shipmentReceipt.getBigDecimal("quantityAccepted"));
                }
                if (shipmentReceipt.getBigDecimal("quantityRejected") != null) {
                    totalReceived = totalReceived.add(shipmentReceipt.getBigDecimal("quantityRejected"));
                }
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    return totalReceived;
}
Also used : 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) BigDecimal(java.math.BigDecimal)

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