Search in sources :

Example 61 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class GroovyEngine method serviceInvoker.

private Map<String, Object> serviceInvoker(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException {
    if (UtilValidate.isEmpty(modelService.location)) {
        throw new GenericServiceException("Cannot run Groovy service with empty location");
    }
    Map<String, Object> params = new HashMap<>();
    params.putAll(context);
    Map<String, Object> gContext = new HashMap<>();
    gContext.putAll(context);
    gContext.put(ScriptUtil.PARAMETERS_KEY, params);
    DispatchContext dctx = dispatcher.getLocalContext(localName);
    gContext.put("dctx", dctx);
    gContext.put("security", dctx.getSecurity());
    gContext.put("dispatcher", dctx.getDispatcher());
    gContext.put("delegator", dispatcher.getDelegator());
    try {
        ScriptContext scriptContext = ScriptUtil.createScriptContext(gContext, protectedKeys);
        ScriptHelper scriptHelper = (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
        if (scriptHelper != null) {
            gContext.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
        }
        Script script = InvokerHelper.createScript(GroovyUtil.getScriptClassFromLocation(this.getLocation(modelService)), GroovyUtil.getBinding(gContext));
        Object resultObj = null;
        if (UtilValidate.isEmpty(modelService.invoke)) {
            resultObj = script.run();
        } else {
            resultObj = script.invokeMethod(modelService.invoke, EMPTY_ARGS);
        }
        if (resultObj == null) {
            resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
        }
        if (resultObj != null && resultObj instanceof Map<?, ?>) {
            return cast(resultObj);
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.putAll(modelService.makeValid(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE), ModelService.OUT_PARAM));
        return result;
    } catch (GeneralException ge) {
        throw new GenericServiceException(ge);
    } catch (Exception e) {
        // make spotting problems very difficult.  Disabling this for now in favor of returning a proper exception.
        throw new GenericServiceException("Error running Groovy method [" + modelService.invoke + "] in Groovy file [" + modelService.location + "]: ", e);
    }
}
Also used : DispatchContext(org.apache.ofbiz.service.DispatchContext) Script(groovy.lang.Script) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ScriptContext(javax.script.ScriptContext) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ScriptHelper(org.apache.ofbiz.base.util.ScriptHelper) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GeneralException(org.apache.ofbiz.base.util.GeneralException)

Example 62 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ProductionRunServices method cloneWorkEffortCostCalcs.

/**
 * Make a copy of the cost calc entities that were defined on the template routing task to the new production run task.
 */
private static void cloneWorkEffortCostCalcs(DispatchContext dctx, GenericValue userLogin, String routingTaskId, String productionRunTaskId) throws GeneralException {
    List<GenericValue> workEffortCostCalcs = null;
    try {
        workEffortCostCalcs = EntityUtil.filterByDate(dctx.getDelegator().findByAnd("WorkEffortCostCalc", UtilMisc.toMap("workEffortId", routingTaskId), null, false));
    } catch (GenericEntityException e) {
        Debug.logError(e.getMessage(), module);
    }
    if (workEffortCostCalcs != null) {
        for (GenericValue costCalc : workEffortCostCalcs) {
            Map<String, Object> createCostCalc = UtilMisc.toMap("workEffortId", productionRunTaskId, "costComponentTypeId", costCalc.getString("costComponentTypeId"), "costComponentCalcId", costCalc.getString("costComponentCalcId"), "fromDate", costCalc.get("fromDate"), "thruDate", costCalc.get("thruDate"), "userLogin", userLogin);
            try {
                Map<String, Object> result = dctx.getDispatcher().runSync("createWorkEffortCostCalc", createCostCalc);
                if (ServiceUtil.isError(result)) {
                    String errorMessage = ServiceUtil.getErrorMessage(result);
                    Debug.logError(errorMessage, module);
                    throw new GeneralException(errorMessage);
                }
            } catch (GenericServiceException gse) {
                Debug.logError(gse, "Problem calling the createWorkEffortCostCalc service", module);
            }
            if (Debug.infoOn())
                Debug.logInfo("ProductionRun CostCalc for cost calc: " + costCalc.getString("costComponentCalcId") + " created", module);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 63 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ProductionRunServices method createProductionRun.

/**
 * Creates a Production Run.
 * <ul>
 *  <li> check if routing - product link exist</li>
 *  <li> check if product have a Bill Of Material</li>
 *  <li> check if routing have routingTask</li>
 *  <li> create the workEffort for ProductionRun</li>
 *  <li> create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce</li>
 *  <li> for each valid routingTask of the routing create a workeffort-task</li>
 *  <li> for the first routingTask, create for all the valid productIdTo with no associateRoutingTask  a WorkEffortGoodStandard</li>
 *  <li> for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard</li>
 * </ul>
 * @param ctx The DispatchContext that this service is operating in.
 * @param context Map containing the input parameters, productId, routingId, pRQuantity, startDate, workEffortName, description
 * @return Map with the result of the service, the output parameters.
 */
public static Map<String, Object> createProductionRun(DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = new HashMap<String, Object>();
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    /* TODO: security management  and finishing cleaning (ex copy from PartyServices.java)        
         */
    // Mandatory input fields
    String productId = (String) context.get("productId");
    Timestamp startDate = (Timestamp) context.get("startDate");
    BigDecimal pRQuantity = (BigDecimal) context.get("pRQuantity");
    String facilityId = (String) context.get("facilityId");
    // Optional input fields
    String workEffortId = (String) context.get("routingId");
    String workEffortName = (String) context.get("workEffortName");
    String description = (String) context.get("description");
    GenericValue routing = null;
    GenericValue product = null;
    List<GenericValue> routingTaskAssocs = null;
    try {
        // Find the product
        product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
        if (product == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductNotExist", locale));
        }
    } catch (GenericEntityException e) {
        Debug.logWarning(e.getMessage(), module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // Select the product's routing
    try {
        Map<String, Object> routingInMap = UtilMisc.toMap("productId", productId, "applicableDate", startDate, "userLogin", userLogin);
        if (workEffortId != null) {
            routingInMap.put("workEffortId", workEffortId);
        }
        Map<String, Object> routingOutMap = dispatcher.runSync("getProductRouting", routingInMap);
        if (ServiceUtil.isError(routingOutMap)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(routingOutMap));
        }
        routing = (GenericValue) routingOutMap.get("routing");
        routingTaskAssocs = UtilGenerics.checkList(routingOutMap.get("tasks"));
    } catch (GenericServiceException gse) {
        Debug.logWarning(gse.getMessage(), module);
    }
    if (routing == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductRoutingNotExist", locale));
    }
    if (UtilValidate.isEmpty(routingTaskAssocs)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingRoutingHasNoRoutingTask", locale));
    }
    // -------------------
    // Components
    // -------------------
    // The components are retrieved using the getManufacturingComponents service
    // (that performs a bom breakdown and if needed runs the configurator).
    List<BOMNode> components = null;
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    // the product that we want to manufacture
    serviceContext.put("productId", productId);
    // the quantity that we want to manufacture
    serviceContext.put("quantity", pRQuantity);
    serviceContext.put("userLogin", userLogin);
    Map<String, Object> serviceResult = null;
    try {
        serviceResult = dispatcher.runSync("getManufacturingComponents", serviceContext);
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
        // a list of objects representing the product's components
        components = UtilGenerics.checkList(serviceResult.get("components"));
    } catch (GenericServiceException e) {
        Debug.logError(e, "Problem calling the getManufacturingComponents service", module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // ProductionRun header creation,
    if (workEffortName == null) {
        String prdName = UtilValidate.isNotEmpty(product.getString("productName")) ? product.getString("productName") : product.getString("productId");
        String wefName = UtilValidate.isNotEmpty(routing.getString("workEffortName")) ? routing.getString("workEffortName") : routing.getString("workEffortId");
        workEffortName = prdName + "-" + wefName;
    }
    serviceContext.clear();
    serviceContext.put("workEffortTypeId", "PROD_ORDER_HEADER");
    serviceContext.put("workEffortPurposeTypeId", "WEPT_PRODUCTION_RUN");
    serviceContext.put("currentStatusId", "PRUN_CREATED");
    serviceContext.put("workEffortName", workEffortName);
    serviceContext.put("description", description);
    serviceContext.put("facilityId", facilityId);
    serviceContext.put("estimatedStartDate", startDate);
    serviceContext.put("quantityToProduce", pRQuantity);
    serviceContext.put("userLogin", userLogin);
    try {
        serviceResult = dispatcher.runSync("createWorkEffort", serviceContext);
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, "Problem calling the createWorkEffort service", module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String productionRunId = (String) serviceResult.get("workEffortId");
    if (Debug.infoOn()) {
        Debug.logInfo("ProductionRun created: " + productionRunId, module);
    }
    // ProductionRun,  product will be produce creation = WorkEffortGoodStandard for the productId
    serviceContext.clear();
    serviceContext.put("workEffortId", productionRunId);
    serviceContext.put("productId", productId);
    serviceContext.put("workEffortGoodStdTypeId", "PRUN_PROD_DELIV");
    serviceContext.put("statusId", "WEGS_CREATED");
    serviceContext.put("estimatedQuantity", pRQuantity);
    serviceContext.put("fromDate", startDate);
    serviceContext.put("userLogin", userLogin);
    try {
        serviceResult = dispatcher.runSync("createWorkEffortGoodStandard", serviceContext);
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, "Problem calling the createWorkEffortGoodStandard service", module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // Multi creation (like clone) ProductionRunTask and GoodAssoc
    boolean first = true;
    for (GenericValue routingTaskAssoc : routingTaskAssocs) {
        if (EntityUtil.isValueActive(routingTaskAssoc, startDate)) {
            GenericValue routingTask = null;
            try {
                routingTask = routingTaskAssoc.getRelatedOne("ToWorkEffort", false);
            } catch (GenericEntityException e) {
                Debug.logError(e.getMessage(), module);
            }
            // Calculate the estimatedCompletionDate
            long totalTime = ProductionRun.getEstimatedTaskTime(routingTask, pRQuantity, dispatcher);
            Timestamp endDate = TechDataServices.addForward(TechDataServices.getTechDataCalendar(routingTask), startDate, totalTime);
            serviceContext.clear();
            serviceContext.put("priority", routingTaskAssoc.get("sequenceNum"));
            serviceContext.put("workEffortPurposeTypeId", "WEPT_PRODUCTION_RUN");
            serviceContext.put("workEffortName", routingTask.get("workEffortName"));
            serviceContext.put("description", routingTask.get("description"));
            serviceContext.put("fixedAssetId", routingTask.get("fixedAssetId"));
            serviceContext.put("workEffortTypeId", "PROD_ORDER_TASK");
            serviceContext.put("currentStatusId", "PRUN_CREATED");
            serviceContext.put("workEffortParentId", productionRunId);
            serviceContext.put("facilityId", facilityId);
            serviceContext.put("reservPersons", routingTask.get("reservPersons"));
            serviceContext.put("estimatedStartDate", startDate);
            serviceContext.put("estimatedCompletionDate", endDate);
            serviceContext.put("estimatedSetupMillis", routingTask.get("estimatedSetupMillis"));
            serviceContext.put("estimatedMilliSeconds", routingTask.get("estimatedMilliSeconds"));
            serviceContext.put("quantityToProduce", pRQuantity);
            serviceContext.put("userLogin", userLogin);
            serviceResult = null;
            try {
                serviceResult = dispatcher.runSync("createWorkEffort", serviceContext);
                if (ServiceUtil.isError(serviceResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problem calling the createWorkEffort service", module);
            }
            String productionRunTaskId = (String) serviceResult.get("workEffortId");
            if (Debug.infoOn())
                Debug.logInfo("ProductionRunTaskId created: " + productionRunTaskId, module);
            // The newly created production run task is associated to the routing task
            // to keep track of the template used to generate it.
            serviceContext.clear();
            serviceContext.put("userLogin", userLogin);
            serviceContext.put("workEffortIdFrom", routingTask.getString("workEffortId"));
            serviceContext.put("workEffortIdTo", productionRunTaskId);
            serviceContext.put("workEffortAssocTypeId", "WORK_EFF_TEMPLATE");
            try {
                serviceResult = dispatcher.runSync("createWorkEffortAssoc", serviceContext);
                if (ServiceUtil.isError(serviceResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problem calling the createWorkEffortAssoc service", module);
            }
            // clone associated objects from the routing task to the run task
            String routingTaskId = routingTaskAssoc.getString("workEffortIdTo");
            try {
                cloneWorkEffortPartyAssignments(ctx, userLogin, routingTaskId, productionRunTaskId);
                cloneWorkEffortCostCalcs(ctx, userLogin, routingTaskId, productionRunTaskId);
            } catch (GeneralException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
            // the component is not added to the production run.
            for (BOMNode node : components) {
                // The components variable contains a list of BOMNodes:
                // each node represents a product (component).
                GenericValue productBom = node.getProductAssoc();
                if ((productBom.getString("routingWorkEffortId") == null && first) || (productBom.getString("routingWorkEffortId") != null && productBom.getString("routingWorkEffortId").equals(routingTask.getString("workEffortId")))) {
                    serviceContext.clear();
                    serviceContext.put("workEffortId", productionRunTaskId);
                    // Here we get the ProductAssoc record from the BOMNode
                    // object to be sure to use the
                    // right component (possibly configured).
                    serviceContext.put("productId", node.getProduct().get("productId"));
                    serviceContext.put("workEffortGoodStdTypeId", "PRUNT_PROD_NEEDED");
                    serviceContext.put("statusId", "WEGS_CREATED");
                    serviceContext.put("fromDate", productBom.get("fromDate"));
                    // Here we use the getQuantity method to get the quantity already
                    // computed by the getManufacturingComponents service
                    serviceContext.put("estimatedQuantity", node.getQuantity());
                    serviceContext.put("userLogin", userLogin);
                    serviceResult = null;
                    try {
                        serviceResult = dispatcher.runSync("createWorkEffortGoodStandard", serviceContext);
                        if (ServiceUtil.isError(serviceResult)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                        }
                    } catch (GenericServiceException e) {
                        Debug.logError(e, "Problem calling the createWorkEffortGoodStandard service", module);
                    }
                    if (Debug.infoOn())
                        Debug.logInfo("ProductLink created for productId: " + productBom.getString("productIdTo"), module);
                }
            }
            first = false;
            startDate = endDate;
        }
    }
    // update the estimatedCompletionDate field for the productionRun
    serviceContext.clear();
    serviceContext.put("workEffortId", productionRunId);
    serviceContext.put("estimatedCompletionDate", startDate);
    serviceContext.put("userLogin", userLogin);
    serviceResult = null;
    try {
        serviceResult = dispatcher.runSync("updateWorkEffort", serviceContext);
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, "Problem calling the updateWorkEffort service", module);
    }
    result.put("productionRunId", productionRunId);
    result.put("estimatedCompletionDate", startDate);
    result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(resource, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale));
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) BOMNode(org.apache.ofbiz.manufacturing.bom.BOMNode) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 64 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ProductionRunServices method cloneWorkEffortPartyAssignments.

/**
 * Make a copy of the party assignments that were defined on the template routing task to the new production run task.
 */
private static void cloneWorkEffortPartyAssignments(DispatchContext dctx, GenericValue userLogin, String routingTaskId, String productionRunTaskId) throws GeneralException {
    List<GenericValue> workEffortPartyAssignments = null;
    try {
        workEffortPartyAssignments = EntityUtil.filterByDate(dctx.getDelegator().findByAnd("WorkEffortPartyAssignment", UtilMisc.toMap("workEffortId", routingTaskId), null, false));
    } catch (GenericEntityException e) {
        Debug.logError(e.getMessage(), module);
    }
    if (workEffortPartyAssignments != null) {
        for (GenericValue workEffortPartyAssignment : workEffortPartyAssignments) {
            Map<String, Object> partyToWorkEffort = UtilMisc.<String, Object>toMap("workEffortId", productionRunTaskId, "partyId", workEffortPartyAssignment.getString("partyId"), "roleTypeId", workEffortPartyAssignment.getString("roleTypeId"), "fromDate", workEffortPartyAssignment.getTimestamp("fromDate"), "statusId", workEffortPartyAssignment.getString("statusId"), "userLogin", userLogin);
            try {
                Map<String, Object> result = dctx.getDispatcher().runSync("assignPartyToWorkEffort", partyToWorkEffort);
                if (ServiceUtil.isError(result)) {
                    String errorMessage = ServiceUtil.getErrorMessage(result);
                    Debug.logError(errorMessage, module);
                    throw new GeneralException(errorMessage);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problem calling the assignPartyToWorkEffort service", module);
            }
            if (Debug.infoOn())
                Debug.logInfo("ProductionRunPartyassigment for party: " + workEffortPartyAssignment.get("partyId") + " created", module);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 65 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class OrderServices method reserveInventory.

public static void reserveInventory(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, Locale locale, List<GenericValue> orderItemShipGroupInfo, List<String> dropShipGroupIds, Map<String, GenericValue> itemValuesBySeqId, String orderTypeId, String productStoreId, List<String> resErrorMessages) throws GeneralException {
    boolean isImmediatelyFulfilled = false;
    GenericValue productStore = null;
    if (UtilValidate.isNotEmpty(productStoreId)) {
        try {
            productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).cache().queryOne();
        } catch (GenericEntityException e) {
            throw new GeneralException(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotFindProductStoreWithID", UtilMisc.toMap("productStoreId", productStoreId), locale) + e.toString());
        }
    }
    if (productStore != null) {
        isImmediatelyFulfilled = "Y".equals(productStore.getString("isImmediatelyFulfilled"));
    }
    boolean reserveInventory = ("SALES_ORDER".equals(orderTypeId));
    if (reserveInventory && isImmediatelyFulfilled) {
        // don't reserve inventory if the product store has isImmediatelyFulfilled set, ie don't if in this store things are immediately fulfilled
        reserveInventory = false;
    }
    // decrement inventory available for each OrderItemShipGroupAssoc, within the same transaction
    if (UtilValidate.isNotEmpty(orderItemShipGroupInfo)) {
        for (GenericValue orderItemShipGroupAssoc : orderItemShipGroupInfo) {
            if ("OrderItemShipGroupAssoc".equals(orderItemShipGroupAssoc.getEntityName())) {
                if (dropShipGroupIds != null && dropShipGroupIds.contains(orderItemShipGroupAssoc.getString("shipGroupSeqId"))) {
                    // the items in the drop ship groups are not reserved
                    continue;
                }
                GenericValue orderItem = itemValuesBySeqId.get(orderItemShipGroupAssoc.get("orderItemSeqId"));
                GenericValue orderItemShipGroup = orderItemShipGroupAssoc.getRelatedOne("OrderItemShipGroup", false);
                String shipGroupFacilityId = orderItemShipGroup.getString("facilityId");
                String itemStatus = orderItem.getString("statusId");
                if ("ITEM_REJECTED".equals(itemStatus) || "ITEM_CANCELLED".equals(itemStatus) || "ITEM_COMPLETED".equals(itemStatus)) {
                    Debug.logInfo("Order item [" + orderItem.getString("orderId") + " / " + orderItem.getString("orderItemSeqId") + "] is not in a proper status for reservation", module);
                    continue;
                }
                if (// only reserve product items, ignore non-product items
                UtilValidate.isNotEmpty(orderItem.getString("productId")) && !"RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) {
                    // ignore for rental
                    try {
                        // get the product of the order item
                        GenericValue product = orderItem.getRelatedOne("Product", false);
                        if (product == null) {
                            Debug.logError("Error when looking up product in reserveInventory service", module);
                            resErrorMessages.add("Error when looking up product in reserveInventory service");
                            continue;
                        }
                        if (reserveInventory) {
                            // for MARKETING_PKG_PICK reserve the components
                            if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG_PICK")) {
                                Map<String, Object> componentsRes = dispatcher.runSync("getAssociatedProducts", UtilMisc.toMap("productId", orderItem.getString("productId"), "type", "PRODUCT_COMPONENT"));
                                if (ServiceUtil.isError(componentsRes)) {
                                    resErrorMessages.add(ServiceUtil.getErrorMessage(componentsRes));
                                    continue;
                                }
                                List<GenericValue> assocProducts = UtilGenerics.checkList(componentsRes.get("assocProducts"));
                                for (GenericValue productAssoc : assocProducts) {
                                    BigDecimal quantityOrd = productAssoc.getBigDecimal("quantity");
                                    BigDecimal quantityKit = orderItemShipGroupAssoc.getBigDecimal("quantity");
                                    BigDecimal quantity = quantityOrd.multiply(quantityKit);
                                    Map<String, Object> reserveInput = new HashMap<>();
                                    reserveInput.put("productStoreId", productStoreId);
                                    reserveInput.put("productId", productAssoc.getString("productIdTo"));
                                    reserveInput.put("orderId", orderItem.getString("orderId"));
                                    reserveInput.put("orderItemSeqId", orderItem.getString("orderItemSeqId"));
                                    reserveInput.put("shipGroupSeqId", orderItemShipGroupAssoc.getString("shipGroupSeqId"));
                                    reserveInput.put("quantity", quantity);
                                    reserveInput.put("userLogin", userLogin);
                                    reserveInput.put("facilityId", shipGroupFacilityId);
                                    Map<String, Object> reserveResult = dispatcher.runSync("reserveStoreInventory", reserveInput);
                                    if (ServiceUtil.isError(reserveResult)) {
                                        String invErrMsg = "The product ";
                                        if (product != null) {
                                            invErrMsg += getProductName(product, orderItem);
                                        }
                                        invErrMsg += " with ID " + orderItem.getString("productId") + " is no longer in stock. Please try reducing the quantity or removing the product from this order.";
                                        resErrorMessages.add(invErrMsg);
                                    }
                                }
                            } else {
                                // reserve the product
                                Map<String, Object> reserveInput = new HashMap<>();
                                reserveInput.put("productStoreId", productStoreId);
                                reserveInput.put("productId", orderItem.getString("productId"));
                                reserveInput.put("orderId", orderItem.getString("orderId"));
                                reserveInput.put("orderItemSeqId", orderItem.getString("orderItemSeqId"));
                                reserveInput.put("shipGroupSeqId", orderItemShipGroupAssoc.getString("shipGroupSeqId"));
                                reserveInput.put("facilityId", shipGroupFacilityId);
                                // use the quantity from the orderItemShipGroupAssoc, NOT the orderItem, these are reserved by item-group assoc
                                reserveInput.put("quantity", orderItemShipGroupAssoc.getBigDecimal("quantity"));
                                reserveInput.put("userLogin", userLogin);
                                Map<String, Object> reserveResult = dispatcher.runSync("reserveStoreInventory", reserveInput);
                                if (ServiceUtil.isError(reserveResult)) {
                                    String invErrMsg = "The product ";
                                    invErrMsg += getProductName(product, orderItem);
                                    invErrMsg += " with ID " + orderItem.getString("productId") + " is no longer in stock. Please try reducing the quantity or removing the product from this order.";
                                    resErrorMessages.add(invErrMsg);
                                }
                            }
                        }
                        // If the product is a marketing package auto, attempt to create enough packages to bring ATP back to 0, won't necessarily create enough to cover this order.
                        if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG_AUTO")) {
                            // do something tricky here: run as the "system" user
                            // that can actually create and run a production run
                            GenericValue permUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne();
                            Map<String, Object> inputMap = new HashMap<>();
                            if (UtilValidate.isNotEmpty(shipGroupFacilityId)) {
                                inputMap.put("facilityId", shipGroupFacilityId);
                            } else {
                                inputMap.put("facilityId", productStore.getString("inventoryFacilityId"));
                            }
                            inputMap.put("orderId", orderItem.getString("orderId"));
                            inputMap.put("orderItemSeqId", orderItem.getString("orderItemSeqId"));
                            inputMap.put("userLogin", permUserLogin);
                            Map<String, Object> prunResult = dispatcher.runSync("createProductionRunForMktgPkg", inputMap);
                            if (ServiceUtil.isError(prunResult)) {
                                Debug.logError(ServiceUtil.getErrorMessage(prunResult) + " for input:" + inputMap, module);
                            }
                        }
                    } catch (GenericServiceException e) {
                        String errMsg = "Fatal error calling reserveStoreInventory service: " + e.toString();
                        Debug.logError(e, errMsg, module);
                        resErrorMessages.add(errMsg);
                    }
                }
                // rent item
                if (UtilValidate.isNotEmpty(orderItem.getString("productId")) && "RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) {
                    try {
                        // get the product of the order item
                        GenericValue product = orderItem.getRelatedOne("Product", false);
                        if (product == null) {
                            Debug.logError("Error when looking up product in reserveInventory service", module);
                            resErrorMessages.add("Error when looking up product in reserveInventory service");
                            continue;
                        }
                        // check product type for rent
                        String productType = (String) product.get("productTypeId");
                        if ("ASSET_USAGE_OUT_IN".equals(productType)) {
                            if (reserveInventory) {
                                // for MARKETING_PKG_PICK reserve the components
                                if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG_PICK")) {
                                    Map<String, Object> componentsRes = dispatcher.runSync("getAssociatedProducts", UtilMisc.toMap("productId", orderItem.getString("productId"), "type", "PRODUCT_COMPONENT"));
                                    if (ServiceUtil.isError(componentsRes)) {
                                        resErrorMessages.add((String) componentsRes.get(ModelService.ERROR_MESSAGE));
                                        continue;
                                    }
                                    List<GenericValue> assocProducts = UtilGenerics.checkList(componentsRes.get("assocProducts"));
                                    for (GenericValue productAssoc : assocProducts) {
                                        BigDecimal quantityOrd = productAssoc.getBigDecimal("quantity");
                                        BigDecimal quantityKit = orderItemShipGroupAssoc.getBigDecimal("quantity");
                                        BigDecimal quantity = quantityOrd.multiply(quantityKit);
                                        Map<String, Object> reserveInput = new HashMap<>();
                                        reserveInput.put("productStoreId", productStoreId);
                                        reserveInput.put("productId", productAssoc.getString("productIdTo"));
                                        reserveInput.put("orderId", orderItem.getString("orderId"));
                                        reserveInput.put("orderItemSeqId", orderItem.getString("orderItemSeqId"));
                                        reserveInput.put("shipGroupSeqId", orderItemShipGroupAssoc.getString("shipGroupSeqId"));
                                        reserveInput.put("quantity", quantity);
                                        reserveInput.put("userLogin", userLogin);
                                        reserveInput.put("facilityId", shipGroupFacilityId);
                                        Map<String, Object> reserveResult = dispatcher.runSync("reserveStoreInventory", reserveInput);
                                        if (ServiceUtil.isError(reserveResult)) {
                                            String invErrMsg = "The product ";
                                            invErrMsg += getProductName(product, orderItem);
                                            invErrMsg += " with ID " + orderItem.getString("productId") + " is no longer in stock. Please try reducing the quantity or removing the product from this order.";
                                            resErrorMessages.add(invErrMsg);
                                        }
                                    }
                                } else {
                                    // reserve the product
                                    Map<String, Object> reserveInput = new HashMap<>();
                                    reserveInput.put("productStoreId", productStoreId);
                                    reserveInput.put("productId", orderItem.getString("productId"));
                                    reserveInput.put("orderId", orderItem.getString("orderId"));
                                    reserveInput.put("orderItemSeqId", orderItem.getString("orderItemSeqId"));
                                    reserveInput.put("shipGroupSeqId", orderItemShipGroupAssoc.getString("shipGroupSeqId"));
                                    reserveInput.put("facilityId", shipGroupFacilityId);
                                    // use the quantity from the orderItemShipGroupAssoc, NOT the orderItem, these are reserved by item-group assoc
                                    reserveInput.put("quantity", orderItemShipGroupAssoc.getBigDecimal("quantity"));
                                    reserveInput.put("userLogin", userLogin);
                                    Map<String, Object> reserveResult = dispatcher.runSync("reserveStoreInventory", reserveInput);
                                    if (ServiceUtil.isError(reserveResult)) {
                                        String invErrMsg = "The product ";
                                        invErrMsg += getProductName(product, orderItem);
                                        invErrMsg += " with ID " + orderItem.getString("productId") + " is no longer in stock. Please try reducing the quantity or removing the product from this order.";
                                        resErrorMessages.add(invErrMsg);
                                    }
                                }
                            }
                            if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG_AUTO")) {
                                GenericValue permUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne();
                                Map<String, Object> inputMap = new HashMap<>();
                                if (UtilValidate.isNotEmpty(shipGroupFacilityId)) {
                                    inputMap.put("facilityId", shipGroupFacilityId);
                                } else {
                                    inputMap.put("facilityId", productStore.getString("inventoryFacilityId"));
                                }
                                inputMap.put("orderId", orderItem.getString("orderId"));
                                inputMap.put("orderItemSeqId", orderItem.getString("orderItemSeqId"));
                                inputMap.put("userLogin", permUserLogin);
                                Map<String, Object> prunResult = dispatcher.runSync("createProductionRunForMktgPkg", inputMap);
                                if (ServiceUtil.isError(prunResult)) {
                                    Debug.logError(ServiceUtil.getErrorMessage(prunResult) + " for input:" + inputMap, module);
                                }
                            }
                        }
                    } catch (GenericServiceException e) {
                        String errMsg = "Fatal error calling reserveStoreInventory service: " + e.toString();
                        Debug.logError(e, errMsg, module);
                        resErrorMessages.add(errMsg);
                    }
                }
            }
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal)

Aggregations

GeneralException (org.apache.ofbiz.base.util.GeneralException)216 GenericValue (org.apache.ofbiz.entity.GenericValue)133 Delegator (org.apache.ofbiz.entity.Delegator)101 Locale (java.util.Locale)81 HashMap (java.util.HashMap)71 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)68 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)68 IOException (java.io.IOException)65 BigDecimal (java.math.BigDecimal)55 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)54 Writer (java.io.Writer)29 LinkedList (java.util.LinkedList)29 Map (java.util.Map)29 Timestamp (java.sql.Timestamp)26 StringWriter (java.io.StringWriter)19 Environment (freemarker.core.Environment)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)14 HttpSession (javax.servlet.http.HttpSession)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13