Search in sources :

Example 21 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class UtilValidate method isDateAfterToday.

/**
 * isDate returns true if string argument date forms a valid date and is after today.
 */
public static boolean isDateAfterToday(String date) {
    if (isEmpty(date)) {
        return defaultEmptyOK;
    }
    int dateSlash1 = date.indexOf("/");
    int dateSlash2 = date.lastIndexOf("/");
    if (dateSlash1 <= 0) {
        return false;
    }
    java.util.Date passed = null;
    if (dateSlash1 == dateSlash2) {
        // consider the day to be optional; use the first day of the following month for comparison since this is an is after test
        String month = date.substring(0, dateSlash1);
        String day = "28";
        String year = date.substring(dateSlash1 + 1);
        if (!isDate(year, month, day)) {
            return false;
        }
        try {
            int monthInt = Integer.parseInt(month);
            int yearInt = Integer.parseInt(year);
            Calendar calendar = Calendar.getInstance();
            calendar.set(yearInt, monthInt - 1, 0, 0, 0, 0);
            calendar.add(Calendar.MONTH, 1);
            passed = new java.util.Date(calendar.getTime().getTime());
        } catch (NumberFormatException e) {
            passed = null;
        }
    } else {
        String month = date.substring(0, dateSlash1);
        String day = date.substring(dateSlash1 + 1, dateSlash2);
        String year = date.substring(dateSlash2 + 1);
        if (!isDate(year, month, day)) {
            return false;
        }
        passed = UtilDateTime.toDate(month, day, year, "0", "0", "0");
    }
    java.util.Date now = UtilDateTime.nowDate();
    if (passed != null) {
        return passed.after(now);
    }
    return false;
}
Also used : Calendar(com.ibm.icu.util.Calendar)

Example 22 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class UtilValidate method isDateBeforeToday.

/**
 * isDate returns true if string argument date forms a valid date and is before today.
 */
public static boolean isDateBeforeToday(String date) {
    if (isEmpty(date)) {
        return defaultEmptyOK;
    }
    int dateSlash1 = date.indexOf("/");
    int dateSlash2 = date.lastIndexOf("/");
    if (dateSlash1 <= 0) {
        // In this case an issue number has been provided (requires a javascript check in template!)
        return defaultEmptyOK;
    }
    java.util.Date passed = null;
    if (dateSlash1 == dateSlash2) {
        // consider the day to be optional; use the first day of the following month for comparison since this is an is after test
        String month = date.substring(0, dateSlash1);
        String day = "28";
        String year = date.substring(dateSlash1 + 1);
        if (!isDate(year, month, day)) {
            return false;
        }
        try {
            int monthInt = Integer.parseInt(month);
            int yearInt = Integer.parseInt(year);
            Calendar calendar = Calendar.getInstance();
            calendar.set(yearInt, monthInt - 1, 0, 0, 0, 0);
            calendar.add(Calendar.MONTH, 1);
            passed = new java.util.Date(calendar.getTime().getTime());
        } catch (NumberFormatException e) {
            passed = null;
        }
    } else {
        String month = date.substring(0, dateSlash1);
        String day = date.substring(dateSlash1 + 1, dateSlash2);
        String year = date.substring(dateSlash2 + 1);
        if (!isDate(year, month, day)) {
            return false;
        }
        passed = UtilDateTime.toDate(month, day, year, "0", "0", "0");
    }
    java.util.Date now = UtilDateTime.nowDate();
    if (passed != null) {
        return passed.before(now);
    }
    return false;
}
Also used : Calendar(com.ibm.icu.util.Calendar)

Example 23 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class TimeDurationTests method testDuration.

