String carrierPartyId = cart.getCarrierPartyId(gi);
Debug.logInfo("Getting ship estimate for group #" + gi + " [" + shipmentMethodTypeId + " / " + carrierPartyId + "]", module);
Map 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);
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 atrributes from the cart
List<Map> modifiedItems = FastList.newInstance();
List toStore = new LinkedList();
List<GenericValue> toAddList = new ArrayList<GenericValue>();
toAddList.addAll(cart.makeAllAdjustments());
cart.clearAllPromotionAdjustments();
ProductPromoWorker.doPromotions(cart, dispatcher);
// validate the payment methods
Map validateResp = coh.validatePaymentMethods();
if (ServiceUtil.isError(validateResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(validateResp));
}
toStore.addAll(cart.makeOrderItems());
toStore.addAll(cart.makeAllAdjustments());
String shipGroupSeqId = null;
long groupIndex = cart.getShipInfoSize();
List orderAdjustments = new ArrayList();
for (long itr = 1; itr <= groupIndex; itr++) {
shipGroupSeqId = UtilFormatOut.formatPaddedNumber(itr, 5);
List<GenericValue> removeList = new ArrayList<GenericValue>();
for (GenericValue stored: (List<GenericValue>)toStore) {
if ("OrderAdjustment".equals(stored.getEntityName())) {
if (("SHIPPING_CHARGES".equals(stored.get("orderAdjustmentTypeId")) ||
"SALES_TAX".equals(stored.get("orderAdjustmentTypeId"))) &&
stored.get("orderId").equals(orderId) &&
stored.get("shipGroupSeqId").equals(shipGroupSeqId)) {
// Removing objects from toStore list for old Shipping and Handling Charges Adjustment and Sales Tax Adjustment.
removeList.add(stored);
}
if (stored.get("comments") != null && ((String)stored.get("comments")).startsWith("Added manually by")) {
// Removing objects from toStore list for Manually added Adjustment.
removeList.add(stored);
}
}
}
toStore.removeAll(removeList);
}
for (GenericValue toAdd: (List<GenericValue>)toAddList) {
if ("OrderAdjustment".equals(toAdd.getEntityName())) {
if (toAdd.get("comments") != null && ((String)toAdd.get("comments")).startsWith("Added manually by") && (("PROMOTION_ADJUSTMENT".equals(toAdd.get("orderAdjustmentTypeId"))) ||
("SHIPPING_CHARGES".equals(toAdd.get("orderAdjustmentTypeId"))) || ("SALES_TAX".equals(toAdd.get("orderAdjustmentTypeId"))))) {
toStore.add(toAdd);
}
}
}
// 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));
// get the empty order item atrributes from the cart and remove them
List toRemove = FastList.newInstance();
toRemove.addAll(cart.makeAllOrderItemAttributes(orderId, ShoppingCart.EMPTY_ONLY));
// set the orderId & other information on all new value objects
List dropShipGroupIds = FastList.newInstance(); // this list will contain the ids of all the ship groups for drop shipments (no reservations)
Iterator tsi = toStore.iterator();
while (tsi.hasNext()) {
GenericValue valueObj = (GenericValue) tsi.next();
valueObj.set("orderId", orderId);
if ("OrderItemShipGroup".equals(valueObj.getEntityName())) {
// ship group
if (valueObj.get("carrierRoleTypeId") == null) {
valueObj.set("carrierRoleTypeId", "CARRIER");
}
if (!UtilValidate.isEmpty(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);
}
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())) {
// ignore promotion items. They are added/canceled automatically
if ("Y".equals(valueObj.getString("isPromo"))) {
continue;
}
GenericValue oldOrderItem = null;
try {
oldOrderItem = delegator.findByPrimaryKey("OrderItem", UtilMisc.toMap("orderId", valueObj.getString("orderId"), "orderItemSeqId", valueObj.getString("orderItemSeqId")));
} catch (GenericEntityException e) {
Debug.logError(e, module);
throw new GeneralException(e.getMessage());
}
if (UtilValidate.isNotEmpty(oldOrderItem)) {
// 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;
boolean changeFound = false;
Map modifiedItem = FastMap.newInstance();
if (!oldItemDescription.equals(valueObj.getString("itemDescription"))) {
modifiedItem.put("itemDescription", oldItemDescription);
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 itemReasonMap = (Map) changeMap.get("itemReasonMap");
Map itemCommentMap = (Map) changeMap.get("itemCommentMap");
if (UtilValidate.isNotEmpty(itemReasonMap)) {
String changeReasonId = (String) itemReasonMap.get(valueObj.getString("orderItemSeqId"));
modifiedItem.put("reasonEnumId", changeReasonId);
}
if (UtilValidate.isNotEmpty(itemCommentMap)) {
String changeComments = (String) itemCommentMap.get(valueObj.getString("orderItemSeqId"));
modifiedItem.put("changeComments", changeComments);
}
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 itemReasonMap = (Map) changeMap.get("itemReasonMap");
Map itemCommentMap = (Map) changeMap.get("itemCommentMap");
Map appendedItem = FastMap.newInstance();
if (UtilValidate.isNotEmpty(itemReasonMap)) {
String changeReasonId = (String) itemReasonMap.get("reasonEnumId");
appendedItem.put("reasonEnumId", changeReasonId);
}
if (UtilValidate.isNotEmpty(itemCommentMap)) {
String changeComments = (String) 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);
}
}
}
Debug.logInfo("To Store Contains: " + toStore, module);
// remove any order item attributes that were set to empty
try {
delegator.removeAll(toRemove,true);
} 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 modifiendItem: modifiedItems) {
Map serviceCtx = FastMap.newInstance();
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 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((String) resp.get(ModelService.ERROR_MESSAGE));
}
}
}
// make the order item object map & the ship group assoc list
List orderItemShipGroupAssoc = new LinkedList();
Map itemValuesBySeqId = new HashMap();
Iterator oii = toStore.iterator();
while (oii.hasNext()) {
GenericValue v = (GenericValue) oii.next();
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 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)));
}
}