Search in sources :

Example 11 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition 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 12 with EntityCondition

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

the class WorkEffortServices method processWorkEffortEventReminders.

/**
 * Process work effort event reminders. This service is used by the job scheduler.
 * @param ctx the dispatch context
 * @param context the context
 * @return returns the result of the service execution
 */
public static Map<String, Object> processWorkEffortEventReminders(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Locale localePar = (Locale) context.get("locale");
    Timestamp now = new Timestamp(System.currentTimeMillis());
    List<GenericValue> eventReminders = null;
    try {
        eventReminders = EntityQuery.use(delegator).from("WorkEffortEventReminder").where(EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("reminderDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("reminderDateTime", EntityOperator.LESS_THAN_EQUAL_TO, now)), EntityOperator.OR)).queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "WorkEffortEventRemindersRetrivingError", UtilMisc.toMap("errorString", e), localePar));
    }
    for (GenericValue reminder : eventReminders) {
        if (UtilValidate.isEmpty(reminder.get("contactMechId"))) {
            continue;
        }
        int repeatCount = reminder.get("repeatCount") == null ? 0 : reminder.getLong("repeatCount").intValue();
        int currentCount = reminder.get("currentCount") == null ? 0 : reminder.getLong("currentCount").intValue();
        GenericValue workEffort = null;
        try {
            workEffort = reminder.getRelatedOne("WorkEffort", false);
        } catch (GenericEntityException e) {
            Debug.logWarning("Error while getting work effort: " + e, module);
        }
        if (workEffort == null) {
            try {
                reminder.remove();
            } catch (GenericEntityException e) {
                Debug.logWarning("Error while removing work effort event reminder: " + e, module);
            }
            continue;
        }
        Locale locale = reminder.getString("localeId") == null ? Locale.getDefault() : new Locale(reminder.getString("localeId"));
        TimeZone timeZone = reminder.getString("timeZoneId") == null ? TimeZone.getDefault() : TimeZone.getTimeZone(reminder.getString("timeZoneId"));
        Map<String, Object> parameters = UtilMisc.toMap("locale", locale, "timeZone", timeZone, "workEffortId", reminder.get("workEffortId"));
        Map<String, Object> processCtx = UtilMisc.toMap("reminder", reminder, "bodyParameters", parameters, "userLogin", context.get("userLogin"));
        Calendar cal = UtilDateTime.toCalendar(now, timeZone, locale);
        Timestamp reminderStamp = reminder.getTimestamp("reminderDateTime");
        Date eventDateTime = workEffort.getTimestamp("estimatedStartDate");
        String tempExprId = workEffort.getString("tempExprId");
        if (UtilValidate.isNotEmpty(tempExprId)) {
            TemporalExpression temporalExpression = null;
            try {
                temporalExpression = TemporalExpressionWorker.getTemporalExpression(delegator, tempExprId);
            } catch (GenericEntityException e) {
                Debug.logWarning("Error while getting temporal expression, id = " + tempExprId + ": " + e, module);
            }
            if (temporalExpression != null) {
                eventDateTime = temporalExpression.first(cal).getTime();
                Date reminderDateTime = null;
                long reminderOffset = reminder.get("reminderOffset") == null ? 0 : reminder.getLong("reminderOffset").longValue();
                if (reminderStamp == null) {
                    if (reminderOffset != 0) {
                        cal.setTime(eventDateTime);
                        TimeDuration duration = TimeDuration.fromLong(reminderOffset);
                        duration.addToCalendar(cal);
                        reminderDateTime = cal.getTime();
                    } else {
                        reminderDateTime = eventDateTime;
                    }
                } else {
                    reminderDateTime = new Date(reminderStamp.getTime());
                }
                if (reminderDateTime.before(now) && reminderStamp != null) {
                    try {
                        parameters.put("eventDateTime", new Timestamp(eventDateTime.getTime()));
                        Map<String, Object> result = dispatcher.runSync("processWorkEffortEventReminder", processCtx);
                        if (ServiceUtil.isError(result)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                        }
                        if (repeatCount != 0 && currentCount + 1 >= repeatCount) {
                            reminder.remove();
                        } else {
                            cal.setTime(reminderDateTime);
                            Date newReminderDateTime = null;
                            if (reminderOffset != 0) {
                                TimeDuration duration = TimeDuration.fromLong(-reminderOffset);
                                duration.addToCalendar(cal);
                                cal.setTime(temporalExpression.next(cal).getTime());
                                duration = TimeDuration.fromLong(reminderOffset);
                                duration.addToCalendar(cal);
                                newReminderDateTime = cal.getTime();
                            } else {
                                newReminderDateTime = temporalExpression.next(cal).getTime();
                            }
                            reminder.set("currentCount", Long.valueOf(currentCount + 1));
                            reminder.set("reminderDateTime", new Timestamp(newReminderDateTime.getTime()));
                            reminder.store();
                        }
                    } catch (GenericEntityException e) {
                        Debug.logWarning("Error while processing temporal expression reminder, id = " + tempExprId + ": " + e, module);
                    } catch (GenericServiceException e) {
                        Debug.logError(e, module);
                    }
                } else if (reminderStamp == null) {
                    try {
                        reminder.set("reminderDateTime", new Timestamp(reminderDateTime.getTime()));
                        reminder.store();
                    } catch (GenericEntityException e) {
                        Debug.logWarning("Error while processing temporal expression reminder, id = " + tempExprId + ": " + e, module);
                    }
                }
            }
            continue;
        }
        if (reminderStamp != null) {
            Date reminderDateTime = new Date(reminderStamp.getTime());
            if (reminderDateTime.before(now)) {
                try {
                    parameters.put("eventDateTime", eventDateTime);
                    Map<String, Object> result = dispatcher.runSync("processWorkEffortEventReminder", processCtx);
                    if (ServiceUtil.isError(result)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                    }
                    TimeDuration duration = TimeDuration.fromNumber(reminder.getLong("repeatInterval"));
                    if ((repeatCount != 0 && currentCount + 1 >= repeatCount) || duration.isZero()) {
                        reminder.remove();
                    } else {
                        cal.setTime(now);
                        duration.addToCalendar(cal);
                        reminderDateTime = cal.getTime();
                        reminder.set("currentCount", Long.valueOf(currentCount + 1));
                        reminder.set("reminderDateTime", new Timestamp(reminderDateTime.getTime()));
                        reminder.store();
                    }
                } catch (GenericEntityException e) {
                    Debug.logWarning("Error while processing event reminder: " + e, module);
                } catch (GenericServiceException e) {
                    Debug.logError(e, module);
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) TemporalExpression(org.apache.ofbiz.service.calendar.TemporalExpression) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) Date(java.util.Date) TimeZone(java.util.TimeZone) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) TimeDuration(org.apache.ofbiz.base.util.TimeDuration) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 13 with EntityCondition

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

the class WorkEffortServices method getWorkEffortEventsByPeriod.

/**
 * Get Work Efforts by period.
 * <p>
 * This method takes the following parameters:
 * </p>
 * <ul>
 *   <li>start - TimeStamp (Period start date/time)</li>
 *   <li>numPeriods - Integer</li>
 *   <li>periodType - Integer (see java.util.Calendar)</li>
 *   <li>eventStatus - String</li>
 *   <li>partyId - String</li>
 *   <li>partyIds - List</li>
 *   <li>facilityId - String</li>
 *   <li>fixedAssetId - String</li>
 *   <li>filterOutCanceledEvents - Boolean</li>
 *   <li>entityExprList - List</li>
 * </ul>
 * <p>
 * The method will find all matching Work Effort events and return them as a List called
 * <b>periods</b> - one List element per period. It also returns a
 * <b>maxConcurrentEntries</b> Integer - which indicates the maximum number of
 * Work Efforts found in one period.
 * </p>
 * <p>
 * Each <b>periods</b> list element is a Map containing the following
 * key/value pairs:
 * </p>
 * <ul>
 *   <li>start - TimeStamp (Period start date/time)</li>
 *   <li>end - TimeStamp (Period end date/time)</li>
 *   <li>calendarEntries - List of Maps. Each Map contains the following key/value pairs</li>
 *   <li><ul>
 *       <li>workEffort - GenericValue</li>
 *       <li>periodSpan - Integer (Number of periods this Work Effort spans)</li>
 *       <li>startOfPeriod - Boolean (true if this is the first occurrence in the period range)</li>
 *   </ul></li>
 * </ul>
 */
public static Map<String, Object> getWorkEffortEventsByPeriod(DispatchContext ctx, Map<String, ? extends Object> context) {
    /*
         To create testdata for  this function for  fixedasset/facility

        1) go to Manufacturing -> JobShop, then click on "create new Production run":
                https://localhost:8443/manufacturing/control/CreateProductionRun
        2) enter as productId "PROD_MANUF", quantity 1, start date tomorrow and press the submit button
    `    3) in the next screen, click on the "Confirm" link (top part of the sccreen)

        Now you have a confirmed production run (starting tomorrow) happening in facility "WebStoreWarehouse",
        with a task happening in fixed asset "WORKCENTER_COST"

        In the calendars screen, selecting the proper facility you should see the work effort associated to the production run;
        if you select the proper fixed asset you should see the task.

         */
    Delegator delegator = ctx.getDelegator();
    Security security = ctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    TimeZone timeZone = (TimeZone) context.get("timeZone");
    Timestamp startDay = (Timestamp) context.get("start");
    Integer numPeriodsInteger = (Integer) context.get("numPeriods");
    String calendarType = (String) context.get("calendarType");
    if (UtilValidate.isEmpty(calendarType)) {
        // This is a bad idea. This causes the service to return only those work efforts that are assigned
        // to the current user even when the service parameters have nothing to do with the current user.
        calendarType = "CAL_PERSONAL";
    }
    String partyId = (String) context.get("partyId");
    Collection<String> partyIds = UtilGenerics.checkCollection(context.get("partyIds"));
    String facilityId = (String) context.get("facilityId");
    String fixedAssetId = (String) context.get("fixedAssetId");
    String workEffortTypeId = (String) context.get("workEffortTypeId");
    Boolean filterOutCanceledEvents = (Boolean) context.get("filterOutCanceledEvents");
    if (filterOutCanceledEvents == null) {
        filterOutCanceledEvents = Boolean.FALSE;
    }
    // To be returned, the max concurrent entries for a single period
    int maxConcurrentEntries = 0;
    Integer periodTypeObject = (Integer) context.get("periodType");
    int periodType = 0;
    if (periodTypeObject != null) {
        periodType = periodTypeObject.intValue();
    }
    int numPeriods = 0;
    if (numPeriodsInteger != null) {
        numPeriods = numPeriodsInteger.intValue();
    }
    // get a timestamp (date) for the beginning of today and for beginning of numDays+1 days from now
    // Commenting this out because it interferes with periods that do not start at the beginning of the day
    Timestamp startStamp = startDay;
    Timestamp endStamp = UtilDateTime.adjustTimestamp(startStamp, periodType, 1, timeZone, locale);
    long periodLen = endStamp.getTime() - startStamp.getTime();
    endStamp = UtilDateTime.adjustTimestamp(startStamp, periodType, numPeriods, timeZone, locale);
    // Get the WorkEfforts
    List<GenericValue> validWorkEfforts = null;
    Collection<String> partyIdsToUse = partyIds;
    if (partyIdsToUse == null) {
        partyIdsToUse = new HashSet<>();
    }
    if (UtilValidate.isNotEmpty(partyId)) {
        if (partyId.equals(userLogin.getString("partyId")) || security.hasEntityPermission("WORKEFFORTMGR", "_VIEW", userLogin)) {
            partyIdsToUse.add(partyId);
        } else {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "WorkEffortPartyPermissionError", UtilMisc.toMap("partyId", partyId), locale));
        }
    } else {
        if ("CAL_PERSONAL".equals(calendarType) && UtilValidate.isNotEmpty(userLogin.getString("partyId"))) {
            partyIdsToUse.add(userLogin.getString("partyId"));
        }
    }
    // cancelled status id's
    List<EntityCondition> cancelledCheckAndList = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "EVENT_CANCELLED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "CAL_CANCELLED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CANCELLED"));
    List<EntityCondition> entityExprList = UtilGenerics.checkList(context.get("entityExprList"));
    if (entityExprList == null) {
        entityExprList = getDefaultWorkEffortExprList(calendarType, partyIdsToUse, workEffortTypeId, cancelledCheckAndList);
    }
    if (UtilValidate.isNotEmpty(facilityId)) {
        entityExprList.add(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId));
    }
    if (UtilValidate.isNotEmpty(fixedAssetId)) {
        entityExprList.add(EntityCondition.makeCondition("fixedAssetId", EntityOperator.EQUALS, fixedAssetId));
    }
    // should have at least a start date
    EntityCondition startDateRequired = EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("estimatedStartDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("actualStartDate", EntityOperator.NOT_EQUAL, null)), EntityJoinOperator.OR);
    List<EntityCondition> periodCheckAndlList = UtilMisc.<EntityCondition>toList(startDateRequired, // the startdate should be less than the period end
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualStartDate", EntityOperator.EQUALS, null), EntityCondition.makeCondition("estimatedStartDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("estimatedStartDate", EntityOperator.LESS_THAN_EQUAL_TO, endStamp)), EntityJoinOperator.AND), EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualStartDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("actualStartDate", EntityOperator.LESS_THAN_EQUAL_TO, endStamp)), EntityJoinOperator.AND)), EntityJoinOperator.OR), // if the completion date is not null then it should be larger than the period start
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(// can also be empty
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("estimatedCompletionDate", EntityOperator.EQUALS, null), EntityCondition.makeCondition("actualCompletionDate", EntityOperator.EQUALS, null)), EntityJoinOperator.AND), // check estimated value if the actual is not provided
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualCompletionDate", EntityOperator.EQUALS, null), EntityCondition.makeCondition("estimatedCompletionDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("estimatedCompletionDate", EntityOperator.GREATER_THAN_EQUAL_TO, startStamp)), EntityJoinOperator.AND), // at last check the actual value
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualCompletionDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("actualCompletionDate", EntityOperator.GREATER_THAN_EQUAL_TO, startStamp)), EntityJoinOperator.AND)), EntityJoinOperator.OR));
    entityExprList.addAll(periodCheckAndlList);
    try {
        List<GenericValue> tempWorkEfforts = null;
        if (UtilValidate.isNotEmpty(partyIdsToUse)) {
            tempWorkEfforts = EntityQuery.use(delegator).from("WorkEffortAndPartyAssignAndType").where(entityExprList).orderBy("estimatedStartDate").filterByDate().queryList();
        } else {
            tempWorkEfforts = EntityQuery.use(delegator).from("WorkEffort").where(entityExprList).orderBy("estimatedStartDate").queryList();
        }
        if (!"CAL_PERSONAL".equals(calendarType) && UtilValidate.isNotEmpty(fixedAssetId)) {
            // Get "new style" work efforts
            tempWorkEfforts.addAll(EntityQuery.use(delegator).from("WorkEffortAndFixedAssetAssign").where(entityExprList).orderBy("estimatedStartDate").filterByDate().queryList());
        }
        validWorkEfforts = WorkEffortWorker.removeDuplicateWorkEfforts(tempWorkEfforts);
    } catch (GenericEntityException e) {
        Debug.logWarning(e, module);
    }
    // Split the WorkEffort list into a map with entries for each period, period start is the key
    List<Map<String, Object>> periods = new LinkedList<>();
    if (validWorkEfforts != null) {
        List<DateRange> periodRanges = new LinkedList<>();
        for (int i = 0; i < numPeriods; i++) {
            Timestamp curPeriodStart = UtilDateTime.adjustTimestamp(startStamp, periodType, i, timeZone, locale);
            Timestamp curPeriodEnd = UtilDateTime.adjustTimestamp(curPeriodStart, periodType, 1, timeZone, locale);
            curPeriodEnd = new Timestamp(curPeriodEnd.getTime() - 1);
            periodRanges.add(new DateRange(curPeriodStart, curPeriodEnd));
        }
        try {
            // Process recurring work efforts
            Set<GenericValue> exclusions = new HashSet<>();
            Set<GenericValue> inclusions = new HashSet<>();
            DateRange range = new DateRange(startStamp, endStamp);
            Calendar cal = UtilDateTime.toCalendar(startStamp, timeZone, locale);
            for (GenericValue workEffort : validWorkEfforts) {
                if (UtilValidate.isNotEmpty(workEffort.getString("tempExprId"))) {
                    // check if either the workeffort is public or the requested party is a member
                    if (UtilValidate.isNotEmpty(partyIdsToUse) && !"WES_PUBLIC".equals(workEffort.getString("scopeEnumId")) && !partyIdsToUse.contains(workEffort.getString("partyId"))) {
                        continue;
                    }
                    // if the workeffort has actual date time, using temporal expression has no sense
                    if (UtilValidate.isNotEmpty(workEffort.getTimestamp("actualStartDate")) || UtilValidate.isNotEmpty(workEffort.getTimestamp("actualCompletionDate"))) {
                        continue;
                    }
                    TemporalExpression tempExpr = TemporalExpressionWorker.getTemporalExpression(delegator, workEffort.getString("tempExprId"));
                    DateRange weRange = new DateRange(workEffort.getTimestamp("estimatedStartDate"), workEffort.getTimestamp("estimatedCompletionDate"));
                    Set<Date> occurrences = tempExpr.getRange(range, cal);
                    for (Date occurrence : occurrences) {
                        for (DateRange periodRange : periodRanges) {
                            if (periodRange.includesDate(occurrence)) {
                                GenericValue cloneWorkEffort = (GenericValue) workEffort.clone();
                                TimeDuration duration = TimeDuration.fromNumber(workEffort.getDouble("estimatedMilliSeconds"));
                                if (!duration.isZero()) {
                                    Calendar endCal = UtilDateTime.toCalendar(occurrence, timeZone, locale);
                                    Date endDate = duration.addToCalendar(endCal).getTime();
                                    cloneWorkEffort.set("estimatedStartDate", new Timestamp(occurrence.getTime()));
                                    cloneWorkEffort.set("estimatedCompletionDate", new Timestamp(endDate.getTime()));
                                } else {
                                    cloneWorkEffort.set("estimatedStartDate", periodRange.startStamp());
                                    cloneWorkEffort.set("estimatedCompletionDate", periodRange.endStamp());
                                }
                                if (weRange.includes(cloneWorkEffort.getTimestamp("estimatedStartDate"))) {
                                    inclusions.add(cloneWorkEffort);
                                }
                            }
                        }
                    }
                    exclusions.add(workEffort);
                }
            }
            validWorkEfforts.removeAll(exclusions);
            validWorkEfforts.addAll(inclusions);
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
        }
        // For each period in the set we check all work efforts to see if they fall within range
        boolean firstEntry = true;
        for (DateRange periodRange : periodRanges) {
            List<Map<String, Object>> curWorkEfforts = new LinkedList<>();
            Map<String, Object> entry = new HashMap<>();
            for (GenericValue workEffort : validWorkEfforts) {
                Timestamp startDate = workEffort.getTimestamp("estimatedStartDate");
                if (workEffort.getTimestamp("actualStartDate") != null) {
                    startDate = workEffort.getTimestamp("actualStartDate");
                }
                Timestamp endDate = workEffort.getTimestamp("estimatedCompletionDate");
                if (workEffort.getTimestamp("actualCompletionDate") != null) {
                    endDate = workEffort.getTimestamp("actualCompletionDate");
                }
                if (endDate == null) {
                    endDate = startDate;
                }
                DateRange weRange = new DateRange(startDate, endDate);
                if (periodRange.intersectsRange(weRange)) {
                    Map<String, Object> calEntry = new HashMap<>();
                    calEntry.put("workEffort", workEffort);
                    long length = ((weRange.end().after(endStamp) ? endStamp.getTime() : weRange.end().getTime()) - (weRange.start().before(startStamp) ? startStamp.getTime() : weRange.start().getTime()));
                    int periodSpan = (int) Math.ceil((double) length / periodLen);
                    if (length % periodLen == 0 && startDate.getTime() > periodRange.start().getTime()) {
                        periodSpan++;
                    }
                    calEntry.put("periodSpan", Integer.valueOf(periodSpan));
                    DateRange calEntryRange = new DateRange((weRange.start().before(startStamp) ? startStamp : weRange.start()), (weRange.end().after(endStamp) ? endStamp : weRange.end()));
                    calEntry.put("calEntryRange", calEntryRange);
                    if (firstEntry) {
                        // If this is the first period any valid entry is starting here
                        calEntry.put("startOfPeriod", Boolean.TRUE);
                        firstEntry = false;
                    } else {
                        boolean startOfPeriod = ((weRange.start().getTime() - periodRange.start().getTime()) >= 0);
                        calEntry.put("startOfPeriod", Boolean.valueOf(startOfPeriod));
                    }
                    curWorkEfforts.add(calEntry);
                }
            }
            int numEntries = curWorkEfforts.size();
            if (numEntries > maxConcurrentEntries) {
                maxConcurrentEntries = numEntries;
            }
            entry.put("start", periodRange.startStamp());
            entry.put("end", periodRange.endStamp());
            entry.put("calendarEntries", curWorkEfforts);
            entry.put("calendarEntriesByDateRange", groupCalendarEntriesByDateRange(periodRange, curWorkEfforts));
            periods.add(entry);
        }
    }
    Map<String, Object> result = new HashMap<>();
    result.put("periods", periods);
    result.put("maxConcurrentEntries", Integer.valueOf(maxConcurrentEntries));
    return result;
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) DateRange(org.apache.ofbiz.base.util.DateRange) TimeDuration(org.apache.ofbiz.base.util.TimeDuration) HashSet(java.util.HashSet) GenericValue(org.apache.ofbiz.entity.GenericValue) TemporalExpression(org.apache.ofbiz.service.calendar.TemporalExpression) Calendar(com.ibm.icu.util.Calendar) LinkedList(java.util.LinkedList) Date(java.util.Date) TimeZone(java.util.TimeZone) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 14 with EntityCondition

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

