Search in sources :

Example 71 with GenericValue

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

the class ProductUtilServices method duplicateRelated.

protected static void duplicateRelated(GenericValue product, String title, String relatedEntityName, String productIdField, String variantProductId, Timestamp nowTimestamp, boolean removeOld, Delegator delegator, boolean test) throws GenericEntityException {
    List<GenericValue> relatedList = EntityUtil.filterByDate(product.getRelated(title + relatedEntityName, null, null, false), nowTimestamp);
    for (GenericValue relatedValue : relatedList) {
        GenericValue newRelatedValue = (GenericValue) relatedValue.clone();
        newRelatedValue.set(productIdField, variantProductId);
        // create a new one? see if one already exists with different from/thru dates
        ModelEntity modelEntity = relatedValue.getModelEntity();
        if (modelEntity.isField("fromDate")) {
            GenericPK findValue = newRelatedValue.getPrimaryKey();
            // can't just set to null, need to remove the value so it isn't a constraint in the query
            findValue.remove("fromDate");
            List<GenericValue> existingValueList = EntityQuery.use(delegator).from(relatedEntityName).where(findValue).filterByDate(nowTimestamp).queryList();
            if (existingValueList.size() > 0) {
                if (test) {
                    Debug.logInfo("Found " + existingValueList.size() + " existing values for related entity name: " + relatedEntityName + ", not copying, findValue is: " + findValue, module);
                }
                continue;
            }
            newRelatedValue.set("fromDate", nowTimestamp);
        }
        if (EntityQuery.use(delegator).from(relatedEntityName).where(EntityCondition.makeCondition(newRelatedValue.getPrimaryKey(), EntityOperator.AND)).queryCount() == 0) {
            if (test) {
                Debug.logInfo("Test mode, would create: " + newRelatedValue, module);
            } else {
                newRelatedValue.create();
            }
        }
    }
    if (removeOld) {
        if (test) {
            Debug.logInfo("Test mode, would remove related " + title + relatedEntityName + " with dummy key: " + product.getRelatedDummyPK(title + relatedEntityName), module);
        } else {
            product.removeRelated(title + relatedEntityName);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericPK(org.apache.ofbiz.entity.GenericPK) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 72 with GenericValue

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

the class ProductUtilServices method discVirtualsWithDiscVariants.

/**
 * First expire all ProductAssocs for all disc variants, then disc all virtuals that have all expired variant ProductAssocs
 */
public static Map<String, Object> discVirtualsWithDiscVariants(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    EntityCondition conditionOne = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("isVariant", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp)), EntityOperator.AND);
    try (EntityListIterator eliOne = EntityQuery.use(delegator).from("Product").where(conditionOne).queryIterator()) {
        GenericValue productOne = null;
        int numSoFarOne = 0;
        while ((productOne = eliOne.next()) != null) {
            String virtualProductId = ProductWorker.getVariantVirtualId(productOne);
            GenericValue virtualProduct = EntityQuery.use(delegator).from("Product").where("productId", virtualProductId).queryOne();
            if (virtualProduct == null) {
                continue;
            }
            List<GenericValue> passocList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", virtualProductId, "productIdTo", productOne.get("productId"), "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList();
            if (passocList.size() > 0) {
                for (GenericValue passoc : passocList) {
                    passoc.set("thruDate", nowTimestamp);
                    passoc.store();
                }
                numSoFarOne++;
                if (numSoFarOne % 500 == 0) {
                    Debug.logInfo("Expired variant ProductAssocs for " + numSoFarOne + " sales discontinued variant products.", module);
                }
            }
        }
        // get all non-discontinued virtuals, see if all variant ProductAssocs are expired, if discontinue
        EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("isVirtual", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp))), EntityOperator.AND);
        try (EntityListIterator eli = EntityQuery.use(delegator).from("Product").where(condition).queryIterator()) {
            GenericValue product = null;
            int numSoFar = 0;
            while ((product = eli.next()) != null) {
                List<GenericValue> passocList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", product.get("productId"), "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList();
                if (passocList.size() == 0) {
                    product.set("salesDiscontinuationDate", nowTimestamp);
                    delegator.store(product);
                    numSoFar++;
                    if (numSoFar % 500 == 0) {
                        Debug.logInfo("Sales discontinued " + numSoFar + " virtual products that have no valid variants.", module);
                    }
                }
            }
        } catch (GenericEntityException e) {
            Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
            errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_discVirtualsWithDiscVariants", messageMap, locale);
            Debug.logError(e, errMsg, module);
            return ServiceUtil.returnError(errMsg);
        }
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_discVirtualsWithDiscVariants", 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) 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)

