Search in sources :

Example 16 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PromoServices method createProductPromoCodeSet.

public static Map<String, Object> createProductPromoCodeSet(DispatchContext dctx, Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Long quantity = (Long) context.get("quantity");
    int codeLength = (Integer) context.get("codeLength");
    String promoCodeLayout = (String) context.get("promoCodeLayout");
    // For PromoCodes we give the option not to use chars that are easy to mix up like 0<>O, 1<>I, ...
    boolean useSmartLayout = false;
    boolean useNormalLayout = false;
    if ("smart".equals(promoCodeLayout)) {
        useSmartLayout = true;
    } else if ("normal".equals(promoCodeLayout)) {
        useNormalLayout = true;
    }
    String newPromoCodeId = "";
    StringBuilder bankOfNumbers = new StringBuilder();
    bankOfNumbers.append(UtilProperties.getMessage(resource, "ProductPromoCodesCreated", locale));
    for (long i = 0; i < quantity; i++) {
        Map<String, Object> createProductPromoCodeMap = null;
        boolean foundUniqueNewCode = false;
        long count = 0;
        while (!foundUniqueNewCode) {
            if (useSmartLayout) {
                newPromoCodeId = RandomStringUtils.random(codeLength, smartChars);
            } else if (useNormalLayout) {
                newPromoCodeId = RandomStringUtils.randomAlphanumeric(codeLength);
            }
            GenericValue existingPromoCode = null;
            try {
                existingPromoCode = EntityQuery.use(delegator).from("ProductPromoCode").where("productPromoCodeId", newPromoCodeId).cache().queryOne();
            } catch (GenericEntityException e) {
                Debug.logWarning("Could not find ProductPromoCode for just generated ID: " + newPromoCodeId, module);
            }
            if (existingPromoCode == null) {
                foundUniqueNewCode = true;
            }
            count++;
            if (count > 999999) {
                return ServiceUtil.returnError("Unable to locate unique PromoCode! Length [" + codeLength + "]");
            }
        }
        try {
            Map<String, Object> newContext = dctx.makeValidContext("createProductPromoCode", ModelService.IN_PARAM, context);
            newContext.put("productPromoCodeId", newPromoCodeId);
            createProductPromoCodeMap = dispatcher.runSync("createProductPromoCode", newContext);
        } catch (GenericServiceException err) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeCannotBeCreated", locale), null, null, null);
        }
        if (ServiceUtil.isError(createProductPromoCodeMap)) {
            // what to do here? try again?
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeCannotBeCreated", locale), null, null, createProductPromoCodeMap);
        }
        bankOfNumbers.append((String) createProductPromoCodeMap.get("productPromoCodeId"));
        bankOfNumbers.append(",");
    }
    return ServiceUtil.returnSuccess(bankOfNumbers.toString());
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 17 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class SubscriptionServices method runServiceOnSubscriptionExpiry.