the class WorkEffortServices method getProductManufacturingSummaryByFacility.

public static Map<String, Object> getProductManufacturingSummaryByFacility(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    String productId = (String) context.get("productId");
    // optional
    String facilityId = (String) context.get("facilityId");
    Locale locale = (Locale) context.get("locale");
    Map<String, Map<String, Object>> summaryInByFacility = new HashMap<>();
    Map<String, Map<String, Object>> summaryOutByFacility = new HashMap<>();
    try {
        // 
        // Information about the running production runs that are going
        // to produce units of productId by facility.
        // 
        List<EntityCondition> findIncomingProductionRunsConds = new LinkedList<>();
        findIncomingProductionRunsConds.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
        findIncomingProductionRunsConds.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "WEGS_CREATED"));
        findIncomingProductionRunsConds.add(EntityCondition.makeCondition("workEffortGoodStdTypeId", EntityOperator.EQUALS, "PRUN_PROD_DELIV"));
        if (facilityId != null) {
            findIncomingProductionRunsConds.add(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId));
        }
        List<EntityCondition> findIncomingProductionRunsStatusConds = new LinkedList<>();
        findIncomingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_CREATED"));
        findIncomingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_SCHEDULED"));
        findIncomingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_DOC_PRINTED"));
        findIncomingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_RUNNING"));
        findIncomingProductionRunsConds.add(EntityCondition.makeCondition(findIncomingProductionRunsStatusConds, EntityOperator.OR));
        List<GenericValue> incomingProductionRuns = EntityQuery.use(delegator).from("WorkEffortAndGoods").where(findIncomingProductionRunsConds).orderBy("-estimatedCompletionDate").queryList();
        for (GenericValue incomingProductionRun : incomingProductionRuns) {
            double producedQtyTot = 0.0;
            if ("PRUN_COMPLETED".equals(incomingProductionRun.getString("currentStatusId"))) {
                List<GenericValue> inventoryItems = EntityQuery.use(delegator).from("WorkEffortAndInventoryProduced").where("productId", productId, "workEffortId", incomingProductionRun.getString("workEffortId")).queryList();
                for (GenericValue inventoryItem : inventoryItems) {
                    GenericValue inventoryItemDetail = EntityQuery.use(delegator).from("InventoryItemDetail").where("inventoryItemId", inventoryItem.getString("inventoryItemId")).orderBy("inventoryItemDetailSeqId").queryFirst();
                    if (inventoryItemDetail != null && inventoryItemDetail.get("quantityOnHandDiff") != null) {
                        Double inventoryItemQty = inventoryItemDetail.getDouble("quantityOnHandDiff");
                        producedQtyTot = producedQtyTot + inventoryItemQty.doubleValue();
                    }
                }
            }
            double estimatedQuantity = 0.0;
            if (incomingProductionRun.get("estimatedQuantity") != null) {
                estimatedQuantity = incomingProductionRun.getDouble("estimatedQuantity").doubleValue();
            }
            // the qty that still needs to be produced
            double remainingQuantity = estimatedQuantity - producedQtyTot;
            if (remainingQuantity > 0) {
                incomingProductionRun.set("estimatedQuantity", Double.valueOf(remainingQuantity));
            } else {
                continue;
            }
            String weFacilityId = incomingProductionRun.getString("facilityId");
            Map<String, Object> quantitySummary = UtilGenerics.checkMap(summaryInByFacility.get(weFacilityId));
            if (quantitySummary == null) {
                quantitySummary = new HashMap<>();
                quantitySummary.put("facilityId", weFacilityId);
                summaryInByFacility.put(weFacilityId, quantitySummary);
            }
            Double remainingQuantityTot = (Double) quantitySummary.get("estimatedQuantityTotal");
            if (remainingQuantityTot == null) {
                quantitySummary.put("estimatedQuantityTotal", Double.valueOf(remainingQuantity));
            } else {
                quantitySummary.put("estimatedQuantityTotal", Double.valueOf(remainingQuantity + remainingQuantityTot.doubleValue()));
            }
            List<GenericValue> incomingProductionRunList = UtilGenerics.checkList(quantitySummary.get("incomingProductionRunList"));
            if (incomingProductionRunList == null) {
                incomingProductionRunList = new LinkedList<>();
                quantitySummary.put("incomingProductionRunList", incomingProductionRunList);
            }
            incomingProductionRunList.add(incomingProductionRun);
        }
        // 
        // Information about the running production runs that are going
        // to consume units of productId by facility.
        // 
        List<EntityCondition> findOutgoingProductionRunsConds = new LinkedList<>();
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "WEGS_CREATED"));
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition("workEffortGoodStdTypeId", EntityOperator.EQUALS, "PRUNT_PROD_NEEDED"));
        if (facilityId != null) {
            findOutgoingProductionRunsConds.add(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId));
        }
        List<EntityCondition> findOutgoingProductionRunsStatusConds = new LinkedList<>();
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_CREATED"));
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_SCHEDULED"));
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_DOC_PRINTED"));
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_RUNNING"));
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition(findOutgoingProductionRunsStatusConds, EntityOperator.OR));
        List<GenericValue> outgoingProductionRuns = EntityQuery.use(delegator).from("WorkEffortAndGoods").where(findOutgoingProductionRunsConds).orderBy("-estimatedStartDate").queryList();
        for (GenericValue outgoingProductionRun : outgoingProductionRuns) {
            String weFacilityId = outgoingProductionRun.getString("facilityId");
            Double neededQuantity = outgoingProductionRun.getDouble("estimatedQuantity");
            if (neededQuantity == null) {
                neededQuantity = Double.valueOf(0);
            }
            Map<String, Object> quantitySummary = UtilGenerics.checkMap(summaryOutByFacility.get(weFacilityId));
            if (quantitySummary == null) {
                quantitySummary = new HashMap<>();
                quantitySummary.put("facilityId", weFacilityId);
                summaryOutByFacility.put(weFacilityId, quantitySummary);
            }
            Double remainingQuantityTot = (Double) quantitySummary.get("estimatedQuantityTotal");
            if (remainingQuantityTot == null) {
                quantitySummary.put("estimatedQuantityTotal", neededQuantity);
            } else {
                quantitySummary.put("estimatedQuantityTotal", Double.valueOf(neededQuantity.doubleValue() + remainingQuantityTot.doubleValue()));
            }
            List<GenericValue> outgoingProductionRunList = UtilGenerics.checkList(quantitySummary.get("outgoingProductionRunList"));
            if (outgoingProductionRunList == null) {
                outgoingProductionRunList = new LinkedList<>();
                quantitySummary.put("outgoingProductionRunList", outgoingProductionRunList);
            }
            outgoingProductionRunList.add(outgoingProductionRun);
        }
    } catch (GenericEntityException gee) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "WorkEffortManufacturingError", UtilMisc.toMap("productId", productId, "errorString", gee.getMessage()), locale));
    }
    Map<String, Object> resultMap = ServiceUtil.returnSuccess();
    resultMap.put("summaryInByFacility", summaryInByFacility);
    resultMap.put("summaryOutByFacility", summaryOutByFacility);
    return resultMap;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 15 with EntityCondition

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

