Search in sources :

Example 26 with Calendar

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

the class TechDataServices method startNextDay.

/**
 * Used to move in a TechDataCalenda, produce the Timestamp for the begining of the next day available and its associated capacity.
 * If the dateFrom (param in) is not  in an available TechDataCalendar period, the return value is the next day available
 *
 * @param techDataCalendar        The TechDataCalendar cover
 * @param dateFrom                        the date
 * @return a map with Timestamp dateTo, Double nextCapacity
 */
public static Map<String, Object> startNextDay(GenericValue techDataCalendar, Timestamp dateFrom) {
    Map<String, Object> result = new HashMap<String, Object>();
    Timestamp dateTo = null;
    GenericValue techDataCalendarWeek = null;
    // TODO read TechDataCalendarExcWeek to manage execption week (maybe it's needed to refactor the entity definition
    try {
        techDataCalendarWeek = techDataCalendar.getRelatedOne("TechDataCalendarWeek", true);
    } catch (GenericEntityException e) {
        Debug.logError("Pb reading Calendar Week associated with calendar" + e.getMessage(), module);
        return ServiceUtil.returnError("Pb reading Calendar Week associated with calendar");
    }
    // TODO read TechDataCalendarExcDay to manage execption day
    Calendar cDateTrav = Calendar.getInstance();
    cDateTrav.setTime(dateFrom);
    Map<String, Object> position = dayStartCapacityAvailable(techDataCalendarWeek, cDateTrav.get(Calendar.DAY_OF_WEEK));
    Time startTime = (Time) position.get("startTime");
    int moveDay = ((Integer) position.get("moveDay")).intValue();
    dateTo = (moveDay == 0) ? dateFrom : UtilDateTime.getDayStart(dateFrom, moveDay);
    Timestamp startAvailablePeriod = new Timestamp(UtilDateTime.getDayStart(dateTo).getTime() + startTime.getTime() + cDateTrav.get(Calendar.ZONE_OFFSET) + cDateTrav.get(Calendar.DST_OFFSET));
    if (dateTo.before(startAvailablePeriod)) {
        dateTo = startAvailablePeriod;
    } else {
        dateTo = UtilDateTime.getNextDayStart(dateTo);
        cDateTrav.setTime(dateTo);
        position = dayStartCapacityAvailable(techDataCalendarWeek, cDateTrav.get(Calendar.DAY_OF_WEEK));
        startTime = (Time) position.get("startTime");
        moveDay = ((Integer) position.get("moveDay")).intValue();
        if (moveDay != 0)
            dateTo = UtilDateTime.getDayStart(dateTo, moveDay);
        dateTo.setTime(dateTo.getTime() + startTime.getTime() + cDateTrav.get(Calendar.ZONE_OFFSET) + cDateTrav.get(Calendar.DST_OFFSET));
    }
    result.put("dateTo", dateTo);
    result.put("nextCapacity", position.get("capacity"));
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Calendar(com.ibm.icu.util.Calendar) Time(java.sql.Time) UtilDateTime(org.apache.ofbiz.base.util.UtilDateTime) Timestamp(java.sql.Timestamp)

Example 27 with Calendar

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

the class TechDataServices method capacityRemainingBackward.

/**
 * Used to request the remaining capacity available for dateFrom in a TechDataCalenda,
 * If the dateFrom (param in) is not  in an available TechDataCalendar period, the return value is zero.
 *
 * @param techDataCalendar        The TechDataCalendar cover
 * @param dateFrom                        the date
 * @return  long capacityRemaining
 */
public static long capacityRemainingBackward(GenericValue techDataCalendar, Timestamp dateFrom) {
    GenericValue techDataCalendarWeek = null;
    // TODO read TechDataCalendarExcWeek to manage exception week (maybe it's needed to refactor the entity definition
    try {
        techDataCalendarWeek = techDataCalendar.getRelatedOne("TechDataCalendarWeek", true);
    } catch (GenericEntityException e) {
        Debug.logError("Pb reading Calendar Week associated with calendar" + e.getMessage(), module);
        return 0;
    }
    // TODO read TechDataCalendarExcDay to manage execption day
    Calendar cDateTrav = Calendar.getInstance();
    cDateTrav.setTime(dateFrom);
    Map<String, Object> position = dayEndCapacityAvailable(techDataCalendarWeek, cDateTrav.get(Calendar.DAY_OF_WEEK));
    int moveDay = ((Integer) position.get("moveDay")).intValue();
    if (moveDay != 0)
        return 0;
    Time startTime = (Time) position.get("startTime");
    Double capacity = (Double) position.get("capacity");
    Timestamp startAvailablePeriod = new Timestamp(UtilDateTime.getDayStart(dateFrom).getTime() + startTime.getTime() + cDateTrav.get(Calendar.ZONE_OFFSET) + cDateTrav.get(Calendar.DST_OFFSET));
    if (dateFrom.before(startAvailablePeriod))
        return 0;
    Timestamp endAvailablePeriod = new Timestamp(startAvailablePeriod.getTime() + capacity.longValue());
    if (dateFrom.after(endAvailablePeriod))
        return 0;
    return dateFrom.getTime() - startAvailablePeriod.getTime();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Calendar(com.ibm.icu.util.Calendar) Time(java.sql.Time) UtilDateTime(org.apache.ofbiz.base.util.UtilDateTime) Timestamp(java.sql.Timestamp)

Example 28 with Calendar

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

the class OrderServices method cancelFlaggedSalesOrders.

public static Map<String, Object> cancelFlaggedSalesOrders(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    List<GenericValue> ordersToCheck = null;
    // create the query expressions
    List<EntityCondition> exprs = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"));
    // get the orders
    try {
        ordersToCheck = EntityQuery.use(delegator).from("OrderHeader").where(exprs).orderBy("orderDate").queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting order headers", module);
    }
    if (UtilValidate.isEmpty(ordersToCheck)) {
        Debug.logInfo("No orders to check, finished", module);
        return ServiceUtil.returnSuccess();
    }
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    for (GenericValue orderHeader : ordersToCheck) {
        String orderId = orderHeader.getString("orderId");
        String orderStatus = orderHeader.getString("statusId");
        if ("ORDER_CREATED".equals(orderStatus)) {
            // first check for un-paid orders
            Timestamp orderDate = orderHeader.getTimestamp("entryDate");
            // need the store for the order
            GenericValue productStore = null;
            try {
                productStore = orderHeader.getRelatedOne("ProductStore", false);
            } catch (GenericEntityException e) {
                Debug.logError(e, "Unable to get ProductStore from OrderHeader", module);
            }
            // default days to cancel
            int daysTillCancel = 30;
            // get the value from the store
            if (productStore != null && productStore.get("daysToCancelNonPay") != null) {
                daysTillCancel = productStore.getLong("daysToCancelNonPay").intValue();
            }
            if (daysTillCancel > 0) {
                // 0 days means do not auto-cancel
                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(orderDate.getTime());
                cal.add(Calendar.DAY_OF_YEAR, daysTillCancel);
                Date cancelDate = cal.getTime();
                Date nowDate = new Date();
                if (cancelDate.equals(nowDate) || nowDate.after(cancelDate)) {
                    // cancel the order item(s)
                    Map<String, Object> svcCtx = UtilMisc.<String, Object>toMap("orderId", orderId, "statusId", "ITEM_CANCELLED", "userLogin", userLogin);
                    try {
                        // TODO: looks like result is ignored here, but we should be looking for errors
                        Map<String, Object> serviceResult = dispatcher.runSync("changeOrderItemStatus", svcCtx);
                        if (ServiceUtil.isError(serviceResult)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                        }
                    } catch (GenericServiceException e) {
                        Debug.logError(e, "Problem calling change item status service : " + svcCtx, module);
                    }
                }
            }
        } else {
            // check for auto-cancel items
            List<EntityCondition> itemsExprs = new ArrayList<>();
            // create the query expressions
            itemsExprs.add(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
            itemsExprs.add(EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_CREATED"), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_APPROVED")), EntityOperator.OR));
            itemsExprs.add(EntityCondition.makeCondition("dontCancelSetUserLogin", EntityOperator.EQUALS, GenericEntity.NULL_FIELD));
            itemsExprs.add(EntityCondition.makeCondition("dontCancelSetDate", EntityOperator.EQUALS, GenericEntity.NULL_FIELD));
            itemsExprs.add(EntityCondition.makeCondition("autoCancelDate", EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD));
            List<GenericValue> orderItems = null;
            try {
                orderItems = EntityQuery.use(delegator).from("OrderItem").where(itemsExprs).queryList();
            } catch (GenericEntityException e) {
                Debug.logError(e, "Problem getting order item records", module);
            }
            if (UtilValidate.isNotEmpty(orderItems)) {
                for (GenericValue orderItem : orderItems) {
                    String orderItemSeqId = orderItem.getString("orderItemSeqId");
                    Timestamp autoCancelDate = orderItem.getTimestamp("autoCancelDate");
                    if (autoCancelDate != null) {
                        if (nowTimestamp.equals(autoCancelDate) || nowTimestamp.after(autoCancelDate)) {
                            // cancel the order item
                            Map<String, Object> svcCtx = UtilMisc.<String, Object>toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "statusId", "ITEM_CANCELLED", "userLogin", userLogin);
                            try {
                                // TODO: check service result for an error return
                                Map<String, Object> serviceResult = dispatcher.runSync("changeOrderItemStatus", svcCtx);
                                if (ServiceUtil.isError(serviceResult)) {
                                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                                }
                            } catch (GenericServiceException e) {
                                Debug.logError(e, "Problem calling change item status service : " + svcCtx, module);
                            }
                        }
                    }
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) Date(java.util.Date) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 29 with Calendar

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

the class OrderServices method runSubscriptionAutoReorders.

public static Map<String, Object> runSubscriptionAutoReorders(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    int count = 0;
    Map<String, Object> result = null;
    boolean beganTransaction = false;
    List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition("orderId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("productId", EntityOperator.NOT_EQUAL, null));
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, "[Delegator] Could not begin transaction: " + e1.toString(), module);
    }
    try (EntityListIterator eli = EntityQuery.use(delegator).from("Subscription").where(exprs).queryIterator()) {
        if (eli != null) {
            GenericValue subscription;
            while (((subscription = eli.next()) != null)) {
                Calendar endDate = Calendar.getInstance();
                endDate.setTime(UtilDateTime.nowTimestamp());
                // Check if today date + cancel period (if provided) is earlier than the thrudate
                int field = Calendar.MONTH;
                if (subscription.get("canclAutmExtTime") != null && subscription.get("canclAutmExtTimeUomId") != null) {
                    if ("TF_day".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.DAY_OF_YEAR;
                    } else if ("TF_wk".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.WEEK_OF_YEAR;
                    } else if ("TF_mon".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.MONTH;
                    } else if ("TF_yr".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.YEAR;
                    } else {
                        Debug.logWarning("Don't know anything about canclAutmExtTimeUomId [" + subscription.getString("canclAutmExtTimeUomId") + "], defaulting to month", module);
                    }
                    endDate.add(field, Integer.parseInt(subscription.getString("canclAutmExtTime")));
                }
                Calendar endDateSubscription = Calendar.getInstance();
                endDateSubscription.setTime(subscription.getTimestamp("thruDate"));
                if (endDate.before(endDateSubscription)) {
                    // nor expired yet.....
                    continue;
                }
                result = dispatcher.runSync("loadCartFromOrder", UtilMisc.toMap("orderId", subscription.get("orderId"), "userLogin", userLogin));
                if (ServiceUtil.isError(result)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                }
                ShoppingCart cart = (ShoppingCart) result.get("shoppingCart");
                // remove former orderId from cart (would cause duplicate entry).
                // orderId is set by order-creation services (including store-specific prefixes, e.g.)
                cart.setOrderId(null);
                // only keep the orderitem with the related product.
                List<ShoppingCartItem> cartItems = cart.items();
                for (ShoppingCartItem shoppingCartItem : cartItems) {
                    if (!subscription.get("productId").equals(shoppingCartItem.getProductId())) {
                        cart.removeCartItem(shoppingCartItem, dispatcher);
                    }
                }
                CheckOutHelper helper = new CheckOutHelper(dispatcher, delegator, cart);
                // store the order
                Map<String, Object> createResp = helper.createOrder(userLogin);
                if (createResp != null && ServiceUtil.isError(createResp)) {
                    Debug.logError("Cannot create order for shopping list - " + subscription, module);
                } else {
                    String orderId = (String) createResp.get("orderId");
                    // authorize the payments
                    Map<String, Object> payRes = null;
                    try {
                        payRes = helper.processPayment(ProductStoreWorker.getProductStore(cart.getProductStoreId(), delegator), userLogin);
                    } catch (GeneralException e) {
                        Debug.logError(e, module);
                    }
                    if (payRes != null && ServiceUtil.isError(payRes)) {
                        Debug.logError("Payment processing problems with shopping list - " + subscription, module);
                    }
                    // remove the automatic extension flag
                    subscription.put("automaticExtend", "N");
                    subscription.store();
                    // send notification
                    if (orderId != null) {
                        dispatcher.runAsync("sendOrderPayRetryNotification", UtilMisc.toMap("orderId", orderId));
                    }
                    count++;
                }
            }
        }
    } catch (GenericServiceException e) {
        Debug.logError("Could call service to create cart", module);
        return ServiceUtil.returnError(e.toString());
    } catch (CartItemModifyException e) {
        Debug.logError("Could not modify cart: " + e.toString(), module);
        return ServiceUtil.returnError(e.toString());
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error creating subscription auto-reorders", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "[Delegator] Could not rollback transaction: " + e2.toString(), module);
        }
        Debug.logError(e, "Error while creating new shopping list based automatic reorder" + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderShoppingListCreationError", UtilMisc.toMap("errorString", e.toString()), locale));
    } finally {
        try {
            // only commit the transaction if we started one... this will throw an exception if it fails
            TransactionUtil.commit(beganTransaction);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Could not commit transaction for creating new shopping list based automatic reorder", module);
        }
    }
    return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "OrderRunSubscriptionAutoReorders", UtilMisc.toMap("count", count), locale));
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) Calendar(com.ibm.icu.util.Calendar) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 30 with Calendar

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

