Search in sources :

Example 1 with RecurrenceInfoException

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

the class ProductPromoWorker method checkCondition.

private static boolean checkCondition(GenericValue productPromoCond, ShoppingCart cart, Delegator delegator, LocalDispatcher dispatcher, Timestamp nowTimestamp) throws GenericEntityException {
    String condValue = productPromoCond.getString("condValue");
    String otherValue = productPromoCond.getString("otherValue");
    String inputParamEnumId = productPromoCond.getString("inputParamEnumId");
    String operatorEnumId = productPromoCond.getString("operatorEnumId");
    String shippingMethod = "";
    String carrierPartyId = "";
    if (otherValue != null && otherValue.contains("@")) {
        carrierPartyId = otherValue.substring(0, otherValue.indexOf('@'));
        shippingMethod = otherValue.substring(otherValue.indexOf('@') + 1);
        otherValue = "";
    }
    String partyId = cart.getPartyId();
    GenericValue userLogin = cart.getUserLogin();
    if (userLogin == null) {
        userLogin = cart.getAutoUserLogin();
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("Checking promotion condition: " + productPromoCond, module);
    }
    Integer compareBase = null;
    if ("PPIP_SERVICE".equals(inputParamEnumId)) {
        Map<String, Object> serviceCtx = UtilMisc.<String, Object>toMap("productPromoCond", productPromoCond, "shoppingCart", cart, "nowTimestamp", nowTimestamp);
        Map<String, Object> condResult;
        try {
            condResult = dispatcher.runSync(condValue, serviceCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Fatal error calling promo condition check service [" + condValue + "]", module);
            return false;
        }
        if (ServiceUtil.isError(condResult)) {
            Debug.logError("Error calling calling promo condition check service [" + condValue + "]", module);
            return false;
        }
        Boolean directResult = (Boolean) condResult.get("directResult");
        if (directResult != null) {
            return directResult.booleanValue();
        }
        compareBase = (Integer) condResult.get("compareBase");
        if (condResult.containsKey("operatorEnumId")) {
            operatorEnumId = (String) condResult.get("operatorEnumId");
        }
    } else if ("PPIP_PRODUCT_AMOUNT".equals(inputParamEnumId)) {
        // for this type of promo force the operatorEnumId = PPC_EQ, effectively ignore that setting because the comparison is implied in the code
        operatorEnumId = "PPC_EQ";
        // this type of condition requires items involved to not be involved in any other quantity consuming cond/action, and does not pro-rate the price, just uses the base price
        BigDecimal amountNeeded = BigDecimal.ZERO;
        if (UtilValidate.isNotEmpty(condValue)) {
            amountNeeded = new BigDecimal(condValue);
        }
        Set<String> productIds = ProductPromoWorker.getPromoRuleCondProductIds(productPromoCond, delegator, nowTimestamp);
        List<ShoppingCartItem> lineOrderedByBasePriceList = cart.getLineListOrderedByBasePrice(false);
        Iterator<ShoppingCartItem> lineOrderedByBasePriceIter = lineOrderedByBasePriceList.iterator();
        while (amountNeeded.compareTo(BigDecimal.ZERO) > 0 && lineOrderedByBasePriceIter.hasNext()) {
            ShoppingCartItem cartItem = lineOrderedByBasePriceIter.next();
            // only include if it is in the productId Set for this check and if it is not a Promo (GWP) item
            GenericValue product = cartItem.getProduct();
            String parentProductId = cartItem.getParentProductId();
            boolean passedItemConds = checkConditionsForItem(productPromoCond, cart, cartItem, delegator, dispatcher, nowTimestamp);
            if (passedItemConds && !cartItem.getIsPromo() && (productIds.contains(cartItem.getProductId()) || (parentProductId != null && productIds.contains(parentProductId))) && (product == null || !"N".equals(product.getString("includeInPromotions")))) {
                BigDecimal basePrice = cartItem.getBasePrice();
                // get a rough price, round it up to an integer
                BigDecimal quantityNeeded = amountNeeded.divide(basePrice, generalRounding).setScale(0, RoundingMode.CEILING);
                // reduce amount still needed to qualify for promo (amountNeeded)
                BigDecimal quantity = cartItem.addPromoQuantityCandidateUse(quantityNeeded, productPromoCond, false);
                // get pro-rated amount based on discount
                amountNeeded = amountNeeded.subtract(quantity.multiply(basePrice));
            }
        }
        // if amountNeeded > 0 then the promo condition failed, so remove candidate promo uses and increment the promoQuantityUsed to restore it
        if (amountNeeded.compareTo(BigDecimal.ZERO) > 0) {
            // failed, reset the entire rule, ie including all other conditions that might have been done before
            cart.resetPromoRuleUse(productPromoCond.getString("productPromoId"), productPromoCond.getString("productPromoRuleId"));
            compareBase = Integer.valueOf(-1);
        } else {
            // we got it, the conditions are in place...
            compareBase = Integer.valueOf(0);
        // NOTE: don't confirm promo rule use here, wait until actions are complete for the rule to do that
        }
    } else if ("PPIP_PRODUCT_TOTAL".equals(inputParamEnumId)) {
        // this type of condition allows items involved to be involved in other quantity consuming cond/action, and does pro-rate the price
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal amountNeeded = new BigDecimal(condValue);
            BigDecimal amountAvailable = BigDecimal.ZERO;
            Set<String> productIds = ProductPromoWorker.getPromoRuleCondProductIds(productPromoCond, delegator, nowTimestamp);
            List<ShoppingCartItem> lineOrderedByBasePriceList = cart.getLineListOrderedByBasePrice(false);
            for (ShoppingCartItem cartItem : lineOrderedByBasePriceList) {
                // only include if it is in the productId Set for this check and if it is not a Promo (GWP) item
                GenericValue product = cartItem.getProduct();
                String parentProductId = cartItem.getParentProductId();
                boolean passedItemConds = checkConditionsForItem(productPromoCond, cart, cartItem, delegator, dispatcher, nowTimestamp);
                if (passedItemConds && !cartItem.getIsPromo() && (productIds.contains(cartItem.getProductId()) || (parentProductId != null && productIds.contains(parentProductId))) && (product == null || !"N".equals(product.getString("includeInPromotions")))) {
                    // just count the entire sub-total of the item
                    amountAvailable = amountAvailable.add(cartItem.getItemSubTotal());
                }
            }
            compareBase = Integer.valueOf(amountAvailable.compareTo(amountNeeded));
        }
    } else if ("PPIP_PRODUCT_QUANT".equals(inputParamEnumId)) {
        if (operatorEnumId == null) {
            // if the operator is not specified in the condition, then assume as default PPC_EQ (for backward compatibility)
            operatorEnumId = "PPC_EQ";
        }
        BigDecimal quantityNeeded = BigDecimal.ONE;
        if (UtilValidate.isNotEmpty(condValue)) {
            quantityNeeded = new BigDecimal(condValue);
        }
        Set<String> productIds = ProductPromoWorker.getPromoRuleCondProductIds(productPromoCond, delegator, nowTimestamp);
        List<ShoppingCartItem> lineOrderedByBasePriceList = cart.getLineListOrderedByBasePrice(false);
        Iterator<ShoppingCartItem> lineOrderedByBasePriceIter = lineOrderedByBasePriceList.iterator();
        while (quantityNeeded.compareTo(BigDecimal.ZERO) > 0 && lineOrderedByBasePriceIter.hasNext()) {
            ShoppingCartItem cartItem = lineOrderedByBasePriceIter.next();
            // only include if it is in the productId Set for this check and if it is not a Promo (GWP) item
            GenericValue product = cartItem.getProduct();
            String parentProductId = cartItem.getParentProductId();
            boolean passedItemConds = checkConditionsForItem(productPromoCond, cart, cartItem, delegator, dispatcher, nowTimestamp);
            if (passedItemConds && !cartItem.getIsPromo() && (productIds.contains(cartItem.getProductId()) || (parentProductId != null && productIds.contains(parentProductId))) && (product == null || !"N".equals(product.getString("includeInPromotions")))) {
                // reduce quantity still needed to qualify for promo (quantityNeeded)
                quantityNeeded = quantityNeeded.subtract(cartItem.addPromoQuantityCandidateUse(quantityNeeded, productPromoCond, !"PPC_EQ".equals(operatorEnumId)));
            }
        }
        // if quantityNeeded > 0 then the promo condition failed, so remove candidate promo uses and increment the promoQuantityUsed to restore it
        if (quantityNeeded.compareTo(BigDecimal.ZERO) > 0) {
            // failed, reset the entire rule, ie including all other conditions that might have been done before
            cart.resetPromoRuleUse(productPromoCond.getString("productPromoId"), productPromoCond.getString("productPromoRuleId"));
            compareBase = Integer.valueOf(-1);
        } else {
            // we got it, the conditions are in place...
            compareBase = Integer.valueOf(0);
        // NOTE: don't confirm rpomo rule use here, wait until actions are complete for the rule to do that
        }
    } else if ("PPIP_NEW_ACCT".equals(inputParamEnumId)) {
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal acctDays = cart.getPartyDaysSinceCreated(nowTimestamp);
            if (acctDays == null) {
                // condition always fails if we don't know how many days since account created
                return false;
            }
            compareBase = acctDays.compareTo(new BigDecimal(condValue));
        }
    } else if ("PPIP_PARTY_ID".equals(inputParamEnumId)) {
        if (partyId != null && UtilValidate.isNotEmpty(condValue)) {
            compareBase = Integer.valueOf(partyId.compareTo(condValue));
        } else {
            compareBase = Integer.valueOf(1);
        }
    } else if ("PPIP_PARTY_GRP_MEM".equals(inputParamEnumId)) {
        if (UtilValidate.isEmpty(partyId) || UtilValidate.isEmpty(condValue)) {
            compareBase = Integer.valueOf(1);
        } else {
            String groupPartyId = condValue;
            if (partyId.equals(groupPartyId)) {
                compareBase = Integer.valueOf(0);
            } else {
                // look for PartyRelationship with partyRelationshipTypeId=GROUP_ROLLUP, the partyIdTo is the group member, so the partyIdFrom is the groupPartyId
                // and from/thru date within range
                List<GenericValue> partyRelationshipList = EntityQuery.use(delegator).from("PartyRelationship").where("partyIdFrom", groupPartyId, "partyIdTo", partyId, "partyRelationshipTypeId", "GROUP_ROLLUP").cache(true).filterByDate().queryList();
                if (UtilValidate.isNotEmpty(partyRelationshipList)) {
                    compareBase = Integer.valueOf(0);
                } else {
                    compareBase = Integer.valueOf(checkConditionPartyHierarchy(delegator, nowTimestamp, groupPartyId, partyId));
                }
            }
        }
    } else if ("PPIP_PARTY_CLASS".equals(inputParamEnumId)) {
        if (UtilValidate.isEmpty(partyId) || UtilValidate.isEmpty(condValue)) {
            compareBase = Integer.valueOf(1);
        } else {
            String partyClassificationGroupId = condValue;
            // find any PartyClassification
            // and from/thru date within range
            List<GenericValue> partyClassificationList = EntityQuery.use(delegator).from("PartyClassification").where("partyId", partyId, "partyClassificationGroupId", partyClassificationGroupId).cache(true).filterByDate().queryList();
            // then 0 (equals), otherwise 1 (not equals)
            if (UtilValidate.isNotEmpty(partyClassificationList)) {
                compareBase = Integer.valueOf(0);
            } else {
                compareBase = Integer.valueOf(1);
            }
        }
    } else if ("PPIP_ROLE_TYPE".equals(inputParamEnumId)) {
        if (partyId != null && UtilValidate.isNotEmpty(condValue)) {
            // if a PartyRole exists for this partyId and the specified roleTypeId
            GenericValue partyRole = EntityQuery.use(delegator).from("PartyRole").where("partyId", partyId, "roleTypeId", condValue).cache(true).queryOne();
            // then 0 (equals), otherwise 1 (not equals)
            if (partyRole != null) {
                compareBase = Integer.valueOf(0);
            } else {
                compareBase = Integer.valueOf(1);
            }
        } else {
            compareBase = Integer.valueOf(1);
        }
    } else if ("PPIP_GEO_ID".equals(inputParamEnumId)) {
        compareBase = Integer.valueOf(1);
        GenericValue shippingAddress = cart.getShippingAddress();
        if (UtilValidate.isNotEmpty(condValue) && shippingAddress != null) {
            if (condValue.equals(shippingAddress.getString("countryGeoId")) || condValue.equals(shippingAddress.getString("countyGeoId")) || condValue.equals(shippingAddress.getString("postalCodeGeoId")) || condValue.equals(shippingAddress.getString("stateProvinceGeoId"))) {
                compareBase = Integer.valueOf(0);
            } else {
                List<GenericValue> geoAssocList = EntityQuery.use(delegator).from("GeoAssoc").where("geoIdTo", condValue).queryList();
                for (GenericValue geo : geoAssocList) {
                    if (geo.get("geoId").equals(shippingAddress.getString("countryGeoId")) || geo.get("geoId").equals(shippingAddress.getString("countyGeoId")) || geo.get("geoId").equals(shippingAddress.getString("postalCodeGeoId")) || condValue.equals(shippingAddress.getString("stateProvinceGeoId"))) {
                        compareBase = Integer.valueOf(0);
                        break;
                    }
                }
            }
        }
    } else if ("PPIP_ORDER_TOTAL".equals(inputParamEnumId)) {
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal orderSubTotal = cart.getSubTotalForPromotions();
            if (Debug.verboseOn())
                Debug.logVerbose("Doing order total compare: orderSubTotal=" + orderSubTotal, module);
            compareBase = Integer.valueOf(orderSubTotal.compareTo(new BigDecimal(condValue)));
        }
    } else if ("PPIP_ORST_HIST".equals(inputParamEnumId)) {
        // description="Order sub-total X in last Y Months"
        if (partyId != null && userLogin != null && UtilValidate.isNotEmpty(condValue)) {
            // call the getOrderedSummaryInformation service to get the sub-total
            int monthsToInclude = 12;
            if (otherValue != null) {
                monthsToInclude = Integer.parseInt(otherValue);
            }
            Map<String, Object> serviceIn = UtilMisc.<String, Object>toMap("partyId", partyId, "roleTypeId", "PLACING_CUSTOMER", "orderTypeId", "SALES_ORDER", "statusId", "ORDER_COMPLETED", "monthsToInclude", Integer.valueOf(monthsToInclude), "userLogin", userLogin);
            try {
                Map<String, Object> result = dispatcher.runSync("getOrderedSummaryInformation", serviceIn);
                if (ServiceUtil.isError(result)) {
                    Debug.logError("Error calling getOrderedSummaryInformation service for the PPIP_ORST_HIST ProductPromo condition input value: " + ServiceUtil.getErrorMessage(result), module);
                    return false;
                } else {
                    BigDecimal orderSubTotal = (BigDecimal) result.get("totalSubRemainingAmount");
                    BigDecimal orderSubTotalAndCartSubTotal = orderSubTotal.add(cart.getSubTotal());
                    if (Debug.verboseOn())
                        Debug.logVerbose("Doing order history sub-total compare: orderSubTotal=" + orderSubTotal + ", for the last " + monthsToInclude + " months.", module);
                    compareBase = Integer.valueOf(orderSubTotalAndCartSubTotal.compareTo(new BigDecimal(condValue)));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error getting order history sub-total in the getOrderedSummaryInformation service, evaluating condition to false.", module);
                return false;
            }
        } else {
            return false;
        }
    } else if ("PPIP_ORST_YEAR".equals(inputParamEnumId)) {
        // description="Order sub-total X since beginning of current year"
        if (partyId != null && userLogin != null && UtilValidate.isNotEmpty(condValue)) {
            // call the getOrderedSummaryInformation service to get the sub-total
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowTimestamp);
            int monthsToInclude = calendar.get(Calendar.MONTH) + 1;
            Map<String, Object> serviceIn = UtilMisc.<String, Object>toMap("partyId", partyId, "roleTypeId", "PLACING_CUSTOMER", "orderTypeId", "SALES_ORDER", "statusId", "ORDER_COMPLETED", "monthsToInclude", Integer.valueOf(monthsToInclude), "userLogin", userLogin);
            try {
                Map<String, Object> result = dispatcher.runSync("getOrderedSummaryInformation", serviceIn);
                if (ServiceUtil.isError(result)) {
                    Debug.logError("Error calling getOrderedSummaryInformation service for the PPIP_ORST_YEAR ProductPromo condition input value: " + ServiceUtil.getErrorMessage(result), module);
                    return false;
                } else {
                    BigDecimal orderSubTotal = (BigDecimal) result.get("totalSubRemainingAmount");
                    if (Debug.verboseOn())
                        Debug.logVerbose("Doing order history sub-total compare: orderSubTotal=" + orderSubTotal + ", for the last " + monthsToInclude + " months.", module);
                    compareBase = Integer.valueOf(orderSubTotal.compareTo(new BigDecimal((condValue))));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error getting order history sub-total in the getOrderedSummaryInformation service, evaluating condition to false.", module);
                return false;
            }
        }
    } else if ("PPIP_ORST_LAST_YEAR".equals(inputParamEnumId)) {
        // description="Order sub-total X since beginning of last year"
        if (partyId != null && userLogin != null && UtilValidate.isNotEmpty(condValue)) {
            // call the getOrderedSummaryInformation service to get the sub-total
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowTimestamp);
            int lastYear = calendar.get(Calendar.YEAR) - 1;
            Calendar fromDateCalendar = Calendar.getInstance();
            fromDateCalendar.set(lastYear, 0, 0, 0, 0);
            Timestamp fromDate = new Timestamp(fromDateCalendar.getTime().getTime());
            Calendar thruDateCalendar = Calendar.getInstance();
            thruDateCalendar.set(lastYear, 12, 0, 0, 0);
            Timestamp thruDate = new Timestamp(thruDateCalendar.getTime().getTime());
            Map<String, Object> serviceIn = UtilMisc.toMap("partyId", partyId, "roleTypeId", "PLACING_CUSTOMER", "orderTypeId", "SALES_ORDER", "statusId", "ORDER_COMPLETED", "fromDate", fromDate, "thruDate", thruDate, "userLogin", userLogin);
            try {
                Map<String, Object> result = dispatcher.runSync("getOrderedSummaryInformation", serviceIn);
                if (ServiceUtil.isError(result)) {
                    Debug.logError("Error calling getOrderedSummaryInformation service for the PPIP_ORST_LAST_YEAR ProductPromo condition input value: " + ServiceUtil.getErrorMessage(result), module);
                    return false;
                } else {
                    Double orderSubTotal = (Double) result.get("totalSubRemainingAmount");
                    if (Debug.verboseOn())
                        Debug.logVerbose("Doing order history sub-total compare: orderSubTotal=" + orderSubTotal + ", for last year.", module);
                    compareBase = Integer.valueOf(orderSubTotal.compareTo(Double.valueOf(condValue)));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error getting order history sub-total in the getOrderedSummaryInformation service, evaluating condition to false.", module);
                return false;
            }
        } else {
            return false;
        }
    } else if ("PPIP_RECURRENCE".equals(inputParamEnumId)) {
        if (UtilValidate.isNotEmpty(condValue)) {
            compareBase = Integer.valueOf(1);
            GenericValue recurrenceInfo = EntityQuery.use(delegator).from("RecurrenceInfo").where("recurrenceInfoId", condValue).cache().queryOne();
            if (recurrenceInfo != null) {
                RecurrenceInfo recurrence = null;
                try {
                    recurrence = new RecurrenceInfo(recurrenceInfo);
                } catch (RecurrenceInfoException e) {
                    Debug.logError(e, module);
                }
                // check the current recurrence
                if (recurrence != null) {
                    if (recurrence.isValidCurrent()) {
                        compareBase = Integer.valueOf(0);
                    }
                }
            }
        }
    } else if ("PPIP_ORDER_SHIPTOTAL".equals(inputParamEnumId) && shippingMethod.equals(cart.getShipmentMethodTypeId()) && carrierPartyId.equals(cart.getCarrierPartyId())) {
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal orderTotalShipping = cart.getTotalShipping();
            if (Debug.verboseOn()) {
                Debug.logVerbose("Doing order total Shipping compare: ordertotalShipping=" + orderTotalShipping, module);
            }
            compareBase = orderTotalShipping.compareTo(new BigDecimal(condValue));
        }
    } else if ("PPIP_LPMUP_AMT".equals(inputParamEnumId)) {
        // does nothing on order level, only checked on item level, so ignore by always considering passed
        return true;
    } else if ("PPIP_LPMUP_PER".equals(inputParamEnumId)) {
        // does nothing on order level, only checked on item level, so ignore by always considering passed
        return true;
    } else {
        Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderAnUnSupportedProductPromoCondInputParameterLhs", UtilMisc.toMap("inputParamEnumId", productPromoCond.getString("inputParamEnumId")), cart.getLocale()), module);
        return false;
    }
    if (Debug.verboseOn())
        Debug.logVerbose("Condition compare done, compareBase=" + compareBase, module);
    if (compareBase != null) {
        int compare = compareBase.intValue();
        if ("PPC_EQ".equals(operatorEnumId)) {
            if (compare == 0)
                return true;
        } else if ("PPC_NEQ".equals(operatorEnumId)) {
            if (compare != 0)
                return true;
        } else if ("PPC_LT".equals(operatorEnumId)) {
            if (compare < 0)
                return true;
        } else if ("PPC_LTE".equals(operatorEnumId)) {
            if (compare <= 0)
                return true;
        } else if ("PPC_GT".equals(operatorEnumId)) {
            if (compare > 0)
                return true;
        } else if ("PPC_GTE".equals(operatorEnumId)) {
            if (compare >= 0)
                return true;
        } else {
            Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderAnUnSupportedProductPromoCondCondition", UtilMisc.toMap("operatorEnumId", operatorEnumId), cart.getLocale()), module);
            return false;
        }
    }
    // default to not meeting the condition
    return false;
}
Also used : RecurrenceInfoException(org.apache.ofbiz.service.calendar.RecurrenceInfoException) GenericValue(org.apache.ofbiz.entity.GenericValue) HashSet(java.util.HashSet) Set(java.util.Set) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) RecurrenceInfo(org.apache.ofbiz.service.calendar.RecurrenceInfo) Iterator(java.util.Iterator) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with RecurrenceInfoException

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