public void testDuration() throws Exception {
    Calendar now = Calendar.getInstance();
    TimeDuration zeroDuration = TimeDuration.ZeroTimeDuration;
    assertFalse("zero equals null", zeroDuration.equals(null));
    Calendar newTime = (Calendar) now.clone();
    zeroDuration.addToCalendar(newTime);
    assertEquals("zero same calendar", now, newTime);
    assertDurationFields("zero(same zero calendar)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", new TimeDuration(zero, zero), false, true);
    assertDurationFields("zero(same now calendar)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", new TimeDuration(now, now), false, true);
    assertDurationFields("zero(empty parse)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.parseDuration(""), false, true);
    assertDurationFields("zero(zero parse)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.parseDuration("0:0:0:0:0:0:0"), false, true);
    assertDurationFields("zero(from null number)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.fromNumber(null), false, true);
    assertDurationFields("zero(from null number)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.fromNumber(null), false, true);
    assertDuration("millisecond", 0, 0, 0, 0, 0, 0, 1);
    assertDuration("second", 0, 0, 0, 0, 0, 1, 0);
    assertDuration("minute", 0, 0, 0, 0, 1, 0, 0);
    assertDuration("hour", 0, 0, 0, 1, 0, 0, 0);
    assertDuration("day", 0, 0, 1, 0, 0, 0, 0);
    assertDuration("month", 0, 1, 0, 0, 0, 0, 0);
    assertDuration("year", 1, 0, 0, 0, 0, 0, 0);
    Calendar start = new com.ibm.icu.util.GregorianCalendar(1967, 1, 1, 0, 0, 0);
    start.set(Calendar.MILLISECOND, 0);
    Calendar end = (Calendar) start.clone();
    end.add(Calendar.MILLISECOND, 1);
    end.add(Calendar.SECOND, 1);
    end.add(Calendar.MINUTE, 1);
    end.add(Calendar.HOUR_OF_DAY, 1);
    end.add(Calendar.DAY_OF_MONTH, 1);
    end.add(Calendar.MONTH, 1);
    end.add(Calendar.YEAR, 1);
    assertDurationFields("pre-epoch elapsed time", 1, 1, 1, 1, 1, 1, 1, "1:1:1:1:1:1:1", new TimeDuration(start, end), false, false);
}
Also used : Calendar(com.ibm.icu.util.Calendar) TimeDuration(org.apache.ofbiz.base.util.TimeDuration)

Example 24 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class PersistedServiceJob method init.

@Override
protected void init() throws InvalidJobException {
    super.init();
    try {
        jobValue.refresh();
    } catch (GenericEntityException e) {
        throw new InvalidJobException("Unable to refresh JobSandbox value", e);
    }
    if (!JobManager.instanceId.equals(jobValue.getString("runByInstanceId"))) {
        throw new InvalidJobException("Job has been accepted by a different instance");
    }
    if (jobValue.getTimestamp("cancelDateTime") != null) {
        // Job cancelled
        throw new InvalidJobException("Job [" + getJobId() + "] was cancelled");
    }
    jobValue.set("startDateTime", UtilDateTime.nowTimestamp());
    jobValue.set("statusId", "SERVICE_RUNNING");
    try {
        jobValue.store();
    } catch (GenericEntityException e) {
        throw new InvalidJobException("Unable to set the startDateTime and statusId on the current job [" + getJobId() + "]; not running!", e);
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("Job [" + getJobId() + "] running", module);
    }
    // configure any additional recurrences
    long maxRecurrenceCount = -1;
    long currentRecurrenceCount = 0;
    TemporalExpression expr = null;
    RecurrenceInfo recurrence = getRecurrenceInfo();
    if (recurrence != null) {
        Debug.logWarning("Persisted Job [" + getJobId() + "] references a RecurrenceInfo, recommend using TemporalExpression instead", module);
        currentRecurrenceCount = recurrence.getCurrentCount();
        expr = RecurrenceInfo.toTemporalExpression(recurrence);
    }
    if (expr == null && UtilValidate.isNotEmpty(jobValue.getString("tempExprId"))) {
        try {
            expr = TemporalExpressionWorker.getTemporalExpression(this.delegator, jobValue.getString("tempExprId"));
        } catch (GenericEntityException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    if (jobValue.get("maxRecurrenceCount") != null) {
        maxRecurrenceCount = jobValue.getLong("maxRecurrenceCount").longValue();
    }
    if (jobValue.get("currentRecurrenceCount") != null) {
        currentRecurrenceCount = jobValue.getLong("currentRecurrenceCount").longValue();
    }
    if (maxRecurrenceCount != -1) {
        currentRecurrenceCount++;
        jobValue.set("currentRecurrenceCount", currentRecurrenceCount);
    }
    try {
        if (expr != null && (maxRecurrenceCount == -1 || currentRecurrenceCount <= maxRecurrenceCount)) {
            if (recurrence != null) {
                recurrence.incrementCurrentCount();
            }
            Calendar next = expr.next(Calendar.getInstance());
            if (next != null) {
                createRecurrence(next.getTimeInMillis(), false);
            }
        }
    } catch (GenericEntityException e) {
        throw new InvalidJobException(e);
    }
    if (Debug.infoOn()) {
        Debug.logInfo("Job  [" + getJobName() + "] Id [" + getJobId() + "] -- Next runtime: " + new Date(nextRecurrence), module);
    }
}
Also used : TemporalExpression(org.apache.ofbiz.service.calendar.TemporalExpression) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) RecurrenceInfo(org.apache.ofbiz.service.calendar.RecurrenceInfo) Calendar(com.ibm.icu.util.Calendar) Date(java.util.Date)

Example 25 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class MrpServices method initMrpEvents.

public static Map<String, Object> initMrpEvents(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Timestamp now = UtilDateTime.nowTimestamp();
    Locale locale = (Locale) context.get("locale");
    String facilityId = (String) context.get("facilityId");
    Integer defaultYearsOffset = (Integer) context.get("defaultYearsOffset");
    String mrpId = (String) context.get("mrpId");
    // Erases the old table for the moment and initializes it with the new orders,
    // Does not modify the old one now.
    List<GenericValue> listResult = null;
    try {
        listResult = EntityQuery.use(delegator).from("MrpEvent").queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error : findList(\"MrpEvent\", null, null, null, null, false)", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventFindError", locale));
    }
    if (listResult != null) {
        try {
            delegator.removeAll(listResult);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error : removeAll(listResult), listResult =" + listResult, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventRemoveError", locale));
        }
    }
    // Proposed requirements are deleted
    listResult = null;
    List<GenericValue> listResultRoles = new LinkedList<GenericValue>();
    try {
        listResult = EntityQuery.use(delegator).from("Requirement").where("requirementTypeId", "PRODUCT_REQUIREMENT", "facilityId", facilityId, "statusId", "REQ_PROPOSED").queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventFindError", locale));
    }
    if (listResult != null) {
        try {
            for (GenericValue tmpRequirement : listResult) {
                listResultRoles.addAll(tmpRequirement.getRelated("RequirementRole", null, null, false));
            }
            delegator.removeAll(listResultRoles);
            delegator.removeAll(listResult);
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventRemoveError", locale));
        }
    }
    listResult = null;
    try {
        listResult = EntityQuery.use(delegator).from("Requirement").where("requirementTypeId", "INTERNAL_REQUIREMENT", "facilityId", facilityId, "statusId", "REQ_PROPOSED").queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventFindError", locale));
    }
    if (listResult != null) {
        try {
            delegator.removeAll(listResult);
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventRemoveError", locale));
        }
    }
    Map<String, Object> parameters = null;
    List<GenericValue> resultList = null;
    // ----------------------------------------
    // Loads all the approved sales order items and purchase order items
    // ----------------------------------------
    // This is the default required date for orders without dates specified:
    // by convention it is a date far in the future of 100 years.
    Timestamp notAssignedDate = null;
    if (UtilValidate.isEmpty(defaultYearsOffset)) {
        notAssignedDate = now;
    } else {
        Calendar calendar = UtilDateTime.toCalendar(now);
        calendar.add(Calendar.YEAR, defaultYearsOffset.intValue());
        notAssignedDate = new Timestamp(calendar.getTimeInMillis());
    }
    resultList = null;
    try {
        resultList = EntityQuery.use(delegator).from("OrderHeaderItemAndShipGroup").where("orderTypeId", "SALES_ORDER", "oiStatusId", "ITEM_APPROVED", "facilityId", facilityId).orderBy("orderId").queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventFindError", locale));
    }
    for (GenericValue genericResult : resultList) {
        String productId = genericResult.getString("productId");
        BigDecimal reservedQuantity = genericResult.getBigDecimal("reservedQuantity");
        BigDecimal shipGroupQuantity = genericResult.getBigDecimal("quantity");
        BigDecimal cancelledQuantity = genericResult.getBigDecimal("cancelQuantity");
        BigDecimal eventQuantityTmp = BigDecimal.ZERO;
        if (UtilValidate.isNotEmpty(reservedQuantity)) {
            eventQuantityTmp = reservedQuantity.negate();
        } else {
            if (UtilValidate.isNotEmpty(cancelledQuantity)) {
                shipGroupQuantity = shipGroupQuantity.subtract(cancelledQuantity);
            }
            eventQuantityTmp = shipGroupQuantity.negate();
        }
        if (eventQuantityTmp.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }
        // This is the order in which order dates are considered:
        // OrderItemShipGroup.shipByDate
        // OrderItemShipGroup.shipAfterDate
        // OrderItem.shipBeforeDate
        // OrderItem.shipAfterDate
        // OrderItem.estimatedDeliveryDate
        Timestamp requiredByDate = genericResult.getTimestamp("shipByDate");
        if (UtilValidate.isEmpty(requiredByDate)) {
            requiredByDate = genericResult.getTimestamp("shipAfterDate");
            if (UtilValidate.isEmpty(requiredByDate)) {
                requiredByDate = genericResult.getTimestamp("oiShipBeforeDate");
                if (UtilValidate.isEmpty(requiredByDate)) {
                    requiredByDate = genericResult.getTimestamp("oiShipAfterDate");
                    if (UtilValidate.isEmpty(requiredByDate)) {
                        requiredByDate = genericResult.getTimestamp("oiEstimatedDeliveryDate");
                        if (requiredByDate == null) {
                            requiredByDate = notAssignedDate;
                        }
                    }
                }
            }
        }
        parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", requiredByDate, "mrpEventTypeId", "SALES_ORDER_SHIP");
        try {
            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator);
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "SALES_ORDER_SHIP"), locale));
        }
    }
    // ----------------------------------------
    // Loads all the approved product requirements (po requirements)
    // ----------------------------------------
    resultList = null;
    try {
        resultList = EntityQuery.use(delegator).from("Requirement").where("requirementTypeId", "PRODUCT_REQUIREMENT", "statusId", "REQ_APPROVED", "facilityId", facilityId).queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventFindError", locale));
    }
    for (GenericValue genericResult : resultList) {
        String productId = genericResult.getString("productId");
        BigDecimal eventQuantityTmp = genericResult.getBigDecimal("quantity");
        if (productId == null || eventQuantityTmp == null) {
            continue;
        }
        Timestamp estimatedShipDate = genericResult.getTimestamp("requiredByDate");
        if (estimatedShipDate == null) {
            estimatedShipDate = now;
        }
        parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "PROD_REQ_RECP");
        try {
            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("requirementId"), false, delegator);
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "PROD_REQ_RECP"), locale));
        }
    }
    // ----------------------------------------
    // Loads all the approved purchase order items
    // ----------------------------------------
    resultList = null;
    String orderId = null;
    GenericValue orderDeliverySchedule = null;
    try {
        List<GenericValue> facilityContactMechs = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).filterByDate().queryList();
        List<String> facilityContactMechIds = EntityUtil.getFieldListFromEntityList(facilityContactMechs, "contactMechId", true);
        resultList = EntityQuery.use(delegator).select("orderId", "orderItemSeqId", "productId", "quantity", "cancelQuantity", "oiEstimatedDeliveryDate").from("OrderHeaderItemAndShipGroup").where(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER"), EntityCondition.makeCondition("oiStatusId", EntityOperator.EQUALS, "ITEM_APPROVED"), EntityCondition.makeCondition("contactMechId", EntityOperator.IN, facilityContactMechIds)).orderBy("orderDate").queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventFindError", locale));
    }
    for (GenericValue genericResult : resultList) {
        try {
            String newOrderId = genericResult.getString("orderId");
            if (!newOrderId.equals(orderId)) {
                orderDeliverySchedule = null;
                orderId = newOrderId;
                orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne();
            }
            String productId = genericResult.getString("productId");
            BigDecimal shipGroupQuantity = genericResult.getBigDecimal("quantity");
            BigDecimal cancelledQuantity = genericResult.getBigDecimal("cancelQuantity");
            if (UtilValidate.isEmpty(shipGroupQuantity)) {
                shipGroupQuantity = BigDecimal.ZERO;
            }
            if (UtilValidate.isNotEmpty(cancelledQuantity)) {
                shipGroupQuantity = shipGroupQuantity.subtract(cancelledQuantity);
            }
            try {
                List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from("ShipmentReceipt").where("orderId", genericResult.getString("orderId"), "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryList();
                for (GenericValue shipmentReceipt : shipmentReceipts) {
                    shipGroupQuantity = shipGroupQuantity.subtract(shipmentReceipt.getBigDecimal("quantityAccepted"));
                    shipGroupQuantity = shipGroupQuantity.subtract(shipmentReceipt.getBigDecimal("quantityRejected"));
                }
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
            GenericValue orderItemDeliverySchedule = null;
            orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryOne();
            Timestamp estimatedShipDate = null;
            if (orderItemDeliverySchedule != null && orderItemDeliverySchedule.get("estimatedReadyDate") != null) {
                estimatedShipDate = orderItemDeliverySchedule.getTimestamp("estimatedReadyDate");
            } else if (orderDeliverySchedule != null && orderDeliverySchedule.get("estimatedReadyDate") != null) {
                estimatedShipDate = orderDeliverySchedule.getTimestamp("estimatedReadyDate");
            } else {
                estimatedShipDate = genericResult.getTimestamp("oiEstimatedDeliveryDate");
            }
            if (estimatedShipDate == null) {
                estimatedShipDate = now;
            }
            parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "PUR_ORDER_RECP");
            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, shipGroupQuantity, null, genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator);
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "PUR_ORDER_RECP"), locale));
        }
    }
    // ----------------------------------------
    // PRODUCTION Run: components
    // ----------------------------------------
    resultList = null;
    try {
        resultList = EntityQuery.use(delegator).from("WorkEffortAndGoods").where("workEffortGoodStdTypeId", "PRUNT_PROD_NEEDED", "statusId", "WEGS_CREATED", "facilityId", facilityId).queryList();
        for (GenericValue genericResult : resultList) {
            if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId")) || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId")) || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) {
                continue;
            }
            String productId = genericResult.getString("productId");
            // get the inventory already consumed
            BigDecimal consumedInventoryTotal = BigDecimal.ZERO;
            List<GenericValue> consumedInventoryItems = EntityQuery.use(delegator).from("WorkEffortAndInventoryAssign").where("workEffortId", genericResult.get("workEffortId"), "productId", productId).queryList();
            for (GenericValue consumedInventoryItem : consumedInventoryItems) {
                consumedInventoryTotal = consumedInventoryTotal.add(consumedInventoryItem.getBigDecimal("quantity"));
            }
            BigDecimal eventQuantityTmp = consumedInventoryTotal.subtract(genericResult.getBigDecimal("estimatedQuantity"));
            Timestamp estimatedShipDate = genericResult.getTimestamp("estimatedStartDate");
            if (estimatedShipDate == null) {
                estimatedShipDate = now;
            }
            parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "MANUF_ORDER_REQ");
            String eventName = (UtilValidate.isEmpty(genericResult.getString("workEffortParentId")) ? genericResult.getString("workEffortId") : genericResult.getString("workEffortParentId") + "-" + genericResult.getString("workEffortId"));
            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, eventName, false, delegator);
        }
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "MANUF_ORDER_REQ"), locale) + " " + e.getMessage());
    }
    // ----------------------------------------
    // PRODUCTION Run: product produced
    // ----------------------------------------
    resultList = null;
    try {
        resultList = EntityQuery.use(delegator).from("WorkEffortAndGoods").where("workEffortGoodStdTypeId", "PRUN_PROD_DELIV", "statusId", "WEGS_CREATED", "workEffortTypeId", "PROD_ORDER_HEADER", "facilityId", facilityId).queryList();
        for (GenericValue genericResult : resultList) {
            if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId")) || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId")) || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) {
                continue;
            }
            BigDecimal qtyToProduce = genericResult.getBigDecimal("quantityToProduce");
            if (qtyToProduce == null) {
                qtyToProduce = BigDecimal.ZERO;
            }
            BigDecimal qtyProduced = genericResult.getBigDecimal("quantityProduced");
            if (qtyProduced == null) {
                qtyProduced = BigDecimal.ZERO;
            }
            if (qtyProduced.compareTo(qtyToProduce) >= 0) {
                continue;
            }
            BigDecimal qtyDiff = qtyToProduce.subtract(qtyProduced);
            String productId = genericResult.getString("productId");
            BigDecimal eventQuantityTmp = qtyDiff;
            Timestamp estimatedShipDate = genericResult.getTimestamp("estimatedCompletionDate");
            if (estimatedShipDate == null) {
                estimatedShipDate = now;
            }
            parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "MANUF_ORDER_RECP");
            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("workEffortId"), false, delegator);
        }
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "MANUF_ORDER_RECP"), locale) + " " + e.getMessage());
    }
    // ----------------------------------------
    // Products without upcoming events but that are already under minimum quantity in warehouse
    // ----------------------------------------
    resultList = null;
    parameters = UtilMisc.<String, Object>toMap("facilityId", facilityId);
    try {
        resultList = EntityQuery.use(delegator).from("ProductFacility").where("facilityId", facilityId).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Unable to retrieve ProductFacility records.", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpCannotFindProductFacility", locale));
    }
    for (GenericValue genericResult : resultList) {
        String productId = genericResult.getString("productId");
        BigDecimal minimumStock = genericResult.getBigDecimal("minimumStock");
        if (minimumStock == null) {
            minimumStock = BigDecimal.ZERO;
        }
        try {
            long numOfEvents = EntityQuery.use(delegator).from("MrpEvent").where("mrpId", mrpId, "productId", productId).queryCount();
            if (numOfEvents > 0) {
                continue;
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Unable to count MrpEvent records.", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpCannotCountRecords", locale));
        }
        BigDecimal qoh = findProductMrpQoh(mrpId, productId, facilityId, dispatcher, delegator);
        if (qoh.compareTo(minimumStock) >= 0) {
            continue;
        }
        parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", now, "mrpEventTypeId", "REQUIRED_MRP");
        try {
            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, BigDecimal.ZERO, null, null, false, delegator);
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "REQUIRED_MRP"), locale));
        }
    }
    // ----------------------------------------
    // SALES FORECASTS
    // ----------------------------------------
    resultList = null;
    GenericValue facility = null;
    try {
        facility = EntityQuery.use(delegator).from("Facility").where("facilityId", facilityId).queryOne();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventFindError", locale));
    }
    String partyId = (String) facility.get("ownerPartyId");
    try {
        resultList = EntityQuery.use(delegator).from("SalesForecast").where("organizationPartyId", partyId).queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpCannotFindSalesForecasts", locale));
    }
    for (GenericValue genericResult : resultList) {
        String customTimePeriodId = genericResult.getString("customTimePeriodId");
        GenericValue customTimePeriod = null;
        try {
            customTimePeriod = EntityQuery.use(delegator).from("CustomTimePeriod").where("customTimePeriodId", customTimePeriodId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpCannotFindCustomTimePeriod", locale));
        }
        if (customTimePeriod != null) {
            if (UtilValidate.isNotEmpty(customTimePeriod.getTimestamp("thruDate")) && customTimePeriod.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp())) {
                continue;
            } else {
                List<GenericValue> salesForecastDetails = null;
                try {
                    salesForecastDetails = EntityQuery.use(delegator).from("SalesForecastDetail").where("salesForecastId", genericResult.get("salesForecastId")).queryList();
                } catch (GenericEntityException e) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpCannotFindSalesForecastDetails", locale));
                }
                for (GenericValue sfd : salesForecastDetails) {
                    String productId = sfd.getString("productId");
                    BigDecimal eventQuantityTmp = sfd.getBigDecimal("quantity");
                    if (productId == null || eventQuantityTmp == null) {
                        continue;
                    }
                    eventQuantityTmp = eventQuantityTmp.negate();
                    parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", customTimePeriod.getDate("fromDate"), "mrpEventTypeId", "SALES_FORECAST");
                    try {
                        InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, sfd.getString("salesForecastDetailId"), false, delegator);
                    } catch (GenericEntityException e) {
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "SALES_FORECAST"), locale));
                    }
                }
            }
        }
    }
    Map<String, Object> result = new HashMap<String, Object>();
    result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    Debug.logInfo("return from initMrpEvent", 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) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Aggregations

Calendar (com.ibm.icu.util.Calendar)75 Timestamp (java.sql.Timestamp)37 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)24 GenericValue (org.apache.ofbiz.entity.GenericValue)24 Delegator (org.apache.ofbiz.entity.Delegator)17 Date (java.util.Date)14 HashMap (java.util.HashMap)12 Locale (java.util.Locale)12 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)11 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)11 GregorianCalendar (com.ibm.icu.util.GregorianCalendar)10 ArrayList (java.util.ArrayList)8 SimpleDateFormat (java.text.SimpleDateFormat)6 LinkedList (java.util.LinkedList)6 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)6 Map (java.util.Map)5 TimeDuration (org.apache.ofbiz.base.util.TimeDuration)5 BigDecimal (java.math.BigDecimal)4 Time (java.sql.Time)4 UtilDateTime (org.apache.ofbiz.base.util.UtilDateTime)4