use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.
the class InventoryServices method checkInventoryAvailability.
/**
* In spite of the generic name this does the very specific task of checking availability of all back-ordered items and sends notices, etc
*/
public static Map<String, Object> checkInventoryAvailability(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
Map<String, Map<String, Timestamp>> ordersToUpdate = new HashMap<>();
Map<String, Map<String, Timestamp>> ordersToCancel = new HashMap<>();
// find all inventory items w/ a negative ATP
List<GenericValue> inventoryItems = null;
try {
inventoryItems = EntityQuery.use(delegator).from("InventoryItem").where(EntityCondition.makeCondition("availableToPromiseTotal", EntityOperator.LESS_THAN, BigDecimal.ZERO)).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Trouble getting inventory items", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveInventoryItem", locale));
}
if (inventoryItems == null) {
Debug.logInfo("No items out of stock; no backorders to worry about", module);
return ServiceUtil.returnSuccess();
}
Debug.logInfo("OOS Inventory Items: " + inventoryItems.size(), module);
for (GenericValue inventoryItem : inventoryItems) {
// get the incomming shipment information for the item
List<GenericValue> shipmentAndItems = null;
try {
List<EntityExpr> exprs = new ArrayList<>();
exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, inventoryItem.get("productId")));
exprs.add(EntityCondition.makeCondition("destinationFacilityId", EntityOperator.EQUALS, inventoryItem.get("facilityId")));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "SHIPMENT_DELIVERED"));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "SHIPMENT_CANCELLED"));
shipmentAndItems = EntityQuery.use(delegator).from("ShipmentAndItem").where(EntityCondition.makeCondition(exprs, EntityOperator.AND)).orderBy("estimatedArrivalDate").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting ShipmentAndItem records", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveShipmentAndItem", locale));
}
// get the reservations in order of newest first
List<GenericValue> reservations = null;
try {
reservations = inventoryItem.getRelated("OrderItemShipGrpInvRes", null, UtilMisc.toList("-reservedDatetime"), false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting related reservations", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveRelativeReservation", locale));
}
if (reservations == null) {
Debug.logWarning("No outstanding reservations for this inventory item, why is it negative then?", module);
continue;
}
Debug.logInfo("Reservations for item: " + reservations.size(), module);
// available at the time of order
BigDecimal availableBeforeReserved = inventoryItem.getBigDecimal("availableToPromiseTotal");
// go through all the reservations in order
for (GenericValue reservation : reservations) {
String orderId = reservation.getString("orderId");
String orderItemSeqId = reservation.getString("orderItemSeqId");
Timestamp promisedDate = reservation.getTimestamp("promisedDatetime");
Timestamp currentPromiseDate = reservation.getTimestamp("currentPromisedDate");
Timestamp actualPromiseDate = currentPromiseDate;
if (actualPromiseDate == null) {
if (promisedDate != null) {
actualPromiseDate = promisedDate;
} else {
// fall back if there is no promised date stored
actualPromiseDate = reservation.getTimestamp("reservedDatetime");
}
}
Debug.logInfo("Promised Date: " + actualPromiseDate, module);
// find the next possible ship date
Timestamp nextShipDate = null;
BigDecimal availableAtTime = BigDecimal.ZERO;
for (GenericValue shipmentItem : shipmentAndItems) {
availableAtTime = availableAtTime.add(shipmentItem.getBigDecimal("quantity"));
if (availableAtTime.compareTo(availableBeforeReserved) >= 0) {
nextShipDate = shipmentItem.getTimestamp("estimatedArrivalDate");
break;
}
}
Debug.logInfo("Next Ship Date: " + nextShipDate, module);
// create a modified promise date (promise date - 1 day)
Calendar pCal = Calendar.getInstance();
pCal.setTimeInMillis(actualPromiseDate.getTime());
pCal.add(Calendar.DAY_OF_YEAR, -1);
Timestamp modifiedPromisedDate = new Timestamp(pCal.getTimeInMillis());
Timestamp now = UtilDateTime.nowTimestamp();
Debug.logInfo("Promised Date + 1: " + modifiedPromisedDate, module);
Debug.logInfo("Now: " + now, module);
// check the promised date vs the next ship date
if (nextShipDate == null || nextShipDate.after(actualPromiseDate)) {
if (nextShipDate == null && modifiedPromisedDate.after(now)) {
// do nothing; we are okay to assume it will be shipped on time
Debug.logInfo("No ship date known yet, but promised date hasn't approached, assuming it will be here on time", module);
} else {
// we cannot ship by the promised date; need to notify the customer
Debug.logInfo("We won't ship on time, getting notification info", module);
Map<String, Timestamp> notifyItems = ordersToUpdate.get(orderId);
if (notifyItems == null) {
notifyItems = new HashMap<>();
}
notifyItems.put(orderItemSeqId, nextShipDate);
ordersToUpdate.put(orderId, notifyItems);
// need to know if nextShipDate is more then 30 days after promised
Calendar sCal = Calendar.getInstance();
sCal.setTimeInMillis(actualPromiseDate.getTime());
sCal.add(Calendar.DAY_OF_YEAR, 30);
Timestamp farPastPromised = new Timestamp(sCal.getTimeInMillis());
// check to see if this is >30 days or second run, if so flag to cancel
boolean needToCancel = false;
if (nextShipDate == null || nextShipDate.after(farPastPromised)) {
// we cannot ship until >30 days after promised; using cancel rule
Debug.logInfo("Ship date is >30 past the promised date", module);
needToCancel = true;
} else if (currentPromiseDate != null && actualPromiseDate.equals(currentPromiseDate)) {
// this is the second notification; using cancel rule
needToCancel = true;
}
// add the info to the cancel map if we need to schedule a cancel
if (needToCancel) {
// queue the item to be cancelled
Debug.logInfo("Flagging the item to auto-cancel", module);
Map<String, Timestamp> cancelItems = ordersToCancel.get(orderId);
if (cancelItems == null) {
cancelItems = new HashMap<>();
}
cancelItems.put(orderItemSeqId, farPastPromised);
ordersToCancel.put(orderId, cancelItems);
}
// store the updated promiseDate as the nextShipDate
try {
reservation.set("currentPromisedDate", nextShipDate);
reservation.store();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem storing reservation : " + reservation, module);
}
}
}
// subtract our qty from reserved to get the next value
availableBeforeReserved = availableBeforeReserved.subtract(reservation.getBigDecimal("quantity"));
}
}
// all items to cancel will also be in the notify list so start with that
List<String> ordersToNotify = new LinkedList<>();
for (Map.Entry<String, Map<String, Timestamp>> entry : ordersToUpdate.entrySet()) {
String orderId = entry.getKey();
Map<String, Timestamp> backOrderedItems = entry.getValue();
Map<String, Timestamp> cancelItems = ordersToCancel.get(orderId);
boolean cancelAll = false;
Timestamp cancelAllTime = null;
List<GenericValue> orderItemShipGroups = null;
try {
orderItemShipGroups = EntityQuery.use(delegator).from("OrderItemShipGroup").where("orderId", orderId).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot get OrderItemShipGroups from orderId" + orderId, module);
}
for (GenericValue orderItemShipGroup : orderItemShipGroups) {
List<GenericValue> orderItems = new LinkedList<>();
List<GenericValue> orderItemShipGroupAssoc = null;
try {
orderItemShipGroupAssoc = EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("shipGroupSeqId", orderItemShipGroup.get("shipGroupSeqId"), "orderId", orderId).queryList();
for (GenericValue assoc : orderItemShipGroupAssoc) {
GenericValue orderItem = assoc.getRelatedOne("OrderItem", false);
if (orderItem != null) {
orderItems.add(orderItem);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem fetching OrderItemShipGroupAssoc", module);
}
/* Check the split preference. */
boolean maySplit = false;
if (orderItemShipGroup.get("maySplit") != null) {
maySplit = orderItemShipGroup.getBoolean("maySplit").booleanValue();
}
/* Figure out if we must cancel all items. */
if (!maySplit && cancelItems != null) {
cancelAll = true;
Set<String> cancelSet = cancelItems.keySet();
cancelAllTime = cancelItems.get(cancelSet.iterator().next());
}
// if there are none to cancel just create an empty map
if (cancelItems == null) {
cancelItems = new HashMap<>();
}
List<GenericValue> toBeStored = new LinkedList<>();
for (GenericValue orderItem : orderItems) {
String orderItemSeqId = orderItem.getString("orderItemSeqId");
Timestamp shipDate = backOrderedItems.get(orderItemSeqId);
Timestamp cancelDate = cancelItems.get(orderItemSeqId);
Timestamp currentCancelDate = orderItem.getTimestamp("autoCancelDate");
Debug.logInfo("OI: " + orderId + " SEQID: " + orderItemSeqId + " cancelAll: " + cancelAll + " cancelDate: " + cancelDate, module);
if (backOrderedItems.containsKey(orderItemSeqId)) {
orderItem.set("estimatedShipDate", shipDate);
if (currentCancelDate == null) {
if (cancelAll || cancelDate != null) {
if (orderItem.get("dontCancelSetUserLogin") == null && orderItem.get("dontCancelSetDate") == null) {
if (cancelAllTime != null) {
orderItem.set("autoCancelDate", cancelAllTime);
} else {
orderItem.set("autoCancelDate", cancelDate);
}
}
}
// only notify orders which have not already sent the final notice
ordersToNotify.add(orderId);
}
toBeStored.add(orderItem);
}
if (toBeStored.size() > 0) {
try {
delegator.storeAll(toBeStored);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem storing order items", module);
}
}
}
}
}
// send off a notification for each order
for (String orderId : ordersToNotify) {
try {
dispatcher.runAsync("sendOrderBackorderNotification", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
} catch (GenericServiceException e) {
Debug.logError(e, "Problems sending off the notification", module);
continue;
}
}
return ServiceUtil.returnSuccess();
}
use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.
the class SubscriptionServices method runServiceOnSubscriptionExpiry.
public static Map<String, Object> runServiceOnSubscriptionExpiry(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
GenericValue userLogin = (GenericValue) context.get("userLogin");
Map<String, Object> result = new HashMap<>();
Map<String, Object> expiryMap = new HashMap<>();
String gracePeriodOnExpiry = null;
String gracePeriodOnExpiryUomId = null;
String subscriptionId = null;
Timestamp expirationCompletedDate = null;
try {
EntityCondition cond1 = EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, "N");
EntityCondition cond2 = EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, null);
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(cond1, cond2), EntityOperator.OR);
List<GenericValue> subscriptionList = null;
subscriptionList = EntityQuery.use(delegator).from("Subscription").where(cond).queryList();
if (subscriptionList != null) {
for (GenericValue subscription : subscriptionList) {
expirationCompletedDate = subscription.getTimestamp("expirationCompletedDate");
if (expirationCompletedDate == null) {
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(UtilDateTime.nowTimestamp());
// check if the thruDate + grace period (if provided) is earlier than today's date
Calendar endDateSubscription = Calendar.getInstance();
int field = Calendar.MONTH;
String subscriptionResourceId = subscription.getString("subscriptionResourceId");
GenericValue subscriptionResource = null;
subscriptionResource = EntityQuery.use(delegator).from("SubscriptionResource").where("subscriptionResourceId", subscriptionResourceId).queryOne();
subscriptionId = subscription.getString("subscriptionId");
gracePeriodOnExpiry = subscription.getString("gracePeriodOnExpiry");
gracePeriodOnExpiryUomId = subscription.getString("gracePeriodOnExpiryUomId");
String serviceNameOnExpiry = subscriptionResource.getString("serviceNameOnExpiry");
endDateSubscription.setTime(subscription.getTimestamp("thruDate"));
if (gracePeriodOnExpiry != null && gracePeriodOnExpiryUomId != null) {
if ("TF_day".equals(gracePeriodOnExpiryUomId)) {
field = Calendar.DAY_OF_YEAR;
} else if ("TF_wk".equals(gracePeriodOnExpiryUomId)) {
field = Calendar.WEEK_OF_YEAR;
} else if ("TF_mon".equals(gracePeriodOnExpiryUomId)) {
field = Calendar.MONTH;
} else if ("TF_yr".equals(gracePeriodOnExpiryUomId)) {
field = Calendar.YEAR;
} else {
Debug.logWarning("Don't know anything about gracePeriodOnExpiryUomId [" + gracePeriodOnExpiryUomId + "], defaulting to month", module);
}
endDateSubscription.add(field, Integer.parseInt(gracePeriodOnExpiry));
}
if ((currentDate.after(endDateSubscription) || currentDate.equals(endDateSubscription)) && serviceNameOnExpiry != null) {
if (userLogin != null) {
expiryMap.put("userLogin", userLogin);
}
if (subscriptionId != null) {
expiryMap.put("subscriptionId", subscriptionId);
}
result = dispatcher.runSync(serviceNameOnExpiry, expiryMap);
if (ServiceUtil.isSuccess(result)) {
subscription.set("expirationCompletedDate", UtilDateTime.nowTimestamp());
delegator.store(subscription);
Debug.logInfo("Subscription expired successfully for subscription ID:" + subscriptionId, module);
} else if (ServiceUtil.isError(result)) {
result = null;
Debug.logError("Error expiring subscription while processing with subscriptionId: " + subscriptionId, module);
}
if (result != null && subscriptionId != null) {
Debug.logInfo("Service mentioned in serviceNameOnExpiry called with result: " + ServiceUtil.makeSuccessMessage(result, "", "", "", ""), module);
} else if (result == null && subscriptionId != null) {
Debug.logError("Subscription couldn't be expired for subscriptionId: " + subscriptionId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "ProductSubscriptionCouldntBeExpired", UtilMisc.toMap("subscriptionId", subscriptionId), locale));
}
}
}
}
}
} catch (GenericServiceException e) {
Debug.logError("Error while calling service specified in serviceNameOnExpiry", module);
return ServiceUtil.returnError(e.toString());
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return result;
}
use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.
the class SubscriptionServices method processExtendSubscription.
public static Map<String, Object> processExtendSubscription(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
String partyId = (String) context.get("partyId");
String subscriptionResourceId = (String) context.get("subscriptionResourceId");
String inventoryItemId = (String) context.get("inventoryItemId");
String roleTypeId = (String) context.get("useRoleTypeId");
GenericValue userLogin = (GenericValue) context.get("userLogin");
Integer useTime = (Integer) context.get("useTime");
String useTimeUomId = (String) context.get("useTimeUomId");
String alwaysCreateNewRecordStr = (String) context.get("alwaysCreateNewRecord");
Locale locale = (Locale) context.get("locale");
boolean alwaysCreateNewRecord = !"N".equals(alwaysCreateNewRecordStr);
GenericValue lastSubscription = null;
try {
Map<String, String> subscriptionFindMap = UtilMisc.toMap("partyId", partyId, "subscriptionResourceId", subscriptionResourceId);
// if this subscription is attached to something the customer owns, filter by that too
if (UtilValidate.isNotEmpty(inventoryItemId)) {
subscriptionFindMap.put("inventoryItemId", inventoryItemId);
}
List<GenericValue> subscriptionList = EntityQuery.use(delegator).from("Subscription").where(subscriptionFindMap).queryList();
// DEJ20070718 DON'T filter by date, we want to consider all subscriptions: List listFiltered = EntityUtil.filterByDate(subscriptionList, true);
List<GenericValue> listOrdered = EntityUtil.orderBy(subscriptionList, UtilMisc.toList("-fromDate"));
if (listOrdered.size() > 0) {
lastSubscription = listOrdered.get(0);
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.toString());
}
GenericValue newSubscription = null;
if (lastSubscription == null || alwaysCreateNewRecord) {
newSubscription = delegator.makeValue("Subscription");
newSubscription.set("subscriptionResourceId", subscriptionResourceId);
newSubscription.set("partyId", partyId);
newSubscription.set("roleTypeId", roleTypeId);
newSubscription.set("productId", context.get("productId"));
newSubscription.set("orderId", context.get("orderId"));
newSubscription.set("orderItemSeqId", context.get("orderItemSeqId"));
newSubscription.set("automaticExtend", context.get("automaticExtend"));
newSubscription.set("canclAutmExtTimeUomId", context.get("canclAutmExtTimeUomId"));
newSubscription.set("canclAutmExtTime", context.get("canclAutmExtTime"));
} else {
newSubscription = lastSubscription;
}
newSubscription.set("inventoryItemId", inventoryItemId);
Timestamp thruDate = lastSubscription != null ? (Timestamp) lastSubscription.get("thruDate") : null;
// set the fromDate, one way or another
if (thruDate == null) {
// no thruDate? start with NOW
thruDate = nowTimestamp;
newSubscription.set("fromDate", nowTimestamp);
} else {
// month and buy another month, we want that second month to start now and not last year
if (thruDate.before(nowTimestamp)) {
thruDate = nowTimestamp;
}
newSubscription.set("fromDate", thruDate);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(thruDate);
int[] times = UomWorker.uomTimeToCalTime(useTimeUomId);
if (times != null) {
calendar.add(times[0], (useTime.intValue() * times[1]));
} else {
Debug.logWarning("Don't know anything about useTimeUomId [" + useTimeUomId + "], defaulting to month", module);
calendar.add(Calendar.MONTH, useTime);
}
thruDate = new Timestamp(calendar.getTimeInMillis());
newSubscription.set("thruDate", thruDate);
Map<String, Object> result = ServiceUtil.returnSuccess();
try {
if (lastSubscription != null && !alwaysCreateNewRecord) {
Map<String, Object> updateSubscriptionMap = dctx.getModelService("updateSubscription").makeValid(newSubscription, ModelService.IN_PARAM);
updateSubscriptionMap.put("userLogin", EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne());
Map<String, Object> updateSubscriptionResult = dispatcher.runSync("updateSubscription", updateSubscriptionMap);
result.put("subscriptionId", updateSubscriptionMap.get("subscriptionId"));
if (ServiceUtil.isError(updateSubscriptionResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionUpdateError", UtilMisc.toMap("subscriptionId", updateSubscriptionMap.get("subscriptionId")), locale), null, null, updateSubscriptionResult);
}
} else {
Map<String, Object> ensurePartyRoleMap = new HashMap<>();
if (UtilValidate.isNotEmpty(roleTypeId)) {
ensurePartyRoleMap.put("partyId", partyId);
ensurePartyRoleMap.put("roleTypeId", roleTypeId);
ensurePartyRoleMap.put("userLogin", userLogin);
Map<String, Object> createPartyRoleResult = dispatcher.runSync("ensurePartyRole", ensurePartyRoleMap);
if (ServiceUtil.isError(createPartyRoleResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionPartyRoleCreationError", UtilMisc.toMap("subscriptionResourceId", subscriptionResourceId), locale), null, null, createPartyRoleResult);
}
}
Map<String, Object> createSubscriptionMap = dctx.getModelService("createSubscription").makeValid(newSubscription, ModelService.IN_PARAM);
createSubscriptionMap.put("userLogin", EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne());
Map<String, Object> createSubscriptionResult = dispatcher.runSync("createSubscription", createSubscriptionMap);
if (ServiceUtil.isError(createSubscriptionResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSubscriptionCreateError", UtilMisc.toMap("subscriptionResourceId", subscriptionResourceId), locale), null, null, createSubscriptionResult);
}
result.put("subscriptionId", createSubscriptionResult.get("subscriptionId"));
}
} catch (GenericEntityException | GenericServiceException e) {
return ServiceUtil.returnError(e.toString());
}
return result;
}
use of com.ibm.icu.util.Calendar 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();
}
use of com.ibm.icu.util.Calendar 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;
}
Aggregations