the class OrderReturnServices method autoCancelReplacementOrders.

// cancel replacement order if return not received within 30 days and send notification
public static Map<String, Object> autoCancelReplacementOrders(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    List<GenericValue> returnHeaders = null;
    try {
        returnHeaders = EntityQuery.use(delegator).from("ReturnHeader").where("statusId", "RETURN_ACCEPTED", "returnHeaderTypeId", "CUSTOMER_RETURN").orderBy("entryDate").queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting Return headers", module);
    }
    for (GenericValue returnHeader : returnHeaders) {
        String returnId = returnHeader.getString("returnId");
        Timestamp entryDate = returnHeader.getTimestamp("entryDate");
        String daysTillCancelStr = EntityUtilProperties.getPropertyValue("order", "daysTillCancelReplacementOrder", "30", delegator);
        int daysTillCancel = 0;
        try {
            daysTillCancel = Integer.parseInt(daysTillCancelStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to get daysTillCancel", module);
        }
        if (daysTillCancel > 0) {
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(entryDate.getTime());
            cal.add(Calendar.DAY_OF_YEAR, daysTillCancel);
            Date cancelDate = cal.getTime();
            Date nowDate = new Date();
            if (cancelDate.equals(nowDate) || nowDate.after(cancelDate)) {
                try {
                    List<GenericValue> returnItems = EntityQuery.use(delegator).from("ReturnItem").where("returnId", returnId, "returnTypeId", "RTN_WAIT_REPLACE_RES").orderBy("createdStamp").queryList();
                    for (GenericValue returnItem : returnItems) {
                        GenericValue returnItemResponse = returnItem.getRelatedOne("ReturnItemResponse", false);
                        if (returnItemResponse != null) {
                            String replacementOrderId = returnItemResponse.getString("replacementOrderId");
                            Map<String, Object> svcCtx = UtilMisc.<String, Object>toMap("orderId", replacementOrderId, "userLogin", userLogin);
                            GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", replacementOrderId).queryOne();
                            if ("ORDER_HOLD".equals(orderHeader.getString("statusId"))) {
                                try {
                                    Map<String, Object> result = dispatcher.runSync("cancelOrderItem", svcCtx);
                                    if (ServiceUtil.isError(result)) {
                                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                                    }
                                } catch (GenericServiceException e) {
                                    Debug.logError(e, "Problem calling service cancelOrderItem: " + svcCtx, module);
                                }
                            }
                        }
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) Date(java.util.Date) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

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