the class JobManager method schedule.

/**
 * Schedule a job to start at a specific time with specific recurrence info
 *
 * @param jobName
 *            The name of the job
 *@param poolName
 *            The name of the pool to run the service from
 *@param serviceName
 *            The name of the service to invoke
 *@param dataId
 *            The persisted context (RuntimeData.runtimeDataId)
 *@param startTime
 *            The time in milliseconds the service should run
 *@param frequency
 *            The frequency of the recurrence (HOURLY,DAILY,MONTHLY,etc)
 *@param interval
 *            The interval of the frequency recurrence
 *@param count
 *            The number of times to repeat
 *@param endTime
 *            The time in milliseconds the service should expire
 *@param maxRetry
 *            The max number of retries on failure (-1 for no max)
 * @throws IllegalStateException if the Job Manager is shut down.
 */
public void schedule(String jobName, String poolName, String serviceName, String dataId, long startTime, int frequency, int interval, int count, long endTime, int maxRetry) throws JobManagerException {
    assertIsRunning();
    // create the recurrence
    String infoId = null;
    if (frequency > -1 && count != 0) {
        try {
            RecurrenceInfo info = RecurrenceInfo.makeInfo(delegator, startTime, frequency, interval, count);
            infoId = info.primaryKey();
        } catch (RecurrenceInfoException e) {
            throw new JobManagerException(e.getMessage(), e);
        }
    }
    // set the persisted fields
    if (UtilValidate.isEmpty(jobName)) {
        jobName = Long.toString((new Date().getTime()));
    }
    Map<String, Object> jFields = UtilMisc.<String, Object>toMap("jobName", jobName, "runTime", new java.sql.Timestamp(startTime), "serviceName", serviceName, "statusId", "SERVICE_PENDING", "recurrenceInfoId", infoId, "runtimeDataId", dataId);
    // set the pool ID
    if (UtilValidate.isNotEmpty(poolName)) {
        jFields.put("poolId", poolName);
    } else {
        try {
            jFields.put("poolId", ServiceConfigUtil.getServiceEngine().getThreadPool().getSendToPool());
        } catch (GenericConfigException e) {
            throw new JobManagerException(e.getMessage(), e);
        }
    }
    // set the loader name
    jFields.put("loaderName", delegator.getDelegatorName());
    // set the max retry
    jFields.put("maxRetry", Long.valueOf(maxRetry));
    jFields.put("currentRetryCount", Long.valueOf(0));
    // create the value and store
    GenericValue jobV;
    try {
        jobV = delegator.makeValue("JobSandbox", jFields);
        delegator.createSetNextSeqId(jobV);
    } catch (GenericEntityException e) {
        throw new JobManagerException(e.getMessage(), e);
    }
}
Also used : RecurrenceInfoException(org.apache.ofbiz.service.calendar.RecurrenceInfoException) GenericValue(org.apache.ofbiz.entity.GenericValue) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) RecurrenceInfo(org.apache.ofbiz.service.calendar.RecurrenceInfo) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Timestamp(java.sql.Timestamp) Date(java.util.Date)