the class PortalPageWorker method getPortalPage.

/**
 * Returns the PortalPage with the specified portalPageId.
 * If a specific PortalPage exists for the current userLogin it is returned instead of the original one.
 */
public static GenericValue getPortalPage(String portalPageId, Map<String, Object> context) {
    GenericValue portalPage = null;
    if (UtilValidate.isNotEmpty(portalPageId)) {
        Delegator delegator = WidgetWorker.getDelegator(context);
        try {
            // Get the current userLoginId
            String userLoginId = "_NA_";
            if (UtilValidate.isNotEmpty(context.get("userLogin"))) {
                // check if a user is logged in
                userLoginId = ((GenericValue) context.get("userLogin")).getString("userLoginId");
            }
            // Get the PortalPage ensuring that it is either owned by the user or a system page
            EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("portalPageId", EntityOperator.EQUALS, portalPageId), EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("ownerUserLoginId", EntityOperator.EQUALS, "_NA_"), EntityCondition.makeCondition("ownerUserLoginId", EntityOperator.EQUALS, userLoginId)), EntityOperator.OR)), EntityOperator.AND);
            List<GenericValue> portalPages = EntityQuery.use(delegator).from("PortalPage").where(cond).queryList();
            if (UtilValidate.isNotEmpty(portalPages)) {
                portalPage = EntityUtil.getFirst(portalPages);
            }
            // If a derived PortalPage private to the user exists, returns this instead of the system one
            cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("originalPortalPageId", EntityOperator.EQUALS, portalPageId), EntityCondition.makeCondition("ownerUserLoginId", EntityOperator.EQUALS, userLoginId)), EntityOperator.AND);
            List<GenericValue> privateDerivedPortalPages = EntityQuery.use(delegator).from("PortalPage").where(cond).queryList();
            if (UtilValidate.isNotEmpty(privateDerivedPortalPages)) {
                portalPage = EntityUtil.getFirst(privateDerivedPortalPages);
            }
        } catch (GenericEntityException e) {
            Debug.logError("Could not retrieve portalpage:" + e.getMessage(), module);
        }
    }
    return portalPage;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition)

Aggregations

EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)118 GenericValue (org.apache.ofbiz.entity.GenericValue)96 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)78 Delegator (org.apache.ofbiz.entity.Delegator)60 LinkedList (java.util.LinkedList)58 Locale (java.util.Locale)43 Timestamp (java.sql.Timestamp)40 HashMap (java.util.HashMap)32 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)29 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)26 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)24 Map (java.util.Map)22 BigDecimal (java.math.BigDecimal)21 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)18 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)14 GeneralException (org.apache.ofbiz.base.util.GeneralException)12 ArrayList (java.util.ArrayList)11 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)9 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)8 HashSet (java.util.HashSet)7