public static final String module = MrpServices.class.getName();
public static final String resource = "ManufacturingUiLabels";
public static Map initMrpEvents(DispatchContext ctx, Map context) {
GenericDelegator delegator = ctx.getDelegator();
LocalDispatcher dispatcher = ctx.getDispatcher();
Timestamp now = UtilDateTime.nowTimestamp();
String facilityId = (String)context.get("facilityId");
String manufacturingFacilityId = (String)context.get("manufacturingFacilityId");
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 listResult = null;
try {
listResult = delegator.findList("MrpEvent", null, null, null, null, false);
//int numOfRecordsRemoved = delegator.removeByCondition("MrpEvent", null);
} catch (GenericEntityException e) {
Debug.logError(e,"Error : findList(\"MrpEvent\", null, null, null, null, false)", module);
return ServiceUtil.returnError("Problem, we can not find all the items of MrpEvent, for more detail look at the log");
}
if (listResult != null) {
try {
delegator.removeAll(listResult);
} catch (GenericEntityException e) {
Debug.logError(e,"Error : removeAll(listResult), listResult ="+listResult, module);
return ServiceUtil.returnError("Problem, we can not remove the MrpEvent items, for more detail look at the log");
}
}
// Proposed requirements are deleted
listResult = null;
List listResultRoles = new ArrayList();
try {
listResult = delegator.findByAnd("Requirement", UtilMisc.toMap("requirementTypeId", "PRODUCT_REQUIREMENT", "statusId", "REQ_PROPOSED"));
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find all the items of MrpEvent, for more detail look at the log");
}
if (listResult != null) {
try {
Iterator listResultIt = listResult.iterator();
while (listResultIt.hasNext()) {
GenericValue tmpRequirement = (GenericValue)listResultIt.next();
listResultRoles.addAll(tmpRequirement.getRelated("RequirementRole"));
//int numOfRecordsRemoved = delegator.removeRelated("RequirementRole", tmpRequirement);
}
delegator.removeAll(listResultRoles);
delegator.removeAll(listResult);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not remove the MrpEvent items, for more detail look at the log");
}
}
listResult = null;
try {
listResult = delegator.findByAnd("Requirement", UtilMisc.toMap("requirementTypeId", "INTERNAL_REQUIREMENT", "statusId", "REQ_PROPOSED"));
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find all the items of MrpEvent, for more detail look at the log");
}
if (listResult != null) {
try {
delegator.removeAll(listResult);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not remove the MrpEvent items, for more detail look at the log");
}
}
GenericValue genericResult = null;
Map parameters = null;
List resultList = null;
Iterator iteratorResult = 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;
iteratorResult = null;
parameters = UtilMisc.toMap("orderTypeId", "SALES_ORDER", "oiStatusId", "ITEM_APPROVED");
parameters.put("facilityId", facilityId);
try {
resultList = delegator.findByAnd("OrderHeaderItemAndShipGroup", parameters, UtilMisc.toList("orderId"));
} catch (GenericEntityException e) {
Debug.logError(e, "Error : findByAnd(\"OrderItem\", parameters\")", module);
Debug.logError(e, "Error : parameters = "+parameters,module);
return ServiceUtil.returnError("Problem, we can not find the order items, for more detail look at the log");
}
iteratorResult = resultList.iterator();
while (iteratorResult.hasNext()) {
genericResult = (GenericValue) iteratorResult.next();
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("Problem initializing the MrpEvent entity (SALES_ORDER_SHIP)");
}
}
// ----------------------------------------
// Loads all the approved product requirements (po requirements)
// ----------------------------------------
resultList = null;
iteratorResult = null;
parameters = UtilMisc.toMap("requirementTypeId", "PRODUCT_REQUIREMENT", "statusId", "REQ_APPROVED", "facilityId", facilityId);
try {
resultList = delegator.findByAnd("Requirement", parameters);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find all the items of MrpEvent, for more detail look at the log");
}
iteratorResult = resultList.iterator();
while (iteratorResult.hasNext()) {
genericResult = (GenericValue) iteratorResult.next();
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("Problem initializing the MrpEvent entity (PROD_REQ_RECP)");
}
}
// ----------------------------------------
// Loads all the approved purchase order items
// ----------------------------------------
resultList = null;
iteratorResult = null;
String orderId = null;
GenericValue orderDeliverySchedule = null;
try {
List facilityContactMechs = EntityUtil.filterByDate(delegator.findByAnd("FacilityContactMech", UtilMisc.toMap("facilityId", facilityId)));
List facilityContactMechIds = EntityUtil.getFieldListFromEntityList(facilityContactMechs, "contactMechId", true);
List searchConditions = UtilMisc.toList(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER"),
EntityCondition.makeCondition("oiStatusId", EntityOperator.EQUALS, "ITEM_APPROVED"),
EntityCondition.makeCondition("contactMechId", EntityOperator.IN, facilityContactMechIds));
Set fieldsToSelect = UtilMisc.toSet("orderId", "orderItemSeqId", "productId", "quantity", "cancelQuantity", "oiEstimatedDeliveryDate");
resultList = delegator.findList("OrderHeaderItemAndShipGroup", EntityCondition.makeCondition(searchConditions, EntityOperator.AND), fieldsToSelect, UtilMisc.toList("orderDate"), null, false);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find the order items, for more detail look at the log");
}
iteratorResult = resultList.iterator();
while (iteratorResult.hasNext()) {
genericResult = (GenericValue) iteratorResult.next();
String newOrderId = genericResult.getString("orderId");
if (!newOrderId.equals(orderId)) {
orderDeliverySchedule = null;
orderId = newOrderId;
try {
orderDeliverySchedule = delegator.findByPrimaryKey("OrderDeliverySchedule", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", "_NA_"));
} catch (GenericEntityException e) {
}
}
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);
}
OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
BigDecimal shippedQuantity = null;
try {
shippedQuantity = orh.getItemShippedQuantity(genericResult.getRelatedOne("OrderItem"));
} catch (GenericEntityException e) {
}
if (UtilValidate.isNotEmpty(shippedQuantity)) {
shipGroupQuantity = shipGroupQuantity.subtract(shippedQuantity);
}
GenericValue orderItemDeliverySchedule = null;
try {
orderItemDeliverySchedule = delegator.findByPrimaryKey("OrderDeliverySchedule", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", genericResult.getString("orderItemSeqId")));
} catch (GenericEntityException e) {
}
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");
try {
InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, shipGroupQuantity, null, genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem initializing the MrpEvent entity (PUR_ORDER_RECP)");
}
}
// ----------------------------------------
// PRODUCTION Run: components
// ----------------------------------------
resultList = null;
iteratorResult = null;
parameters = UtilMisc.toMap("workEffortGoodStdTypeId", "PRUNT_PROD_NEEDED", "statusId", "WEGS_CREATED", "facilityId", facilityId);
try {
resultList = delegator.findByAnd("WorkEffortAndGoods", parameters);
} catch (GenericEntityException e) {
Debug.logError(e, "Error : findByAnd(\"OrderItem\", parameters\")", module);
Debug.logError(e, "Error : parameters = "+parameters,module);
return ServiceUtil.returnError("Problem, we can not find the order items, for more detail look at the log");
}
iteratorResult = resultList.iterator();
while (iteratorResult.hasNext()) {
genericResult = (GenericValue) iteratorResult.next();
String productId = genericResult.getString("productId");
BigDecimal eventQuantityTmp = genericResult.getBigDecimal("estimatedQuantity").negate();
Timestamp estimatedShipDate = genericResult.getTimestamp("estimatedStartDate");
if (estimatedShipDate == null) {
estimatedShipDate = now;
}
parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "MANUF_ORDER_REQ");
try {
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("Problem initializing the MrpEvent entity (MRP_REQUIREMENT)");
}
}
// ----------------------------------------
// PRODUCTION Run: product produced
// ----------------------------------------
resultList = null;
iteratorResult = null;
parameters = UtilMisc.toMap("workEffortGoodStdTypeId", "PRUN_PROD_DELIV", "statusId", "WEGS_CREATED", "workEffortTypeId", "PROD_ORDER_HEADER", "facilityId", facilityId);
try {
resultList = delegator.findByAnd("WorkEffortAndGoods", parameters);
} catch (GenericEntityException e) {
Debug.logError(e, "Error : findByAnd(\"OrderItem\", parameters\")", module);
Debug.logError(e, "Error : parameters = "+parameters,module);
return ServiceUtil.returnError("Problem, we can not find the order items, for more detail look at the log");
}
iteratorResult = resultList.iterator();
while (iteratorResult.hasNext()) {
genericResult = (GenericValue) iteratorResult.next();
if ("PRUN_CLOSED".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");
try {
InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("workEffortId"), false, delegator);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem initializing the MrpEvent entity (MANUF_ORDER_RECP)");
}
}
// ----------------------------------------
// Products without upcoming events but that are already under minimum quantity in warehouse
// ----------------------------------------
resultList = null;
iteratorResult = null;
parameters = UtilMisc.toMap("facilityId", facilityId);
try {
resultList = delegator.findByAnd("ProductFacility", parameters);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to retrieve ProductFacility records.", module);
return ServiceUtil.returnError("Unable to retrieve ProductFacility records.");
}
iteratorResult = resultList.iterator();
while (iteratorResult.hasNext()) {
genericResult = (GenericValue) iteratorResult.next();
String productId = genericResult.getString("productId");
BigDecimal minimumStock = genericResult.getBigDecimal("minimumStock");
if (minimumStock == null) {
minimumStock = BigDecimal.ZERO;
}
try {
EntityFieldMap ecl = EntityCondition.makeCondition(UtilMisc.toMap("mrpId", mrpId, "productId", productId), EntityOperator.AND);
long numOfEvents = delegator.findCountByCondition("MrpEvent", ecl, null, null);
if (numOfEvents > 0) {
continue;
}
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to count MrpEvent records.", module);
return ServiceUtil.returnError("Unable to count MrpEvent records.");
}
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("Problem initializing the MrpEvent entity (REQUIRED_MRP)");
}
}
// ----------------------------------------
// SALES FORECASTS
// ----------------------------------------
resultList = null;
iteratorResult = null;
GenericValue facility = null;
try {
facility = delegator.findOne("Facility", UtilMisc.toMap("facilityId", facilityId), false);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find Facility, for more detail look at the log");
}
String partyId = (String)facility.get("ownerPartyId");
try {
resultList = delegator.findByAnd("SalesForecast", UtilMisc.toMap("organizationPartyId", partyId));
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find SalesForecasts, for more detail look at the log");
}
iteratorResult = resultList.iterator();
while (iteratorResult.hasNext()) {
genericResult = (GenericValue) iteratorResult.next();
String customTimePeriodId = genericResult.getString("customTimePeriodId");
GenericValue customTimePeriod = null;
try {
customTimePeriod = delegator.findOne("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", customTimePeriodId), false);
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find CustomTimePeriod, for more detail look at the log");
}
if (customTimePeriod.getDate("thruDate").before(UtilDateTime.nowDate())) {
continue;
} else {
List salesForecastDetails = null;
Iterator sfdIter = null;
try {
salesForecastDetails = delegator.findByAnd("SalesForecastDetail", UtilMisc.toMap("salesForecastId", genericResult.getString("salesForecastId")));
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Problem, we can not find SalesForecastDetails, for more detail look at the log");
}
sfdIter = salesForecastDetails.iterator();
while (sfdIter.hasNext()) {