public static Map<String, Object> runServiceOnSubscriptionExpiry(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Map<String, Object> result = new HashMap<>();
    Map<String, Object> expiryMap = new HashMap<>();
    String gracePeriodOnExpiry = null;
    String gracePeriodOnExpiryUomId = null;
    String subscriptionId = null;
    Timestamp expirationCompletedDate = null;
    try {
        EntityCondition cond1 = EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, "N");
        EntityCondition cond2 = EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, null);
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(cond1, cond2), EntityOperator.OR);
        List<GenericValue> subscriptionList = null;
        subscriptionList = EntityQuery.use(delegator).from("Subscription").where(cond).queryList();
        if (subscriptionList != null) {
            for (GenericValue subscription : subscriptionList) {
                expirationCompletedDate = subscription.getTimestamp("expirationCompletedDate");
                if (expirationCompletedDate == null) {
                    Calendar currentDate = Calendar.getInstance();
                    currentDate.setTime(UtilDateTime.nowTimestamp());
                    // check if the thruDate + grace period (if provided) is earlier than today's date
                    Calendar endDateSubscription = Calendar.getInstance();
                    int field = Calendar.MONTH;
                    String subscriptionResourceId = subscription.getString("subscriptionResourceId");
                    GenericValue subscriptionResource = null;
                    subscriptionResource = EntityQuery.use(delegator).from("SubscriptionResource").where("subscriptionResourceId", subscriptionResourceId).queryOne();
                    subscriptionId = subscription.getString("subscriptionId");
                    gracePeriodOnExpiry = subscription.getString("gracePeriodOnExpiry");
                    gracePeriodOnExpiryUomId = subscription.getString("gracePeriodOnExpiryUomId");
                    String serviceNameOnExpiry = subscriptionResource.getString("serviceNameOnExpiry");
                    endDateSubscription.setTime(subscription.getTimestamp("thruDate"));
                    if (gracePeriodOnExpiry != null && gracePeriodOnExpiryUomId != null) {
                        if ("TF_day".equals(gracePeriodOnExpiryUomId)) {
                            field = Calendar.DAY_OF_YEAR;
                        } else if ("TF_wk".equals(gracePeriodOnExpiryUomId)) {
                            field = Calendar.WEEK_OF_YEAR;
                        } else if ("TF_mon".equals(gracePeriodOnExpiryUomId)) {
                            field = Calendar.MONTH;
                        } else if ("TF_yr".equals(gracePeriodOnExpiryUomId)) {
                            field = Calendar.YEAR;
                        } else {
                            Debug.logWarning("Don't know anything about gracePeriodOnExpiryUomId [" + gracePeriodOnExpiryUomId + "], defaulting to month", module);
                        }
                        endDateSubscription.add(field, Integer.parseInt(gracePeriodOnExpiry));
                    }
                    if ((currentDate.after(endDateSubscription) || currentDate.equals(endDateSubscription)) && serviceNameOnExpiry != null) {
                        if (userLogin != null) {
                            expiryMap.put("userLogin", userLogin);
                        }
                        if (subscriptionId != null) {
                            expiryMap.put("subscriptionId", subscriptionId);
                        }
                        result = dispatcher.runSync(serviceNameOnExpiry, expiryMap);
                        if (ServiceUtil.isSuccess(result)) {
                            subscription.set("expirationCompletedDate", UtilDateTime.nowTimestamp());
                            delegator.store(subscription);
                            Debug.logInfo("Subscription expired successfully for subscription ID:" + subscriptionId, module);
                        } else if (ServiceUtil.isError(result)) {
                            result = null;
                            Debug.logError("Error expiring subscription while processing with subscriptionId: " + subscriptionId, module);
                        }
                        if (result != null && subscriptionId != null) {
                            Debug.logInfo("Service mentioned in serviceNameOnExpiry called with result: " + ServiceUtil.makeSuccessMessage(result, "", "", "", ""), module);
                        } else if (result == null && subscriptionId != null) {
                            Debug.logError("Subscription couldn't be expired for subscriptionId: " + subscriptionId, module);
                            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "ProductSubscriptionCouldntBeExpired", UtilMisc.toMap("subscriptionId", subscriptionId), locale));
                        }
                    }
                }
            }
        }
    } catch (GenericServiceException e) {
        Debug.logError("Error while calling service specified in serviceNameOnExpiry", module);
        return ServiceUtil.returnError(e.toString());
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    return result;
}
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) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 18 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class SubscriptionServices method processExtendSubscriptionByProduct.