Example 3 with RecurrenceInfoException

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

the class ShoppingListServices method setShoppingListRecurrence.

public static Map<String, Object> setShoppingListRecurrence(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Timestamp startDate = (Timestamp) context.get("startDateTime");
    Timestamp endDate = (Timestamp) context.get("endDateTime");
    Integer frequency = (Integer) context.get("frequency");
    Integer interval = (Integer) context.get("intervalNumber");
    Locale locale = (Locale) context.get("locale");
    if (frequency == null || interval == null) {
        Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderFrequencyOrIntervalWasNotSpecified", locale), module);
        return ServiceUtil.returnSuccess();
    }
    if (startDate == null) {
        switch(frequency.intValue()) {
            case 5:
                startDate = UtilDateTime.getWeekStart(UtilDateTime.nowTimestamp(), 0, interval.intValue());
                break;
            case 6:
                startDate = UtilDateTime.getMonthStart(UtilDateTime.nowTimestamp(), 0, interval.intValue());
                break;
            case 7:
                startDate = UtilDateTime.getYearStart(UtilDateTime.nowTimestamp(), 0, interval.intValue());
                break;
            default:
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderInvalidFrequencyForShoppingListRecurrence", locale));
        }
    }
    long startTime = startDate.getTime();
    long endTime = 0;
    if (endDate != null) {
        endTime = endDate.getTime();
    }
    RecurrenceInfo recInfo = null;
    try {
        recInfo = RecurrenceInfo.makeInfo(delegator, startTime, frequency.intValue(), interval.intValue(), -1, endTime);
    } catch (RecurrenceInfoException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderUnableToCreateShoppingListRecurrenceInformation", locale));
    }
    Debug.logInfo("Next Recurrence - " + UtilDateTime.getTimestamp(recInfo.next()), module);
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("recurrenceInfoId", recInfo.getID());
    return result;
}
Also used : Locale(java.util.Locale) RecurrenceInfoException(org.apache.ofbiz.service.calendar.RecurrenceInfoException) Delegator(org.apache.ofbiz.entity.Delegator) RecurrenceInfo(org.apache.ofbiz.service.calendar.RecurrenceInfo) Timestamp(java.sql.Timestamp)

