use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class OrderServices method validateOrderItemShipGroupAssoc.
/**
* Validate OrderItemShipGroupAssoc quantity
* This service should be called after updateOrderItemShipGroupAssoc
* test if orderItem quantity equals OrderItemShipGroupAssocs quantities
* if not then get the last orderItemShipgroupAssoc estimated shipDate and add quantity to this OrderItemShipGroupAssoc
* @param ctx
* @param context
* @return
* @throws GeneralException
*/
private static String validateOrderItemShipGroupAssoc(Delegator delegator, LocalDispatcher dispatcher, GenericValue orderItem, BigDecimal totalQuantity, GenericValue lastOISGAssoc, GenericValue userLogin, Locale locale) throws GeneralException {
String result = null;
BigDecimal qty = (BigDecimal) orderItem.get("quantity");
if (UtilValidate.isEmpty(qty)) {
qty = BigDecimal.ZERO;
}
BigDecimal cancelQty = (BigDecimal) orderItem.get("cancelQuantity");
if (UtilValidate.isEmpty(cancelQty)) {
cancelQty = BigDecimal.ZERO;
}
BigDecimal orderItemQuantity = qty.subtract(cancelQty);
if (totalQuantity.compareTo(orderItemQuantity) < 0) {
// if quantity in orderItem is bigger than in totalQUantity then added missing quantity in ShipGroupAssoc
BigDecimal adjustementQuantity = orderItemQuantity.subtract(totalQuantity);
BigDecimal lastOISGAssocQuantity = (BigDecimal) lastOISGAssoc.get("quantity");
if (UtilValidate.isEmpty(lastOISGAssocQuantity)) {
lastOISGAssocQuantity = BigDecimal.ZERO;
}
BigDecimal oisgaQty = lastOISGAssocQuantity.add(adjustementQuantity);
lastOISGAssoc.set("quantity", oisgaQty);
lastOISGAssoc.store();
// reserve the inventory
GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", lastOISGAssoc.get("orderId")).queryOne();
if (UtilValidate.isNotEmpty(orderHeader)) {
Map<String, Object> cancelOrderInventoryReservationMap = UtilMisc.toMap("userLogin", userLogin, "locale", locale);
cancelOrderInventoryReservationMap.put("orderId", lastOISGAssoc.get("orderId"));
cancelOrderInventoryReservationMap.put("orderItemSeqId", lastOISGAssoc.get("orderItemSeqId"));
cancelOrderInventoryReservationMap.put("shipGroupSeqId", lastOISGAssoc.get("shipGroupSeqId"));
Map<String, Object> cancelResp = dispatcher.runSync("cancelOrderInventoryReservation", cancelOrderInventoryReservationMap);
if (ServiceUtil.isError(cancelResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(cancelResp));
}
String productStoreId = orderHeader.getString("productStoreId");
String orderTypeId = orderHeader.getString("orderTypeId");
List<String> resErrorMessages = new LinkedList<>();
if (Debug.infoOn()) {
Debug.logInfo("Calling reserve inventory...", module);
}
reserveInventory(delegator, dispatcher, userLogin, locale, UtilMisc.toList(lastOISGAssoc), null, UtilMisc.<String, GenericValue>toMap(lastOISGAssoc.getString("orderItemSeqId"), orderItem), orderTypeId, productStoreId, resErrorMessages);
}
// return warning message
return "Order OISG Assoc Quantity Auto Completed";
}
return result;
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class OrderServices method saveUpdatedCartToOrder.
private static void saveUpdatedCartToOrder(LocalDispatcher dispatcher, Delegator delegator, ShoppingCart cart, Locale locale, GenericValue userLogin, String orderId, Map<String, Object> changeMap, boolean calcTax, boolean deleteItems) throws GeneralException {
// get/set the shipping estimates. If it's a SALES ORDER, then return an error if there are no ship estimates
int shipGroupsSize = cart.getShipGroupSize();
int realShipGroupsSize = (new OrderReadHelper(delegator, orderId)).getOrderItemShipGroups().size();
// If an empty csi has initially been added to cart.shipInfo by ShoppingCart.setItemShipGroupQty() (called indirectly by ShoppingCart.setUserLogin() and then ProductPromoWorker.doPromotions(), etc.)
// shipGroupsSize > realShipGroupsSize are different (+1 for shipGroupsSize), then simply bypass the 1st empty csi!
int origin = realShipGroupsSize == shipGroupsSize ? 0 : 1;
for (int gi = origin; gi < shipGroupsSize; gi++) {
String shipmentMethodTypeId = cart.getShipmentMethodTypeId(gi);
String carrierPartyId = cart.getCarrierPartyId(gi);
Debug.logInfo("Getting ship estimate for group #" + gi + " [" + shipmentMethodTypeId + " / " + carrierPartyId + "]", module);
Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, gi);
if (("SALES_ORDER".equals(cart.getOrderType())) && (ServiceUtil.isError(result))) {
Debug.logError(ServiceUtil.getErrorMessage(result), module);
throw new GeneralException(ServiceUtil.getErrorMessage(result));
}
BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
if (shippingTotal == null) {
shippingTotal = BigDecimal.ZERO;
}
cart.setItemShipGroupEstimate(shippingTotal, gi);
}
// calc the sales tax
CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
if (calcTax) {
try {
coh.calcAndAddTax();
} catch (GeneralException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
}
// get the new orderItems, adjustments, shipping info, payments and order item attributes from the cart
List<Map<String, Object>> modifiedItems = new LinkedList<>();
List<Map<String, Object>> newItems = new LinkedList<>();
List<GenericValue> toStore = new LinkedList<>();
List<GenericValue> toAddList = new ArrayList<>();
toAddList.addAll(cart.makeAllAdjustments());
cart.clearAllPromotionAdjustments();
ProductPromoWorker.doPromotions(cart, dispatcher);
// validate the payment methods
Map<String, Object> validateResp = coh.validatePaymentMethods();
if (ServiceUtil.isError(validateResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(validateResp));
}
// handle OrderHeader fields
String billingAccountId = cart.getBillingAccountId();
if (UtilValidate.isNotEmpty(billingAccountId)) {
try {
GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
orderHeader.set("billingAccountId", billingAccountId);
toStore.add(orderHeader);
} catch (GenericEntityException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
}
toStore.addAll(cart.makeOrderItems(false, true, dispatcher));
toStore.addAll(cart.makeAllAdjustments());
long groupIndex = cart.getShipInfoSize();
if (!deleteItems) {
for (long itr = 1; itr <= groupIndex; itr++) {
List<GenericValue> removeList = new ArrayList<>();
for (GenericValue stored : toStore) {
if ("OrderAdjustment".equals(stored.getEntityName())) {
if (("SHIPPING_CHARGES".equals(stored.get("orderAdjustmentTypeId")) || "SALES_TAX".equals(stored.get("orderAdjustmentTypeId"))) && stored.get("orderId").equals(orderId)) {
// Removing objects from toStore list for old Shipping and Handling Charges Adjustment and Sales Tax Adjustment.
removeList.add(stored);
}
if ("Y".equals(stored.getString("isManual"))) {
// Removing objects from toStore list for Manually added Adjustment.
removeList.add(stored);
}
}
}
toStore.removeAll(removeList);
}
for (GenericValue toAdd : toAddList) {
if ("OrderAdjustment".equals(toAdd.getEntityName())) {
if ("Y".equals(toAdd.getString("isManual")) && (("PROMOTION_ADJUSTMENT".equals(toAdd.get("orderAdjustmentTypeId"))) || ("SHIPPING_CHARGES".equals(toAdd.get("orderAdjustmentTypeId"))) || ("SALES_TAX".equals(toAdd.get("orderAdjustmentTypeId"))))) {
toStore.add(toAdd);
}
}
}
} else {
// add all the cart adjustments
toStore.addAll(toAddList);
}
// Creating objects for New Shipping and Handling Charges Adjustment and Sales Tax Adjustment
toStore.addAll(cart.makeAllShipGroupInfos());
toStore.addAll(cart.makeAllOrderPaymentInfos(dispatcher));
toStore.addAll(cart.makeAllOrderItemAttributes(orderId, ShoppingCart.FILLED_ONLY));
List<GenericValue> toRemove = new LinkedList<>();
if (deleteItems) {
// flag to delete existing order items and adjustments
try {
toRemove.addAll(EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderItemContactMech").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderItemPriceInfo").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderItemAttribute").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderItemBilling").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderItemRole").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderItemChange").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderAdjustment").where("orderId", orderId).queryList());
toRemove.addAll(EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId).queryList());
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
} else {
// get the empty order item atrributes from the cart and remove them
toRemove.addAll(cart.makeAllOrderItemAttributes(orderId, ShoppingCart.EMPTY_ONLY));
}
// get the promo uses and codes
for (String promoCodeEntered : cart.getProductPromoCodesEntered()) {
GenericValue orderProductPromoCode = delegator.makeValue("OrderProductPromoCode");
orderProductPromoCode.set("orderId", orderId);
orderProductPromoCode.set("productPromoCodeId", promoCodeEntered);
toStore.add(orderProductPromoCode);
}
for (GenericValue promoUse : cart.makeProductPromoUses()) {
promoUse.set("orderId", orderId);
toStore.add(promoUse);
}
List<GenericValue> existingPromoCodes = null;
List<GenericValue> existingPromoUses = null;
try {
existingPromoCodes = EntityQuery.use(delegator).from("OrderProductPromoCode").where("orderId", orderId).queryList();
existingPromoUses = EntityQuery.use(delegator).from("ProductPromoUse").where("orderId", orderId).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
toRemove.addAll(existingPromoCodes);
toRemove.addAll(existingPromoUses);
// set the orderId & other information on all new value objects
// this list will contain the ids of all the ship groups for drop shipments (no reservations)
List<String> dropShipGroupIds = new LinkedList<>();
for (GenericValue valueObj : toStore) {
valueObj.set("orderId", orderId);
if ("OrderItemShipGroup".equals(valueObj.getEntityName())) {
// ship group
if (valueObj.get("carrierRoleTypeId") == null) {
valueObj.set("carrierRoleTypeId", "CARRIER");
}
if (UtilValidate.isNotEmpty(valueObj.get("supplierPartyId"))) {
dropShipGroupIds.add(valueObj.getString("shipGroupSeqId"));
}
} else if ("OrderAdjustment".equals(valueObj.getEntityName())) {
// shipping / tax adjustment(s)
if (UtilValidate.isEmpty(valueObj.get("orderItemSeqId"))) {
valueObj.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
}
// in order to avoid duplicate adjustments don't set orderAdjustmentId (which is the pk) if there is already one
if (UtilValidate.isEmpty(valueObj.getString("orderAdjustmentId"))) {
valueObj.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
}
valueObj.set("createdDate", UtilDateTime.nowTimestamp());
valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
} else if ("OrderPaymentPreference".equals(valueObj.getEntityName())) {
if (valueObj.get("orderPaymentPreferenceId") == null) {
valueObj.set("orderPaymentPreferenceId", delegator.getNextSeqId("OrderPaymentPreference"));
valueObj.set("createdDate", UtilDateTime.nowTimestamp());
valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
}
if (valueObj.get("statusId") == null) {
valueObj.set("statusId", "PAYMENT_NOT_RECEIVED");
}
} else if ("OrderItem".equals(valueObj.getEntityName()) && !deleteItems) {
// ignore promotion items. They are added/canceled automatically
if ("Y".equals(valueObj.getString("isPromo"))) {
// Fetching the new promo items and adding it to list so that we can create OrderStatus record for that items.
Map<String, Object> promoItem = new HashMap<>();
promoItem.put("orderId", valueObj.getString("orderId"));
promoItem.put("orderItemSeqId", valueObj.getString("orderItemSeqId"));
promoItem.put("quantity", valueObj.getBigDecimal("quantity"));
newItems.add(promoItem);
continue;
}
GenericValue oldOrderItem = null;
try {
oldOrderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", valueObj.getString("orderId"), "orderItemSeqId", valueObj.getString("orderItemSeqId")).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
if (oldOrderItem != null) {
// Existing order item found. Check for modifications and store if any
String oldItemDescription = oldOrderItem.getString("itemDescription") != null ? oldOrderItem.getString("itemDescription") : "";
BigDecimal oldQuantity = oldOrderItem.getBigDecimal("quantity") != null ? oldOrderItem.getBigDecimal("quantity") : BigDecimal.ZERO;
BigDecimal oldUnitPrice = oldOrderItem.getBigDecimal("unitPrice") != null ? oldOrderItem.getBigDecimal("unitPrice") : BigDecimal.ZERO;
String oldItemComment = oldOrderItem.getString("comments") != null ? oldOrderItem.getString("comments") : "";
boolean changeFound = false;
Map<String, Object> modifiedItem = new HashMap<>();
if (!oldItemDescription.equals(valueObj.getString("itemDescription"))) {
modifiedItem.put("itemDescription", oldItemDescription);
changeFound = true;
}
if (!oldItemComment.equals(valueObj.getString("comments"))) {
modifiedItem.put("changeComments", valueObj.getString("comments"));
changeFound = true;
}
BigDecimal quantityDif = valueObj.getBigDecimal("quantity").subtract(oldQuantity);
BigDecimal unitPriceDif = valueObj.getBigDecimal("unitPrice").subtract(oldUnitPrice);
if (quantityDif.compareTo(BigDecimal.ZERO) != 0) {
modifiedItem.put("quantity", quantityDif);
changeFound = true;
}
if (unitPriceDif.compareTo(BigDecimal.ZERO) != 0) {
modifiedItem.put("unitPrice", unitPriceDif);
changeFound = true;
}
if (changeFound) {
// found changes to store
Map<String, String> itemReasonMap = UtilGenerics.checkMap(changeMap.get("itemReasonMap"));
if (UtilValidate.isNotEmpty(itemReasonMap)) {
String changeReasonId = itemReasonMap.get(valueObj.getString("orderItemSeqId"));
modifiedItem.put("reasonEnumId", changeReasonId);
}
modifiedItem.put("orderId", valueObj.getString("orderId"));
modifiedItem.put("orderItemSeqId", valueObj.getString("orderItemSeqId"));
modifiedItem.put("changeTypeEnumId", "ODR_ITM_UPDATE");
modifiedItems.add(modifiedItem);
}
} else {
// this is a new item appended to the order
Map<String, String> itemReasonMap = UtilGenerics.checkMap(changeMap.get("itemReasonMap"));
Map<String, String> itemCommentMap = UtilGenerics.checkMap(changeMap.get("itemCommentMap"));
Map<String, Object> appendedItem = new HashMap<>();
if (UtilValidate.isNotEmpty(itemReasonMap)) {
String changeReasonId = itemReasonMap.get("reasonEnumId");
appendedItem.put("reasonEnumId", changeReasonId);
}
if (UtilValidate.isNotEmpty(itemCommentMap)) {
String changeComments = itemCommentMap.get("changeComments");
appendedItem.put("changeComments", changeComments);
}
appendedItem.put("orderId", valueObj.getString("orderId"));
appendedItem.put("orderItemSeqId", valueObj.getString("orderItemSeqId"));
appendedItem.put("quantity", valueObj.getBigDecimal("quantity"));
appendedItem.put("changeTypeEnumId", "ODR_ITM_APPEND");
modifiedItems.add(appendedItem);
newItems.add(appendedItem);
}
}
}
if (Debug.verboseOn()) {
Debug.logVerbose("To Store Contains: " + toStore, module);
}
// remove any order item attributes that were set to empty
try {
delegator.removeAll(toRemove);
} catch (GenericEntityException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
// store the new items/adjustments/order item attributes
try {
delegator.storeAll(toStore);
} catch (GenericEntityException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
// store the OrderItemChange
if (UtilValidate.isNotEmpty(modifiedItems)) {
for (Map<String, Object> modifiendItem : modifiedItems) {
Map<String, Object> serviceCtx = new HashMap<>();
serviceCtx.put("orderId", modifiendItem.get("orderId"));
serviceCtx.put("orderItemSeqId", modifiendItem.get("orderItemSeqId"));
serviceCtx.put("itemDescription", modifiendItem.get("itemDescription"));
serviceCtx.put("quantity", modifiendItem.get("quantity"));
serviceCtx.put("unitPrice", modifiendItem.get("unitPrice"));
serviceCtx.put("changeTypeEnumId", modifiendItem.get("changeTypeEnumId"));
serviceCtx.put("reasonEnumId", modifiendItem.get("reasonEnumId"));
serviceCtx.put("changeComments", modifiendItem.get("changeComments"));
serviceCtx.put("userLogin", userLogin);
Map<String, Object> resp = null;
try {
resp = dispatcher.runSync("createOrderItemChange", serviceCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
if (ServiceUtil.isError(resp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(resp));
}
}
}
// To create record of OrderStatus entity
if (UtilValidate.isNotEmpty(newItems)) {
for (Map<String, Object> newItem : newItems) {
String itemStatusId = delegator.getNextSeqId("OrderStatus");
GenericValue itemStatus = delegator.makeValue("OrderStatus", UtilMisc.toMap("orderStatusId", itemStatusId));
itemStatus.put("statusId", "ITEM_CREATED");
itemStatus.put("orderId", newItem.get("orderId"));
itemStatus.put("orderItemSeqId", newItem.get("orderItemSeqId"));
itemStatus.put("statusDatetime", UtilDateTime.nowTimestamp());
itemStatus.set("statusUserLogin", userLogin.get("userLoginId"));
delegator.create(itemStatus);
}
}
// make the order item object map & the ship group assoc list
List<GenericValue> orderItemShipGroupAssoc = new LinkedList<>();
Map<String, GenericValue> itemValuesBySeqId = new HashMap<>();
for (GenericValue v : toStore) {
if ("OrderItem".equals(v.getEntityName())) {
itemValuesBySeqId.put(v.getString("orderItemSeqId"), v);
} else if ("OrderItemShipGroupAssoc".equals(v.getEntityName())) {
orderItemShipGroupAssoc.add(v);
}
}
// reserve the inventory
String productStoreId = cart.getProductStoreId();
String orderTypeId = cart.getOrderType();
List<String> resErrorMessages = new LinkedList<>();
try {
Debug.logInfo("Calling reserve inventory...", module);
reserveInventory(delegator, dispatcher, userLogin, locale, orderItemShipGroupAssoc, dropShipGroupIds, itemValuesBySeqId, orderTypeId, productStoreId, resErrorMessages);
} catch (GeneralException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
if (resErrorMessages.size() > 0) {
throw new GeneralException(ServiceUtil.getErrorMessage(ServiceUtil.returnError(resErrorMessages)));
}
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class OrderServices method processOrderPayments.
public static Map<String, Object> processOrderPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String orderId = (String) context.get("orderId");
Locale locale = (Locale) context.get("locale");
OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
String productStoreId = orh.getProductStoreId();
// check if order was already cancelled / rejected
GenericValue orderHeader = orh.getOrderHeader();
String orderStatus = orderHeader.getString("statusId");
if ("ORDER_CANCELLED".equals(orderStatus) || "ORDER_REJECTED".equals(orderStatus)) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "OrderProcessOrderPaymentsStatusInvalid", locale) + orderStatus);
}
// process the payments
if (!"PURCHASE_ORDER".equals(orh.getOrderTypeId())) {
GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
Map<String, Object> paymentResp = null;
try {
Debug.logInfo("Calling process payments...", module);
paymentResp = CheckOutHelper.processPayment(orderId, orh.getOrderGrandTotal(), orh.getCurrency(), productStore, userLogin, false, false, dispatcher, delegator);
} catch (GeneralException | GeneralRuntimeException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (ServiceUtil.isError(paymentResp)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderProcessOrderPayments", locale), null, null, paymentResp);
}
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.base.util.GeneralException 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));
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class OrderServices method updateShipGroupShipInfo.
/**
* This service runs when you update shipping method of Order from order view page.
*/
public static Map<String, Object> updateShipGroupShipInfo(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");
String orderId = (String) context.get("orderId");
String shipGroupSeqId = (String) context.get("shipGroupSeqId");
String contactMechId = (String) context.get("contactMechId");
String oldContactMechId = (String) context.get("oldContactMechId");
String shipmentMethod = (String) context.get("shipmentMethod");
// load cart from order to update new shipping method or address
ShoppingCart shoppingCart = null;
try {
shoppingCart = loadCartForUpdate(dispatcher, delegator, userLogin, orderId);
} catch (GeneralException e) {
Debug.logError(e, module);
}
String message = null;
if (UtilValidate.isNotEmpty(shipGroupSeqId)) {
OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
List<GenericValue> shippingMethods = null;
String shipmentMethodTypeId = null;
String carrierPartyId = null;
// get shipment method from OrderItemShipGroup, if not available in parameters
if (UtilValidate.isNotEmpty(shipmentMethod)) {
String[] arr = shipmentMethod.split("@");
shipmentMethodTypeId = arr[0];
carrierPartyId = arr[1];
} else {
GenericValue orderItemshipGroup = orh.getOrderItemShipGroup(shipGroupSeqId);
shipmentMethodTypeId = orderItemshipGroup.getString("shipmentMethodTypeId");
carrierPartyId = orderItemshipGroup.getString("carrierPartyId");
}
int groupIdx = Integer.parseInt(shipGroupSeqId);
/* check whether new selected contact address is same as old contact.
If contact address is different, get applicable ship methods for changed contact */
if (UtilValidate.isNotEmpty(oldContactMechId) && oldContactMechId.equals(contactMechId)) {
shoppingCart.setShipmentMethodTypeId(groupIdx - 1, shipmentMethodTypeId);
shoppingCart.setCarrierPartyId(groupIdx - 1, carrierPartyId);
} else {
Map<String, BigDecimal> shippableItemFeatures = orh.getFeatureIdQtyMap(shipGroupSeqId);
BigDecimal shippableTotal = orh.getShippableTotal(shipGroupSeqId);
BigDecimal shippableWeight = orh.getShippableWeight(shipGroupSeqId);
List<BigDecimal> shippableItemSizes = orh.getShippableSizes(shipGroupSeqId);
GenericValue shippingAddress = orh.getShippingAddress(shipGroupSeqId);
shippingMethods = ProductStoreWorker.getAvailableStoreShippingMethods(delegator, orh.getProductStoreId(), shippingAddress, shippableItemSizes, shippableItemFeatures, shippableWeight, shippableTotal);
boolean isShippingMethodAvailable = false;
// search shipping method for ship group is applicable to new address or not.
for (GenericValue shippingMethod : shippingMethods) {
isShippingMethodAvailable = shippingMethod.getString("partyId").equals(carrierPartyId) && shippingMethod.getString("shipmentMethodTypeId").equals(shipmentMethodTypeId);
if (isShippingMethodAvailable) {
shoppingCart.setShipmentMethodTypeId(groupIdx - 1, shipmentMethodTypeId);
shoppingCart.setCarrierPartyId(groupIdx - 1, carrierPartyId);
break;
}
}
// set first shipping method from list, if shipping method for ship group is not applicable to new ship address.
if (!isShippingMethodAvailable) {
shoppingCart.setShipmentMethodTypeId(groupIdx - 1, shippingMethods.get(0).getString("shipmentMethodTypeId"));
shoppingCart.setCarrierPartyId(groupIdx - 1, shippingMethods.get(0).getString("carrierPartyId"));
String newShipMethTypeDesc = null;
String shipMethTypeDesc = null;
try {
shipMethTypeDesc = EntityQuery.use(delegator).from("ShipmentMethodType").where("shipmentMethodTypeId", shipmentMethodTypeId).queryOne().getString("description");
newShipMethTypeDesc = EntityQuery.use(delegator).from("ShipmentMethodType").where("shipmentMethodTypeId", shippingMethods.get(0).getString("shipmentMethodTypeId")).queryOne().getString("description");
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
// message to notify user for not applicability of shipping method
message = "Shipping Method " + carrierPartyId + " " + shipMethTypeDesc + " is not applicable to shipping address. " + shippingMethods.get(0).getString("carrierPartyId") + " " + newShipMethTypeDesc + " has been set for shipping address.";
}
shoppingCart.setShippingContactMechId(groupIdx - 1, contactMechId);
}
}
// save cart after updating shipping method and shipping address.
Map<String, Object> changeMap = new HashMap<>();
try {
saveUpdatedCartToOrder(dispatcher, delegator, shoppingCart, locale, userLogin, orderId, changeMap, true, false);
} catch (GeneralException e) {
Debug.logError(e, module);
}
if (UtilValidate.isNotEmpty(message)) {
return ServiceUtil.returnSuccess(message);
}
return ServiceUtil.returnSuccess();
}
Aggregations