public static Map<String, Object> processExtendSubscriptionByProduct(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String productId = (String) context.get("productId");
    Integer qty = (Integer) context.get("quantity");
    Locale locale = (Locale) context.get("locale");
    if (qty == null) {
        qty = Integer.valueOf(1);
    }
    Timestamp orderCreatedDate = (Timestamp) context.get("orderCreatedDate");
    if (orderCreatedDate == null) {
        orderCreatedDate = UtilDateTime.nowTimestamp();
    }
    try {
        List<GenericValue> productSubscriptionResourceList = EntityQuery.use(delegator).from("ProductSubscriptionResource").where("productId", productId).cache(true).filterByDate(orderCreatedDate, "fromDate", "thruDate", "purchaseFromDate", "purchaseThruDate").queryList();
        if (productSubscriptionResourceList.size() == 0) {
            Debug.logError("No ProductSubscriptionResource found for productId: " + productId, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionResourceNotFound", UtilMisc.toMap("productId", productId), locale));
        }
        for (GenericValue productSubscriptionResource : productSubscriptionResourceList) {
            Long useTime = productSubscriptionResource.getLong("useTime");
            Integer newUseTime = Integer.valueOf(0);
            if (useTime != null) {
                newUseTime = Integer.valueOf(useTime.intValue() * qty.intValue());
            }
            Map<String, Object> subContext = UtilMisc.makeMapWritable(context);
            subContext.put("useTime", newUseTime);
            subContext.put("useTimeUomId", productSubscriptionResource.get("useTimeUomId"));
            subContext.put("useRoleTypeId", productSubscriptionResource.get("useRoleTypeId"));
            subContext.put("subscriptionResourceId", productSubscriptionResource.get("subscriptionResourceId"));
            subContext.put("automaticExtend", productSubscriptionResource.get("automaticExtend"));
            subContext.put("canclAutmExtTime", productSubscriptionResource.get("canclAutmExtTime"));
            subContext.put("canclAutmExtTimeUomId", productSubscriptionResource.get("canclAutmExtTimeUomId"));
            subContext.put("gracePeriodOnExpiry", productSubscriptionResource.get("gracePeriodOnExpiry"));
            subContext.put("gracePeriodOnExpiryUomId", productSubscriptionResource.get("gracePeriodOnExpiryUomId"));
            Map<String, Object> ctx = dctx.getModelService("processExtendSubscription").makeValid(subContext, ModelService.IN_PARAM);
            Map<String, Object> processExtendSubscriptionResult = dispatcher.runSync("processExtendSubscription", ctx);
            if (ServiceUtil.isError(processExtendSubscriptionResult)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionByProductError", UtilMisc.toMap("productId", productId), locale), null, null, processExtendSubscriptionResult);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, e.toString(), module);
        return ServiceUtil.returnError(e.toString());
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Timestamp(java.sql.Timestamp)

Example 19 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class SubscriptionServices method processExtendSubscription.

public static Map<String, Object> processExtendSubscription(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    String partyId = (String) context.get("partyId");
    String subscriptionResourceId = (String) context.get("subscriptionResourceId");
    String inventoryItemId = (String) context.get("inventoryItemId");
    String roleTypeId = (String) context.get("useRoleTypeId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Integer useTime = (Integer) context.get("useTime");
    String useTimeUomId = (String) context.get("useTimeUomId");
    String alwaysCreateNewRecordStr = (String) context.get("alwaysCreateNewRecord");
    Locale locale = (Locale) context.get("locale");
    boolean alwaysCreateNewRecord = !"N".equals(alwaysCreateNewRecordStr);
    GenericValue lastSubscription = null;
    try {
        Map<String, String> subscriptionFindMap = UtilMisc.toMap("partyId", partyId, "subscriptionResourceId", subscriptionResourceId);
        // if this subscription is attached to something the customer owns, filter by that too
        if (UtilValidate.isNotEmpty(inventoryItemId)) {
            subscriptionFindMap.put("inventoryItemId", inventoryItemId);
        }
        List<GenericValue> subscriptionList = EntityQuery.use(delegator).from("Subscription").where(subscriptionFindMap).queryList();
        // DEJ20070718 DON'T filter by date, we want to consider all subscriptions: List listFiltered = EntityUtil.filterByDate(subscriptionList, true);
        List<GenericValue> listOrdered = EntityUtil.orderBy(subscriptionList, UtilMisc.toList("-fromDate"));
        if (listOrdered.size() > 0) {
            lastSubscription = listOrdered.get(0);
        }
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.toString());
    }
    GenericValue newSubscription = null;
    if (lastSubscription == null || alwaysCreateNewRecord) {
        newSubscription = delegator.makeValue("Subscription");
        newSubscription.set("subscriptionResourceId", subscriptionResourceId);
        newSubscription.set("partyId", partyId);
        newSubscription.set("roleTypeId", roleTypeId);
        newSubscription.set("productId", context.get("productId"));
        newSubscription.set("orderId", context.get("orderId"));
        newSubscription.set("orderItemSeqId", context.get("orderItemSeqId"));
        newSubscription.set("automaticExtend", context.get("automaticExtend"));
        newSubscription.set("canclAutmExtTimeUomId", context.get("canclAutmExtTimeUomId"));
        newSubscription.set("canclAutmExtTime", context.get("canclAutmExtTime"));
    } else {
        newSubscription = lastSubscription;
    }
    newSubscription.set("inventoryItemId", inventoryItemId);
    Timestamp thruDate = lastSubscription != null ? (Timestamp) lastSubscription.get("thruDate") : null;
    // set the fromDate, one way or another
    if (thruDate == null) {
        // no thruDate? start with NOW
        thruDate = nowTimestamp;
        newSubscription.set("fromDate", nowTimestamp);
    } else {
        // month and buy another month, we want that second month to start now and not last year
        if (thruDate.before(nowTimestamp)) {
            thruDate = nowTimestamp;
        }
        newSubscription.set("fromDate", thruDate);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(thruDate);
    int[] times = UomWorker.uomTimeToCalTime(useTimeUomId);
    if (times != null) {
        calendar.add(times[0], (useTime.intValue() * times[1]));
    } else {
        Debug.logWarning("Don't know anything about useTimeUomId [" + useTimeUomId + "], defaulting to month", module);
        calendar.add(Calendar.MONTH, useTime);
    }
    thruDate = new Timestamp(calendar.getTimeInMillis());
    newSubscription.set("thruDate", thruDate);
    Map<String, Object> result = ServiceUtil.returnSuccess();
    try {
        if (lastSubscription != null && !alwaysCreateNewRecord) {
            Map<String, Object> updateSubscriptionMap = dctx.getModelService("updateSubscription").makeValid(newSubscription, ModelService.IN_PARAM);
            updateSubscriptionMap.put("userLogin", EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne());
            Map<String, Object> updateSubscriptionResult = dispatcher.runSync("updateSubscription", updateSubscriptionMap);
            result.put("subscriptionId", updateSubscriptionMap.get("subscriptionId"));
            if (ServiceUtil.isError(updateSubscriptionResult)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionUpdateError", UtilMisc.toMap("subscriptionId", updateSubscriptionMap.get("subscriptionId")), locale), null, null, updateSubscriptionResult);
            }
        } else {
            Map<String, Object> ensurePartyRoleMap = new HashMap<>();
            if (UtilValidate.isNotEmpty(roleTypeId)) {
                ensurePartyRoleMap.put("partyId", partyId);
                ensurePartyRoleMap.put("roleTypeId", roleTypeId);
                ensurePartyRoleMap.put("userLogin", userLogin);
                Map<String, Object> createPartyRoleResult = dispatcher.runSync("ensurePartyRole", ensurePartyRoleMap);
                if (ServiceUtil.isError(createPartyRoleResult)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionPartyRoleCreationError", UtilMisc.toMap("subscriptionResourceId", subscriptionResourceId), locale), null, null, createPartyRoleResult);
                }
            }
            Map<String, Object> createSubscriptionMap = dctx.getModelService("createSubscription").makeValid(newSubscription, ModelService.IN_PARAM);
            createSubscriptionMap.put("userLogin", EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne());
            Map<String, Object> createSubscriptionResult = dispatcher.runSync("createSubscription", createSubscriptionMap);
            if (ServiceUtil.isError(createSubscriptionResult)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionCreateError", UtilMisc.toMap("subscriptionResourceId", subscriptionResourceId), locale), null, null, createSubscriptionResult);
            }
            result.put("subscriptionId", createSubscriptionResult.get("subscriptionId"));
        }
    } catch (GenericEntityException | GenericServiceException e) {
        return ServiceUtil.returnError(e.toString());
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 20 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class ProductUtilServices method makeStandAloneFromSingleVariantVirtuals.

public static Map<String, Object> makeStandAloneFromSingleVariantVirtuals(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    Debug.logInfo("Starting makeStandAloneFromSingleVariantVirtuals", module);
    DynamicViewEntity dve = new DynamicViewEntity();
    dve.addMemberEntity("PVIRT", "Product");
    dve.addMemberEntity("PVA", "ProductAssoc");
    dve.addViewLink("PVIRT", "PVA", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("productId", "productId")));
    dve.addAlias("PVIRT", "productId", null, null, null, Boolean.TRUE, null);
    dve.addAlias("PVIRT", "salesDiscontinuationDate", null, null, null, null, null);
    dve.addAlias("PVA", "productAssocTypeId", null, null, null, null, null);
    dve.addAlias("PVA", "fromDate", null, null, null, null, null);
    dve.addAlias("PVA", "thruDate", null, null, null, null, null);
    dve.addAlias("PVA", "productIdToCount", "productIdTo", null, null, null, "count-distinct");
    EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS, "PRODUCT_VARIANT"), EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN, nowTimestamp))), EntityOperator.AND);
    EntityCondition havingCond = EntityCondition.makeCondition("productIdToCount", EntityOperator.EQUALS, Long.valueOf(1));
    EntityQuery eq = EntityQuery.use(delegator).select("productId", "productIdToCount").from(dve).where(condition).having(havingCond);
    try (EntityListIterator eliOne = eq.queryIterator()) {
        List<GenericValue> valueList = eliOne.getCompleteList();
        Debug.logInfo("Found " + valueList.size() + " virtual products with one variant to turn into a stand alone product.", module);
        int numWithOneOnly = 0;
        for (GenericValue value : valueList) {
            // has only one variant period, is it valid? should already be discontinued if not
            String productId = value.getString("productId");
            List<GenericValue> paList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList();
            // verify the query; tested on a bunch, looks good
            if (paList.size() != 1) {
                Debug.logInfo("Virtual product with ID " + productId + " should have 1 assoc, has " + paList.size(), module);
            } else {
                // for all virtuals with one variant move all info from virtual to variant and remove virtual, make variant as not a variant
                dispatcher.runSync("mergeVirtualWithSingleVariant", UtilMisc.<String, Object>toMap("productId", productId, "removeOld", Boolean.TRUE, "userLogin", userLogin));
                numWithOneOnly++;
                if (numWithOneOnly % 100 == 0) {
                    Debug.logInfo("Made " + numWithOneOnly + " virtual products with only one valid variant stand-alone products.", module);
                }
            }
        }
        EntityCondition conditionWithDates = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS, "PRODUCT_VARIANT"), EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN, nowTimestamp)), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp), EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp))), EntityOperator.AND);
        eq = EntityQuery.use(delegator).select("productId", "productIdToCount").from(dve).where(conditionWithDates).having(havingCond);
        try (EntityListIterator eliMulti = eq.queryIterator()) {
            List<GenericValue> valueMultiList = eliMulti.getCompleteList();
            Debug.logInfo("Found " + valueMultiList.size() + " virtual products with one VALID variant to pull the variant from to make a stand alone product.", module);
            int numWithOneValid = 0;
            for (GenericValue value : valueMultiList) {
                // has only one valid variant
                String productId = value.getString("productId");
                List<GenericValue> paList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList();
                // verify the query; tested on a bunch, looks good
                if (paList.size() != 1) {
                    Debug.logInfo("Virtual product with ID " + productId + " should have 1 assoc, has " + paList.size(), module);
                } else {
                    // for all virtuals with one valid variant move info from virtual to variant, put variant in categories from virtual, remove virtual from all categories but leave "family" otherwise intact, mark variant as not a variant
                    dispatcher.runSync("mergeVirtualWithSingleVariant", UtilMisc.<String, Object>toMap("productId", productId, "removeOld", Boolean.FALSE, "userLogin", userLogin));
                    numWithOneValid++;
                    if (numWithOneValid % 100 == 0) {
                        Debug.logInfo("Made " + numWithOneValid + " virtual products with one valid variant stand-alone products.", module);
                    }
                }
            }
            Debug.logInfo("Found virtual products with one valid variant: " + numWithOneValid + ", with one variant only: " + numWithOneOnly, module);
        } catch (GenericEntityException e) {
            Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
            errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_makeStandAloneFromSingleVariantVirtuals", messageMap, locale);
            Debug.logError(e, errMsg, module);
            return ServiceUtil.returnError(errMsg);
        }
    } catch (GenericEntityException | GenericServiceException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_makeStandAloneFromSingleVariantVirtuals", 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) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashMap(java.util.HashMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap)

Aggregations

LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)427 GenericValue (org.apache.ofbiz.entity.GenericValue)356 Delegator (org.apache.ofbiz.entity.Delegator)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)321 Locale (java.util.Locale)296 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)270 HashMap (java.util.HashMap)214 BigDecimal (java.math.BigDecimal)135 GeneralException (org.apache.ofbiz.base.util.GeneralException)87 Timestamp (java.sql.Timestamp)81 LinkedList (java.util.LinkedList)79 IOException (java.io.IOException)59 Map (java.util.Map)51 HttpSession (javax.servlet.http.HttpSession)49 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)28 ModelService (org.apache.ofbiz.service.ModelService)28 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)24 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)23 Security (org.apache.ofbiz.security.Security)20 ByteBuffer (java.nio.ByteBuffer)19