Example 4 with RecurrenceInfoException

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

the class ShoppingListServices method createListReorders.

public static Map<String, Object> createListReorders(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    boolean beganTransaction = false;
    EntityQuery eq = EntityQuery.use(delegator).from("ShoppingList").where("shoppingListTypeId", "SLT_AUTO_REODR", "isActive", "Y").orderBy("-lastOrderedDate");
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, "[Delegator] Could not begin transaction: " + e1.toString(), module);
    }
    try (EntityListIterator eli = eq.queryIterator()) {
        if (eli != null) {
            GenericValue shoppingList;
            while (((shoppingList = eli.next()) != null)) {
                Timestamp lastOrder = shoppingList.getTimestamp("lastOrderedDate");
                RecurrenceInfo recurrence = null;
                GenericValue recurrenceInfo = shoppingList.getRelatedOne("RecurrenceInfo", false);
                Timestamp startDateTime = recurrenceInfo.getTimestamp("startDateTime");
                try {
                    recurrence = new RecurrenceInfo(recurrenceInfo);
                } catch (RecurrenceInfoException e) {
                    Debug.logError(e, module);
                }
                // check the next recurrence
                if (recurrence != null) {
                    long next = lastOrder == null ? recurrence.next(startDateTime.getTime()) : recurrence.next(lastOrder.getTime());
                    Timestamp now = UtilDateTime.nowTimestamp();
                    Timestamp nextOrder = UtilDateTime.getDayStart(UtilDateTime.getTimestamp(next));
                    if (nextOrder.after(now)) {
                        continue;
                    }
                } else {
                    continue;
                }
                ShoppingCart listCart = makeShoppingListCart(dispatcher, shoppingList, locale);
                CheckOutHelper helper = new CheckOutHelper(dispatcher, delegator, listCart);
                // store the order
                Map<String, Object> createResp = helper.createOrder(userLogin);
                if (createResp == null || (createResp != null && ServiceUtil.isError(createResp))) {
                    Debug.logError("Cannot create order for shopping list - " + shoppingList, module);
                } else {
                    String orderId = (String) createResp.get("orderId");
                    // authorize the payments
                    Map<String, Object> payRes = null;
                    try {
                        payRes = helper.processPayment(ProductStoreWorker.getProductStore(listCart.getProductStoreId(), delegator), userLogin);
                    } catch (GeneralException e) {
                        Debug.logError(e, module);
                    }
                    if (payRes != null && ServiceUtil.isError(payRes)) {
                        Debug.logError("Payment processing problems with shopping list - " + shoppingList, module);
                    }
                    shoppingList.set("lastOrderedDate", UtilDateTime.nowTimestamp());
                    shoppingList.store();
                    // send notification
                    try {
                        dispatcher.runAsync("sendOrderPayRetryNotification", UtilMisc.toMap("orderId", orderId));
                    } catch (GenericServiceException e) {
                        Debug.logError(e, module);
                    }
                    // increment the recurrence
                    recurrence.incrementCurrentCount();
                }
            }
        }
        return ServiceUtil.returnSuccess();
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error creating shopping list auto-reorders", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "[Delegator] Could not rollback transaction: " + e2.toString(), module);
        }
        String errMsg = UtilProperties.getMessage(resource_error, "OrderErrorWhileCreatingNewShoppingListBasedAutomaticReorder", UtilMisc.toMap("errorString", e.toString()), locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    } finally {
        try {
            // only commit the transaction if we started one... this will throw an exception if it fails
            TransactionUtil.commit(beganTransaction);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Could not commit transaction for creating new shopping list based automatic reorder", module);
        }
    }
}
Also used : Locale(java.util.Locale) RecurrenceInfoException(org.apache.ofbiz.service.calendar.RecurrenceInfoException) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) RecurrenceInfo(org.apache.ofbiz.service.calendar.RecurrenceInfo) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Aggregations

Timestamp (java.sql.Timestamp)4 RecurrenceInfo (org.apache.ofbiz.service.calendar.RecurrenceInfo)4 RecurrenceInfoException (org.apache.ofbiz.service.calendar.RecurrenceInfoException)4 GenericValue (org.apache.ofbiz.entity.GenericValue)3 Locale (java.util.Locale)2 Delegator (org.apache.ofbiz.entity.Delegator)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)2 Calendar (com.ibm.icu.util.Calendar)1 BigDecimal (java.math.BigDecimal)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 GenericConfigException (org.apache.ofbiz.base.config.GenericConfigException)1