Example 73 with GenericValue

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

the class VariantEvents method quickAddChosenVariant.

/**
 * Creates variant products from a virtual product and a combination of selectable features
 *@param request The HTTPRequest object for the current request
 *@param response The HTTPResponse object for the current request
 *@return String specifying the exit status of this event
 */
public static String quickAddChosenVariant(HttpServletRequest request, HttpServletResponse response) {
    String errMsg = "";
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String productId = request.getParameter("productId");
    String variantProductId = request.getParameter("variantProductId");
    String featureTypeSizeStr = request.getParameter("featureTypeSize");
    if (UtilValidate.isEmpty(productId)) {
        errMsg = UtilProperties.getMessage(resource, "variantevents.productId_required_but_missing", UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (UtilValidate.isEmpty(variantProductId)) {
        errMsg = UtilProperties.getMessage(resource, "variantevents.variantProductId_required_but_missing_enter_an_id", UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    int featureTypeSize = 0;
    try {
        featureTypeSize = Integer.parseInt(featureTypeSizeStr);
    } catch (NumberFormatException e) {
        Map<String, String> messageMap = UtilMisc.toMap("featureTypeSizeStr", featureTypeSizeStr);
        errMsg = UtilProperties.getMessage(resource, "variantevents.featureTypeSize_not_number", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    try {
        boolean beganTransacton = TransactionUtil.begin();
        try {
            // read the product, duplicate it with the given id
            GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
            if (product == null) {
                Map<String, String> messageMap = UtilMisc.toMap("productId", productId);
                errMsg = UtilProperties.getMessage(resource, "variantevents.product_not_found_with_ID", messageMap, UtilHttp.getLocale(request));
                TransactionUtil.rollback(beganTransacton, errMsg, null);
                request.setAttribute("_ERROR_MESSAGE_", errMsg);
                return "error";
            }
            // check if product exists
            GenericValue variantProduct = EntityQuery.use(delegator).from("Product").where("productId", variantProductId).queryOne();
            if (variantProduct == null) {
                // if product does not exist
                variantProduct = GenericValue.create(product);
                variantProduct.set("productId", variantProductId);
                variantProduct.set("isVirtual", "N");
                variantProduct.set("isVariant", "Y");
                variantProduct.set("primaryProductCategoryId", null);
                // create new
                variantProduct.create();
            } else {
                // if product does exist
                variantProduct.set("isVirtual", "N");
                variantProduct.set("isVariant", "Y");
                variantProduct.set("primaryProductCategoryId", null);
                // update entry
                variantProduct.store();
            }
            // add an association from productId to variantProductId of the PRODUCT_VARIANT
            GenericValue productAssoc = delegator.makeValue("ProductAssoc", UtilMisc.toMap("productId", productId, "productIdTo", variantProductId, "productAssocTypeId", "PRODUCT_VARIANT", "fromDate", UtilDateTime.nowTimestamp()));
            productAssoc.create();
            // add the selected standard features to the new product given the productFeatureIds
            for (int i = 0; i < featureTypeSize; i++) {
                String productFeatureId = request.getParameter("feature_" + i);
                if (productFeatureId == null) {
                    Map<String, String> messageMap = UtilMisc.toMap("i", Integer.toString(i));
                    errMsg = UtilProperties.getMessage(resource, "variantevents.productFeatureId_for_feature_type_number_not_found", messageMap, UtilHttp.getLocale(request));
                    TransactionUtil.rollback(beganTransacton, errMsg, null);
                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
                    return "error";
                }
                GenericValue productFeature = EntityQuery.use(delegator).from("ProductFeature").where("productFeatureId", productFeatureId).queryOne();
                GenericValue productFeatureAppl = delegator.makeValue("ProductFeatureAppl", UtilMisc.toMap("productId", variantProductId, "productFeatureId", productFeatureId, "productFeatureApplTypeId", "STANDARD_FEATURE", "fromDate", UtilDateTime.nowTimestamp()));
                // set the default seq num if it's there...
                if (productFeature != null) {
                    productFeatureAppl.set("sequenceNum", productFeature.get("defaultSequenceNum"));
                }
                productFeatureAppl.create();
            }
            TransactionUtil.commit(beganTransacton);
        } catch (GenericEntityException e) {
            Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
            errMsg = UtilProperties.getMessage(resource, "variantevents.entity_error_quick_add_variant_data", messageMap, UtilHttp.getLocale(request));
            TransactionUtil.rollback(beganTransacton, errMsg, null);
            Debug.logError(e, "Entity error creating quick add variant data", module);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (GenericTransactionException e) {
        Debug.logError(e, "Transaction error creating quick add variant data", module);
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resource, "variantevents.transaction_error_quick_add_variant_data", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    Map<String, String> messageMap = UtilMisc.toMap("variantProductId", variantProductId);
    String sucMsg = UtilProperties.getMessage(resource, "variantevents.successfully_created_variant_product_with_id", messageMap, UtilHttp.getLocale(request));
    request.setAttribute("_EVENT_MESSAGE_", sucMsg);
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) Map(java.util.Map)

Example 74 with GenericValue

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

the class ProductStoreEvents method getChildProductStoreGroupTree.

// Please note : the structure of map in this function is according to the JSON data map of the jsTree
@SuppressWarnings("unchecked")
public static String getChildProductStoreGroupTree(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String parentGroupId = request.getParameter("parentGroupId");
    String onclickFunction = request.getParameter("onclickFunction");
    List productStoreGroupList = new LinkedList();
    List<GenericValue> children;
    List<String> sortList = org.apache.ofbiz.base.util.UtilMisc.toList("sequenceNum");
    try {
        GenericValue productStoreGroup = EntityQuery.use(delegator).from("ProductStoreGroup").where("productStoreGroupId", parentGroupId).cache(true).queryOne();
        if (productStoreGroup != null) {
            children = EntityQuery.use(delegator).from("ProductStoreGroupRollupAndChild").where("parentGroupId", parentGroupId).cache(true).filterByDate().queryList();
            if (UtilValidate.isNotEmpty(children)) {
                for (GenericValue child : children) {
                    String productStoreGroupId = child.getString("productStoreGroupId");
                    Map josonMap = new HashMap();
                    List<GenericValue> childList = null;
                    // Get the child list of chosen category
                    childList = EntityQuery.use(delegator).from("ProductStoreGroupRollupAndChild").where("parentGroupId", productStoreGroupId).cache(true).filterByDate().queryList();
                    if (UtilValidate.isNotEmpty(childList)) {
                        josonMap.put("state", "closed");
                    }
                    Map dataMap = new HashMap();
                    Map dataAttrMap = new HashMap();
                    dataAttrMap.put("onClick", onclickFunction + "('" + productStoreGroupId + "')");
                    String hrefStr = "EditProductStoreGroupAndAssoc";
                    dataAttrMap.put("href", hrefStr);
                    dataMap.put("attr", dataAttrMap);
                    dataMap.put("title", child.get("productStoreGroupName") + " [" + child.get("productStoreGroupId") + "]");
                    josonMap.put("data", dataMap);
                    Map attrMap = new HashMap();
                    attrMap.put("parentGroupId", productStoreGroupId);
                    josonMap.put("attr", attrMap);
                    josonMap.put("sequenceNum", child.get("sequenceNum"));
                    josonMap.put("title", child.get("productStoreGroupName"));
                    productStoreGroupList.add(josonMap);
                }
                List<Map<Object, Object>> sortedProductStoreGroupList = UtilMisc.sortMaps(productStoreGroupList, sortList);
                request.setAttribute("storeGroupTree", sortedProductStoreGroupList);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return "error";
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) List(java.util.List) LinkedList(java.util.LinkedList) HashMap(java.util.HashMap) Map(java.util.Map) LinkedList(java.util.LinkedList)

Example 75 with GenericValue

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

the class ProductStoreWorker method isStoreInventoryRequiredAndAvailable.

/**
 * This method is used in the showcart pages to determine whether or not to show the inventory message and
 * in the productdetail pages to determine whether or not to show the item as out of stock.
 *
 * @param request ServletRequest (or HttpServletRequest of course)
 * @param product GenericValue representing the product in question
 * @param quantity Quantity desired.
 * @param wantRequired If true then inventory required must be true for the result to be true, if false must be false; if null don't care
 * @param wantAvailable If true then inventory avilable must be true for the result to be true, if false must be false; if null don't care
 */
public static boolean isStoreInventoryRequiredAndAvailable(ServletRequest request, GenericValue product, BigDecimal quantity, Boolean wantRequired, Boolean wantAvailable) {
    GenericValue productStore = getProductStore(request);
    if (productStore == null) {
        Debug.logWarning("No ProductStore found, return false for inventory check", module);
        return false;
    }
    if (product == null) {
        Debug.logWarning("No Product passed, return false for inventory check", module);
        return false;
    }
    if (quantity == null)
        quantity = BigDecimal.ONE;
    String productStoreId = productStore.getString("productStoreId");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    try {
        Boolean requiredOkay = null;
        if (wantRequired != null) {
            Map<String, Object> invReqResult = dispatcher.runSync("isStoreInventoryRequired", UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"), "product", product, "productStore", productStore));
            if (ServiceUtil.isError(invReqResult)) {
                Debug.logError("Error calling isStoreInventoryRequired service, result is: " + invReqResult, module);
                return false;
            }
            requiredOkay = Boolean.valueOf(wantRequired.booleanValue() == "Y".equals(invReqResult.get("requireInventory")));
        }
        Boolean availableOkay = null;
        if (wantAvailable != null) {
            Map<String, Object> invAvailResult = dispatcher.runSync("isStoreInventoryAvailable", UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"), "product", product, "productStore", productStore, "quantity", quantity));
            if (ServiceUtil.isError(invAvailResult)) {
                Debug.logError("Error calling isStoreInventoryAvailable service, result is: " + invAvailResult, module);
                return false;
            }
            availableOkay = Boolean.valueOf(wantAvailable.booleanValue() == "Y".equals(invAvailResult.get("available")));
        }
        if ((requiredOkay == null || requiredOkay.booleanValue()) && (availableOkay == null || availableOkay.booleanValue())) {
            return true;
        } else {
            return false;
        }
    } catch (GenericServiceException e) {
        String errMsg = "Fatal error calling inventory checking services: " + e.toString();
        Debug.logError(e, errMsg, module);
        return false;
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)1422 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)871 Delegator (org.apache.ofbiz.entity.Delegator)721 Locale (java.util.Locale)505 HashMap (java.util.HashMap)463 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)370 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)356 BigDecimal (java.math.BigDecimal)338 LinkedList (java.util.LinkedList)312 Timestamp (java.sql.Timestamp)202 GeneralException (org.apache.ofbiz.base.util.GeneralException)168 Map (java.util.Map)155 IOException (java.io.IOException)116 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)97 HttpSession (javax.servlet.http.HttpSession)89 ArrayList (java.util.ArrayList)69 Security (org.apache.ofbiz.security.Security)69 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)59 List (java.util.List)56 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)52