0001: /*******************************************************************************
0002: * Licensed to the Apache Software Foundation (ASF) under one
0003: * or more contributor license agreements. See the NOTICE file
0004: * distributed with this work for additional information
0005: * regarding copyright ownership. The ASF licenses this file
0006: * to you under the Apache License, Version 2.0 (the
0007: * "License"); you may not use this file except in compliance
0008: * with the License. You may obtain a copy of the License at
0009: *
0010: * http://www.apache.org/licenses/LICENSE-2.0
0011: *
0012: * Unless required by applicable law or agreed to in writing,
0013: * software distributed under the License is distributed on an
0014: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
0015: * KIND, either express or implied. See the License for the
0016: * specific language governing permissions and limitations
0017: * under the License.
0018: *******************************************************************************/package org.ofbiz.order.shoppingcart;
0019:
0020: import java.text.NumberFormat;
0021: import java.util.Iterator;
0022: import java.util.LinkedList;
0023: import java.util.List;
0024: import java.util.Locale;
0025: import java.util.Map;
0026: import javax.servlet.http.HttpServletRequest;
0027: import javax.servlet.http.HttpServletResponse;
0028: import javax.servlet.http.HttpSession;
0029:
0030: import org.ofbiz.base.util.Debug;
0031: import org.ofbiz.base.util.UtilDateTime;
0032: import org.ofbiz.base.util.UtilFormatOut;
0033: import org.ofbiz.base.util.UtilHttp;
0034: import org.ofbiz.base.util.UtilMisc;
0035: import org.ofbiz.base.util.UtilProperties;
0036: import org.ofbiz.base.util.UtilValidate;
0037: import org.ofbiz.entity.GenericDelegator;
0038: import org.ofbiz.entity.GenericEntityException;
0039: import org.ofbiz.entity.GenericPK;
0040: import org.ofbiz.entity.GenericValue;
0041: import org.ofbiz.entity.util.EntityUtil;
0042: import org.ofbiz.order.shoppingcart.product.ProductPromoWorker;
0043: import org.ofbiz.product.catalog.CatalogWorker;
0044: import org.ofbiz.product.config.ProductConfigWorker;
0045: import org.ofbiz.product.config.ProductConfigWrapper;
0046: import org.ofbiz.product.product.ProductWorker;
0047: import org.ofbiz.product.store.ProductStoreSurveyWrapper;
0048: import org.ofbiz.product.store.ProductStoreWorker;
0049: import org.ofbiz.security.Security;
0050: import org.ofbiz.service.GenericServiceException;
0051: import org.ofbiz.service.LocalDispatcher;
0052: import org.ofbiz.service.ModelService;
0053: import org.ofbiz.service.ServiceUtil;
0054: import org.ofbiz.webapp.control.RequestHandler;
0055:
0056: /**
0057: * Shopping cart events.
0058: */
0059: public class ShoppingCartEvents {
0060:
0061: public static String module = ShoppingCartEvents.class.getName();
0062: public static final String resource = "OrderUiLabels";
0063: public static final String resource_error = "OrderErrorUiLabels";
0064:
0065: private static final String NO_ERROR = "noerror";
0066: private static final String NON_CRITICAL_ERROR = "noncritical";
0067: private static final String ERROR = "error";
0068:
0069: public static String addProductPromoCode(
0070: HttpServletRequest request, HttpServletResponse response) {
0071: LocalDispatcher dispatcher = (LocalDispatcher) request
0072: .getAttribute("dispatcher");
0073: ShoppingCart cart = getCartObject(request);
0074: String productPromoCodeId = request
0075: .getParameter("productPromoCodeId");
0076: if (UtilValidate.isNotEmpty(productPromoCodeId)) {
0077: String checkResult = cart.addProductPromoCode(
0078: productPromoCodeId, dispatcher);
0079: if (UtilValidate.isNotEmpty(checkResult)) {
0080: request.setAttribute("_ERROR_MESSAGE_", checkResult);
0081: return "error";
0082: }
0083: }
0084: return "success";
0085: }
0086:
0087: public static String addItemGroup(HttpServletRequest request,
0088: HttpServletResponse response) {
0089: ShoppingCart cart = getCartObject(request);
0090: Map parameters = UtilHttp.getParameterMap(request);
0091: String groupName = (String) parameters.get("groupName");
0092: String parentGroupNumber = (String) parameters
0093: .get("parentGroupNumber");
0094: String groupNumber = cart.addItemGroup(groupName,
0095: parentGroupNumber);
0096: request.setAttribute("itemGroupNumber", groupNumber);
0097: return "success";
0098: }
0099:
0100: public static String addCartItemToGroup(HttpServletRequest request,
0101: HttpServletResponse response) {
0102: ShoppingCart cart = getCartObject(request);
0103: Map parameters = UtilHttp.getParameterMap(request);
0104: String itemGroupNumber = (String) parameters
0105: .get("itemGroupNumber");
0106: String indexStr = (String) parameters.get("lineIndex");
0107: int index = Integer.parseInt(indexStr);
0108: ShoppingCartItem cartItem = cart.findCartItem(index);
0109: cartItem.setItemGroup(itemGroupNumber, cart);
0110: return "success";
0111: }
0112:
0113: /** Event to add an item to the shopping cart. */
0114: public static String addToCart(HttpServletRequest request,
0115: HttpServletResponse response) {
0116: GenericDelegator delegator = (GenericDelegator) request
0117: .getAttribute("delegator");
0118: LocalDispatcher dispatcher = (LocalDispatcher) request
0119: .getAttribute("dispatcher");
0120: ShoppingCart cart = getCartObject(request);
0121: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
0122: delegator, dispatcher, cart);
0123: String controlDirective = null;
0124: Map result = null;
0125: String productId = null;
0126: String parentProductId = null;
0127: String itemType = null;
0128: String itemDescription = null;
0129: String productCategoryId = null;
0130: String priceStr = null;
0131: Double price = null;
0132: String quantityStr = null;
0133: double quantity = 0;
0134: String reservStartStr = null;
0135: String reservEndStr = null;
0136: java.sql.Timestamp reservStart = null;
0137: java.sql.Timestamp reservEnd = null;
0138: String reservLengthStr = null;
0139: Double reservLength = null;
0140: String reservPersonsStr = null;
0141: Double reservPersons = null;
0142: String shipBeforeStr = null;
0143: String shipBeforeDateStr = null;
0144: String shipAfterDateStr = null;
0145: java.sql.Timestamp shipBeforeDate = null;
0146: java.sql.Timestamp shipAfterDate = null;
0147:
0148: // not used right now: Map attributes = null;
0149: String catalogId = CatalogWorker.getCurrentCatalogId(request);
0150: Locale locale = UtilHttp.getLocale(request);
0151: NumberFormat nf = NumberFormat.getNumberInstance(locale);
0152:
0153: // Get the parameters as a MAP, remove the productId and quantity params.
0154: Map paramMap = UtilHttp.getParameterMap(request);
0155:
0156: String itemGroupNumber = (String) paramMap
0157: .get("itemGroupNumber");
0158:
0159: // Get shoppingList info if passed
0160: String shoppingListId = (String) paramMap.get("shoppingListId");
0161: String shoppingListItemSeqId = (String) paramMap
0162: .get("shoppingListItemSeqId");
0163: if (paramMap.containsKey("ADD_PRODUCT_ID")) {
0164: productId = (String) paramMap.remove("ADD_PRODUCT_ID");
0165: } else if (paramMap.containsKey("add_product_id")) {
0166: productId = (String) paramMap.remove("add_product_id");
0167: }
0168: if (paramMap.containsKey("PRODUCT_ID")) {
0169: parentProductId = (String) paramMap.remove("PRODUCT_ID");
0170: } else if (paramMap.containsKey("product_id")) {
0171: parentProductId = (String) paramMap.remove("product_id");
0172: }
0173:
0174: Debug.logInfo("adding item product " + productId, module);
0175: Debug.logInfo("adding item parent product " + parentProductId,
0176: module);
0177:
0178: if (paramMap.containsKey("ADD_CATEGORY_ID")) {
0179: productCategoryId = (String) paramMap
0180: .remove("ADD_CATEGORY_ID");
0181: } else if (paramMap.containsKey("add_category_id")) {
0182: productCategoryId = (String) paramMap
0183: .remove("add_category_id");
0184: }
0185: if (productCategoryId != null
0186: && productCategoryId.length() == 0) {
0187: productCategoryId = null;
0188: }
0189:
0190: if (paramMap.containsKey("ADD_ITEM_TYPE")) {
0191: itemType = (String) paramMap.remove("ADD_ITEM_TYPE");
0192: } else if (paramMap.containsKey("add_item_type")) {
0193: itemType = (String) paramMap.remove("add_item_type");
0194: }
0195:
0196: if (UtilValidate.isEmpty(productId)) {
0197: // before returning error; check make sure we aren't adding a special item type
0198: if (UtilValidate.isEmpty(itemType)) {
0199: request.setAttribute("_ERROR_MESSAGE_", UtilProperties
0200: .getMessage(resource,
0201: "cart.addToCart.noProductInfoPassed",
0202: locale));
0203: return "success"; // not critical return to same page
0204: }
0205: } else {
0206: try {
0207: String pId = ProductWorker.findProductId(delegator,
0208: productId);
0209: if (pId != null) {
0210: productId = pId;
0211: }
0212: } catch (Throwable e) {
0213: Debug.logWarning(e, module);
0214: }
0215: }
0216:
0217: // check for an itemDescription
0218: if (paramMap.containsKey("ADD_ITEM_DESCRIPTION")) {
0219: itemDescription = (String) paramMap
0220: .remove("ADD_ITEM_DESCRIPTION");
0221: } else if (paramMap.containsKey("add_item_description")) {
0222: itemDescription = (String) paramMap
0223: .remove("add_item_description");
0224: }
0225: if (itemDescription != null && itemDescription.length() == 0) {
0226: itemDescription = null;
0227: }
0228:
0229: // Get the ProductConfigWrapper (it's not null only for configurable items)
0230: ProductConfigWrapper configWrapper = null;
0231: configWrapper = ProductConfigWorker.getProductConfigWrapper(
0232: productId, cart.getCurrency(), request);
0233:
0234: if (configWrapper != null) {
0235: // The choices selected by the user are taken from request and set in the wrapper
0236: ProductConfigWorker.fillProductConfigWrapper(configWrapper,
0237: request);
0238: if (!configWrapper.isCompleted()) {
0239: // The configuration is not valid
0240: request
0241: .setAttribute(
0242: "_ERROR_MESSAGE_",
0243: UtilProperties
0244: .getMessage(
0245: resource,
0246: "cart.addToCart.productConfigurationIsNotValid",
0247: locale));
0248: return "error";
0249: }
0250: }
0251:
0252: // get the override price
0253: if (paramMap.containsKey("PRICE")) {
0254: priceStr = (String) paramMap.remove("PRICE");
0255: } else if (paramMap.containsKey("price")) {
0256: priceStr = (String) paramMap.remove("price");
0257: }
0258: if (priceStr == null) {
0259: priceStr = "0"; // default price is 0
0260: }
0261:
0262: // get the renting data
0263: if (paramMap.containsKey("reservStart")) {
0264: reservStartStr = (String) paramMap.remove("reservStart");
0265: if (reservStartStr.length() == 10) // only date provided, no time string?
0266: reservStartStr += " 00:00:00.000000000"; // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
0267: if (reservStartStr.length() > 0) {
0268: try {
0269: reservStart = java.sql.Timestamp
0270: .valueOf(reservStartStr);
0271: } catch (Exception e) {
0272: Debug.logWarning(e,
0273: "Problems parsing Reservation start string: "
0274: + reservStartStr, module);
0275: reservStart = null;
0276: request.setAttribute("_ERROR_MESSAGE_",
0277: UtilProperties.getMessage(resource,
0278: "cart.addToCart.rental.startDate",
0279: locale));
0280: return "error";
0281: }
0282: } else
0283: reservStart = null;
0284:
0285: if (paramMap.containsKey("reservEnd")) {
0286: reservEndStr = (String) paramMap.remove("reservEnd");
0287: if (reservEndStr.length() == 10) // only date provided, no time string?
0288: reservEndStr += " 00:00:00.000000000"; // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
0289: if (reservEndStr.length() > 0) {
0290: try {
0291: reservEnd = java.sql.Timestamp
0292: .valueOf(reservEndStr);
0293: } catch (Exception e) {
0294: Debug.logWarning(e,
0295: "Problems parsing Reservation end string: "
0296: + reservEndStr, module);
0297: reservEnd = null;
0298: request
0299: .setAttribute(
0300: "_ERROR_MESSAGE_",
0301: UtilProperties
0302: .getMessage(
0303: resource,
0304: "cart.addToCart.rental.endDate",
0305: locale));
0306: return "error";
0307: }
0308: } else
0309: reservEnd = null;
0310: }
0311:
0312: if (reservStart != null && reservEnd != null) {
0313: reservLength = new Double(UtilDateTime.getInterval(
0314: reservStart, reservEnd) / 86400000);
0315: }
0316:
0317: if (reservStart != null
0318: && paramMap.containsKey("reservLength")) {
0319: reservLengthStr = (String) paramMap
0320: .remove("reservLength");
0321: // parse the reservation Length
0322: try {
0323: reservLength = new Double(nf.parse(reservLengthStr)
0324: .doubleValue());
0325: } catch (Exception e) {
0326: Debug.logWarning(e,
0327: "Problems parsing reservation length string: "
0328: + reservLengthStr, module);
0329: reservLength = new Double(1);
0330: request
0331: .setAttribute(
0332: "_ERROR_MESSAGE_",
0333: UtilProperties
0334: .getMessage(
0335: resource_error,
0336: "OrderReservationLengthShouldBeAPositiveNumber",
0337: locale));
0338: return "error";
0339: }
0340: }
0341:
0342: if (reservStart != null
0343: && paramMap.containsKey("reservPersons")) {
0344: reservPersonsStr = (String) paramMap
0345: .remove("reservPersons");
0346: // parse the number of persons
0347: try {
0348: reservPersons = new Double(nf.parse(
0349: reservPersonsStr).doubleValue());
0350: } catch (Exception e) {
0351: Debug.logWarning(e,
0352: "Problems parsing reservation number of persons string: "
0353: + reservPersonsStr, module);
0354: reservPersons = new Double(1);
0355: request
0356: .setAttribute(
0357: "_ERROR_MESSAGE_",
0358: UtilProperties
0359: .getMessage(
0360: resource_error,
0361: "OrderNumberOfPersonsShouldBeOneOrLarger",
0362: locale));
0363: return "error";
0364: }
0365: }
0366: }
0367:
0368: // get the quantity
0369: if (paramMap.containsKey("QUANTITY")) {
0370: quantityStr = (String) paramMap.remove("QUANTITY");
0371: } else if (paramMap.containsKey("quantity")) {
0372: quantityStr = (String) paramMap.remove("quantity");
0373: }
0374: if (UtilValidate.isEmpty(quantityStr)) {
0375: quantityStr = "1"; // default quantity is 1
0376: }
0377:
0378: // parse the price
0379: try {
0380: price = new Double(nf.parse(priceStr).doubleValue());
0381: } catch (Exception e) {
0382: Debug.logWarning(e, "Problems parsing price string: "
0383: + priceStr, module);
0384: price = null;
0385: }
0386:
0387: // parse the quantity
0388: try {
0389: quantity = nf.parse(quantityStr).doubleValue();
0390: } catch (Exception e) {
0391: Debug.logWarning(e, "Problems parsing quantity string: "
0392: + quantityStr, module);
0393: quantity = 1;
0394: }
0395:
0396: // get the selected amount
0397: String selectedAmountStr = "0.00";
0398: if (paramMap.containsKey("ADD_AMOUNT")) {
0399: selectedAmountStr = (String) paramMap.remove("ADD_AMOUNT");
0400: } else if (paramMap.containsKey("add_amount")) {
0401: selectedAmountStr = (String) paramMap.remove("add_amount");
0402: }
0403:
0404: // parse the amount
0405: Double amount = null;
0406: if (selectedAmountStr != null && selectedAmountStr.length() > 0) {
0407: try {
0408: amount = new Double(nf.parse(selectedAmountStr)
0409: .doubleValue());
0410: } catch (Exception e) {
0411: Debug.logWarning(e, "Problem parsing amount string: "
0412: + selectedAmountStr, module);
0413: amount = null;
0414: }
0415: }
0416:
0417: // get the ship before date (handles both yyyy-mm-dd input and full timestamp)
0418: shipBeforeDateStr = (String) paramMap.remove("shipBeforeDate");
0419: if (shipBeforeDateStr != null && shipBeforeDateStr.length() > 0) {
0420: if (shipBeforeDateStr.length() == 10)
0421: shipBeforeDateStr += " 00:00:00.000";
0422: try {
0423: shipBeforeDate = java.sql.Timestamp
0424: .valueOf(shipBeforeDateStr);
0425: } catch (IllegalArgumentException e) {
0426: Debug.logWarning(e, "Bad shipBeforeDate input: "
0427: + e.getMessage(), module);
0428: shipBeforeDate = null;
0429: }
0430: }
0431:
0432: // get the ship after date (handles both yyyy-mm-dd input and full timestamp)
0433: shipAfterDateStr = (String) paramMap.remove("shipAfterDate");
0434: if (shipAfterDateStr != null && shipAfterDateStr.length() > 0) {
0435: if (shipAfterDateStr.length() == 10)
0436: shipAfterDateStr += " 00:00:00.000";
0437: try {
0438: shipAfterDate = java.sql.Timestamp
0439: .valueOf(shipAfterDateStr);
0440: } catch (IllegalArgumentException e) {
0441: Debug.logWarning(e, "Bad shipAfterDate input: "
0442: + e.getMessage(), module);
0443: shipAfterDate = null;
0444: }
0445: }
0446:
0447: // check for an add-to cart survey
0448: List surveyResponses = null;
0449: if (productId != null) {
0450: String productStoreId = ProductStoreWorker
0451: .getProductStoreId(request);
0452: List productSurvey = ProductStoreWorker.getProductSurveys(
0453: delegator, productStoreId, productId, "CART_ADD",
0454: parentProductId);
0455: if (productSurvey != null && productSurvey.size() > 0) {
0456: // TODO: implement multiple survey per product
0457: GenericValue survey = EntityUtil
0458: .getFirst(productSurvey);
0459: String surveyResponseId = (String) request
0460: .getAttribute("surveyResponseId");
0461: if (surveyResponseId != null) {
0462: surveyResponses = UtilMisc.toList(surveyResponseId);
0463: } else {
0464: Map surveyContext = UtilHttp
0465: .getParameterMap(request);
0466: GenericValue userLogin = cart.getUserLogin();
0467: String partyId = null;
0468: if (userLogin != null) {
0469: partyId = userLogin.getString("partyId");
0470: }
0471: String formAction = "/additemsurvey";
0472: String nextPage = RequestHandler
0473: .getNextPageUri(request.getPathInfo());
0474: if (nextPage != null) {
0475: formAction = formAction + "/" + nextPage;
0476: }
0477: ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(
0478: survey, partyId, surveyContext);
0479: request.setAttribute("surveyWrapper", wrapper);
0480: request.setAttribute("surveyAction", formAction); // will be used as the form action of the survey
0481: return "survey";
0482: }
0483: }
0484: }
0485: if (surveyResponses != null) {
0486: paramMap.put("surveyResponses", surveyResponses);
0487: }
0488:
0489: // Translate the parameters and add to the cart
0490: result = cartHelper.addToCart(catalogId, shoppingListId,
0491: shoppingListItemSeqId, productId, productCategoryId,
0492: itemType, itemDescription, price, amount, quantity,
0493: reservStart, reservLength, reservPersons,
0494: shipBeforeDate, shipAfterDate, configWrapper,
0495: itemGroupNumber, paramMap, parentProductId);
0496: controlDirective = processResult(result, request);
0497:
0498: // Determine where to send the browser
0499: if (controlDirective.equals(ERROR)) {
0500: return "error";
0501: } else {
0502: if (cart.viewCartOnAdd()) {
0503: return "viewcart";
0504: } else {
0505: return "success";
0506: }
0507: }
0508: }
0509:
0510: public static String addToCartFromOrder(HttpServletRequest request,
0511: HttpServletResponse response) {
0512: String orderId = request.getParameter("orderId");
0513: String itemGroupNumber = request
0514: .getParameter("itemGroupNumber");
0515: String[] itemIds = request.getParameterValues("item_id");
0516: // not used yet: Locale locale = UtilHttp.getLocale(request);
0517:
0518: ShoppingCart cart = getCartObject(request);
0519: GenericDelegator delegator = (GenericDelegator) request
0520: .getAttribute("delegator");
0521: LocalDispatcher dispatcher = (LocalDispatcher) request
0522: .getAttribute("dispatcher");
0523: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
0524: delegator, dispatcher, cart);
0525: String catalogId = CatalogWorker.getCurrentCatalogId(request);
0526: Map result;
0527: String controlDirective;
0528:
0529: boolean addAll = ("true"
0530: .equals(request.getParameter("add_all")));
0531: result = cartHelper.addToCartFromOrder(catalogId, orderId,
0532: itemIds, addAll, itemGroupNumber);
0533: controlDirective = processResult(result, request);
0534:
0535: //Determine where to send the browser
0536: if (controlDirective.equals(ERROR)) {
0537: return "error";
0538: } else {
0539: return "success";
0540: }
0541: }
0542:
0543: /** Adds all products in a category according to quantity request parameter
0544: * for each; if no parameter for a certain product in the category, or if
0545: * quantity is 0, do not add
0546: */
0547: public static String addToCartBulk(HttpServletRequest request,
0548: HttpServletResponse response) {
0549: String categoryId = request.getParameter("category_id");
0550: ShoppingCart cart = getCartObject(request);
0551: GenericDelegator delegator = (GenericDelegator) request
0552: .getAttribute("delegator");
0553: LocalDispatcher dispatcher = (LocalDispatcher) request
0554: .getAttribute("dispatcher");
0555: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
0556: delegator, dispatcher, cart);
0557: String controlDirective;
0558: Map result;
0559: // not used yet: Locale locale = UtilHttp.getLocale(request);
0560:
0561: //Convert the params to a map to pass in
0562: Map paramMap = UtilHttp.getParameterMap(request);
0563: String catalogId = CatalogWorker.getCurrentCatalogId(request);
0564: result = cartHelper.addToCartBulk(catalogId, categoryId,
0565: paramMap);
0566: controlDirective = processResult(result, request);
0567:
0568: //Determine where to send the browser
0569: if (controlDirective.equals(ERROR)) {
0570: return "error";
0571: } else {
0572: return "success";
0573: }
0574: }
0575:
0576: public static String quickInitPurchaseOrder(
0577: HttpServletRequest request, HttpServletResponse response) {
0578: HttpSession session = request.getSession();
0579:
0580: ShoppingCart cart = new WebShoppingCart(request);
0581: // TODO: the code below here needs some cleanups
0582: cart.setBillToCustomerPartyId(request
0583: .getParameter("billToCustomerPartyId_o_0"));
0584: cart.setBillFromVendorPartyId(request
0585: .getParameter("supplierPartyId_o_0"));
0586: cart.setOrderPartyId(request
0587: .getParameter("supplierPartyId_o_0"));
0588:
0589: cart.setOrderType("PURCHASE_ORDER");
0590:
0591: session.setAttribute("shoppingCart", cart);
0592: session
0593: .setAttribute("productStoreId", cart
0594: .getProductStoreId());
0595: session.setAttribute("orderMode", cart.getOrderType());
0596: session.setAttribute("orderPartyId", cart.getOrderPartyId());
0597:
0598: return "success";
0599: }
0600:
0601: public static String quickCheckoutOrderWithDefaultOptions(
0602: HttpServletRequest request, HttpServletResponse response) {
0603: LocalDispatcher dispatcher = (LocalDispatcher) request
0604: .getAttribute("dispatcher");
0605: ShoppingCart cart = getCartObject(request);
0606:
0607: // Set the cart's default checkout options for a quick checkout
0608: cart.setDefaultCheckoutOptions(dispatcher);
0609:
0610: return "success";
0611: }
0612:
0613: /** Adds a set of requirements to the cart
0614: */
0615: public static String addToCartBulkRequirements(
0616: HttpServletRequest request, HttpServletResponse response) {
0617: ShoppingCart cart = getCartObject(request);
0618: GenericDelegator delegator = (GenericDelegator) request
0619: .getAttribute("delegator");
0620: LocalDispatcher dispatcher = (LocalDispatcher) request
0621: .getAttribute("dispatcher");
0622: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
0623: delegator, dispatcher, cart);
0624: String controlDirective;
0625: Map result;
0626: // not used yet: Locale locale = UtilHttp.getLocale(request);
0627:
0628: //Convert the params to a map to pass in
0629: Map paramMap = UtilHttp.getParameterMap(request);
0630: String catalogId = CatalogWorker.getCurrentCatalogId(request);
0631: result = cartHelper.addToCartBulkRequirements(catalogId,
0632: paramMap);
0633: controlDirective = processResult(result, request);
0634:
0635: //Determine where to send the browser
0636: if (controlDirective.equals(ERROR)) {
0637: return "error";
0638: } else {
0639: return "success";
0640: }
0641: }
0642:
0643: /** Adds all products in a category according to default quantity on ProductCategoryMember
0644: * for each; if no default for a certain product in the category, or if
0645: * quantity is 0, do not add
0646: */
0647: public static String addCategoryDefaults(
0648: HttpServletRequest request, HttpServletResponse response) {
0649: String itemGroupNumber = request
0650: .getParameter("itemGroupNumber");
0651: String categoryId = request.getParameter("category_id");
0652: String catalogId = CatalogWorker.getCurrentCatalogId(request);
0653: ShoppingCart cart = getCartObject(request);
0654: GenericDelegator delegator = (GenericDelegator) request
0655: .getAttribute("delegator");
0656: LocalDispatcher dispatcher = (LocalDispatcher) request
0657: .getAttribute("dispatcher");
0658: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
0659: delegator, dispatcher, cart);
0660: String controlDirective;
0661: Map result;
0662: Double totalQuantity;
0663: Locale locale = UtilHttp.getLocale(request);
0664:
0665: result = cartHelper.addCategoryDefaults(catalogId, categoryId,
0666: itemGroupNumber);
0667: controlDirective = processResult(result, request);
0668:
0669: //Determine where to send the browser
0670: if (controlDirective.equals(ERROR)) {
0671: return "error";
0672: } else {
0673: totalQuantity = (Double) result.get("totalQuantity");
0674: Map messageMap = UtilMisc.toMap("totalQuantity",
0675: UtilFormatOut.formatQuantity(totalQuantity));
0676:
0677: request.setAttribute("_EVENT_MESSAGE_", UtilProperties
0678: .getMessage(resource, "cart.add_category_defaults",
0679: messageMap, locale));
0680:
0681: return "success";
0682: }
0683: }
0684:
0685: /** Delete an item from the shopping cart. */
0686: public static String deleteFromCart(HttpServletRequest request,
0687: HttpServletResponse response) {
0688: ShoppingCart cart = getCartObject(request);
0689: LocalDispatcher dispatcher = (LocalDispatcher) request
0690: .getAttribute("dispatcher");
0691: ShoppingCartHelper cartHelper = new ShoppingCartHelper(null,
0692: dispatcher, cart);
0693: String controlDirective;
0694: Map result;
0695: Map paramMap = UtilHttp.getParameterMap(request);
0696: // not used yet: Locale locale = UtilHttp.getLocale(request);
0697:
0698: //Delegate the cart helper
0699: result = cartHelper.deleteFromCart(paramMap);
0700: controlDirective = processResult(result, request);
0701:
0702: //Determine where to send the browser
0703: if (controlDirective.equals(ERROR)) {
0704: return "error";
0705: } else {
0706: return "success";
0707: }
0708: }
0709:
0710: /** Update the items in the shopping cart. */
0711: public static String modifyCart(HttpServletRequest request,
0712: HttpServletResponse response) {
0713: HttpSession session = request.getSession();
0714: ShoppingCart cart = getCartObject(request);
0715: Locale locale = UtilHttp.getLocale(request);
0716: GenericValue userLogin = (GenericValue) session
0717: .getAttribute("userLogin");
0718: LocalDispatcher dispatcher = (LocalDispatcher) request
0719: .getAttribute("dispatcher");
0720: Security security = (Security) request.getAttribute("security");
0721: ShoppingCartHelper cartHelper = new ShoppingCartHelper(null,
0722: dispatcher, cart);
0723: String controlDirective;
0724: Map result;
0725: // not used yet: Locale locale = UtilHttp.getLocale(request);
0726:
0727: Map paramMap = UtilHttp.getParameterMap(request);
0728:
0729: String removeSelectedFlag = request
0730: .getParameter("removeSelected");
0731: String selectedItems[] = request
0732: .getParameterValues("selectedItem");
0733: boolean removeSelected = ("true".equals(removeSelectedFlag)
0734: && selectedItems != null && selectedItems.length > 0);
0735: result = cartHelper.modifyCart(security, userLogin, paramMap,
0736: removeSelected, selectedItems, locale);
0737: controlDirective = processResult(result, request);
0738:
0739: //Determine where to send the browser
0740: if (controlDirective.equals(ERROR)) {
0741: return "error";
0742: } else {
0743: return "success";
0744: }
0745: }
0746:
0747: /** Empty the shopping cart. */
0748: public static String clearCart(HttpServletRequest request,
0749: HttpServletResponse response) {
0750: ShoppingCart cart = getCartObject(request);
0751: cart.clear();
0752:
0753: // if this was an anonymous checkout process, go ahead and clear the session and such now that the order is placed; we don't want this to mess up additional orders and such
0754: HttpSession session = request.getSession();
0755: GenericValue userLogin = (GenericValue) session
0756: .getAttribute("userLogin");
0757: if (userLogin != null
0758: && "anonymous".equals(userLogin.get("userLoginId"))) {
0759: // here we want to do a full logout, but not using the normal logout stuff because it saves things in the UserLogin record that we don't want changed for the anonymous user
0760: session.invalidate();
0761: session = request.getSession(true);
0762:
0763: // to allow the display of the order confirmation page put the userLogin in the request, but leave it out of the session
0764: request.setAttribute("temporaryAnonymousUserLogin",
0765: userLogin);
0766:
0767: Debug
0768: .logInfo(
0769: "Doing clearCart for anonymous user, so logging out but put anonymous userLogin in temporaryAnonymousUserLogin request attribute",
0770: module);
0771: }
0772:
0773: return "success";
0774: }
0775:
0776: /** Totally wipe out the cart, removes all stored info. */
0777: public static String destroyCart(HttpServletRequest request,
0778: HttpServletResponse response) {
0779: HttpSession session = request.getSession();
0780: clearCart(request, response);
0781: session.removeAttribute("shoppingCart");
0782: session.removeAttribute("orderPartyId");
0783: session.removeAttribute("orderMode");
0784: session.removeAttribute("productStoreId");
0785: session.removeAttribute("CURRENT_CATALOG_ID");
0786: return "success";
0787: }
0788:
0789: /** Gets or creates the shopping cart object */
0790: public static ShoppingCart getCartObject(
0791: HttpServletRequest request, Locale locale,
0792: String currencyUom) {
0793: LocalDispatcher dispatcher = (LocalDispatcher) request
0794: .getAttribute("dispatcher");
0795: ShoppingCart cart = (ShoppingCart) request
0796: .getAttribute("shoppingCart");
0797: HttpSession session = request.getSession(true);
0798: if (cart == null) {
0799: cart = (ShoppingCart) session.getAttribute("shoppingCart");
0800: } else {
0801: session.setAttribute("shoppingCart", cart);
0802: }
0803:
0804: if (cart == null) {
0805: cart = new WebShoppingCart(request, locale, currencyUom);
0806: session.setAttribute("shoppingCart", cart);
0807: } else {
0808: if (locale != null && !locale.equals(cart.getLocale())) {
0809: cart.setLocale(locale);
0810: }
0811: if (currencyUom != null
0812: && !currencyUom.equals(cart.getCurrency())) {
0813: try {
0814: cart.setCurrency(dispatcher, currencyUom);
0815: } catch (CartItemModifyException e) {
0816: Debug
0817: .logError(
0818: e,
0819: "Unable to modify currency in cart",
0820: module);
0821: }
0822: }
0823: }
0824: return cart;
0825: }
0826:
0827: /** Main get cart method; uses the locale & currency from the session */
0828: public static ShoppingCart getCartObject(HttpServletRequest request) {
0829: return getCartObject(request, null, null);
0830: }
0831:
0832: /** Update the cart's UserLogin object if it isn't already set. */
0833: public static String keepCartUpdated(HttpServletRequest request,
0834: HttpServletResponse response) {
0835: LocalDispatcher dispatcher = (LocalDispatcher) request
0836: .getAttribute("dispatcher");
0837: HttpSession session = request.getSession();
0838: ShoppingCart cart = getCartObject(request);
0839:
0840: // if we just logged in set the UL
0841: if (cart.getUserLogin() == null) {
0842: GenericValue userLogin = (GenericValue) session
0843: .getAttribute("userLogin");
0844: if (userLogin != null) {
0845: try {
0846: cart.setUserLogin(userLogin, dispatcher);
0847: } catch (CartItemModifyException e) {
0848: Debug.logWarning(e, module);
0849: }
0850: }
0851: }
0852:
0853: // same for autoUserLogin
0854: if (cart.getAutoUserLogin() == null) {
0855: GenericValue autoUserLogin = (GenericValue) session
0856: .getAttribute("autoUserLogin");
0857: if (autoUserLogin != null) {
0858: if (cart.getUserLogin() == null) {
0859: try {
0860: cart
0861: .setAutoUserLogin(autoUserLogin,
0862: dispatcher);
0863: } catch (CartItemModifyException e) {
0864: Debug.logWarning(e, module);
0865: }
0866: } else {
0867: cart.setAutoUserLogin(autoUserLogin);
0868: }
0869: }
0870: }
0871:
0872: // update the locale
0873: Locale locale = UtilHttp.getLocale(request);
0874: if (cart.getLocale() == null
0875: || !locale.equals(cart.getLocale())) {
0876: cart.setLocale(locale);
0877: }
0878:
0879: return "success";
0880: }
0881:
0882: /** For GWP Promotions with multiple alternatives, selects an alternative to the current GWP */
0883: public static String setDesiredAlternateGwpProductId(
0884: HttpServletRequest request, HttpServletResponse response) {
0885: ShoppingCart cart = getCartObject(request);
0886: GenericDelegator delegator = (GenericDelegator) request
0887: .getAttribute("delegator");
0888: LocalDispatcher dispatcher = (LocalDispatcher) request
0889: .getAttribute("dispatcher");
0890: String alternateGwpProductId = request
0891: .getParameter("alternateGwpProductId");
0892: String alternateGwpLineStr = request
0893: .getParameter("alternateGwpLine");
0894: Locale locale = UtilHttp.getLocale(request);
0895:
0896: if (UtilValidate.isEmpty(alternateGwpProductId)) {
0897: request
0898: .setAttribute(
0899: "_ERROR_MESSAGE_",
0900: UtilProperties
0901: .getMessage(
0902: resource_error,
0903: "OrderCouldNotSelectAlternateGiftNoAlternateGwpProductIdPassed",
0904: locale));
0905: return "error";
0906: }
0907: if (UtilValidate.isEmpty(alternateGwpLineStr)) {
0908: request
0909: .setAttribute(
0910: "_ERROR_MESSAGE_",
0911: UtilProperties
0912: .getMessage(
0913: resource_error,
0914: "OrderCouldNotSelectAlternateGiftNoAlternateGwpLinePassed",
0915: locale));
0916: return "error";
0917: }
0918:
0919: int alternateGwpLine = 0;
0920: try {
0921: alternateGwpLine = Integer.parseInt(alternateGwpLineStr);
0922: } catch (Exception e) {
0923: request
0924: .setAttribute(
0925: "_ERROR_MESSAGE_",
0926: UtilProperties
0927: .getMessage(
0928: resource_error,
0929: "OrderCouldNotSelectAlternateGiftAlternateGwpLineIsNotAValidNumber",
0930: locale));
0931: return "error";
0932: }
0933:
0934: ShoppingCartItem cartLine = cart.findCartItem(alternateGwpLine);
0935: if (cartLine == null) {
0936: request.setAttribute("_ERROR_MESSAGE_",
0937: "Could not select alternate gift, no cart line item found for #"
0938: + alternateGwpLine + ".");
0939: return "error";
0940: }
0941:
0942: if (cartLine.getIsPromo()) {
0943: // note that there should just be one promo adjustment, the reversal of the GWP, so use that to get the promo action key
0944: Iterator checkOrderAdjustments = UtilMisc
0945: .toIterator(cartLine.getAdjustments());
0946: while (checkOrderAdjustments != null
0947: && checkOrderAdjustments.hasNext()) {
0948: GenericValue checkOrderAdjustment = (GenericValue) checkOrderAdjustments
0949: .next();
0950: if (UtilValidate.isNotEmpty(checkOrderAdjustment
0951: .getString("productPromoId"))
0952: && UtilValidate.isNotEmpty(checkOrderAdjustment
0953: .getString("productPromoRuleId"))
0954: && UtilValidate.isNotEmpty(checkOrderAdjustment
0955: .getString("productPromoActionSeqId"))) {
0956: GenericPK productPromoActionPk = delegator
0957: .makeValidValue("ProductPromoAction",
0958: checkOrderAdjustment)
0959: .getPrimaryKey();
0960: cart
0961: .setDesiredAlternateGiftByAction(
0962: productPromoActionPk,
0963: alternateGwpProductId);
0964: if (cart.getOrderType().equals("SALES_ORDER")) {
0965: org.ofbiz.order.shoppingcart.product.ProductPromoWorker
0966: .doPromotions(cart, dispatcher);
0967: }
0968: return "success";
0969: }
0970: }
0971: }
0972:
0973: request
0974: .setAttribute(
0975: "_ERROR_MESSAGE_",
0976: "Could not select alternate gift, cart line item found for #"
0977: + alternateGwpLine
0978: + " does not appear to be a valid promotional gift.");
0979: return "error";
0980: }
0981:
0982: /** Associates a party to order */
0983: public static String addAdditionalParty(HttpServletRequest request,
0984: HttpServletResponse response) {
0985: ShoppingCart cart = getCartObject(request);
0986: String partyId = request.getParameter("additionalPartyId");
0987: String roleTypeId[] = request
0988: .getParameterValues("additionalRoleTypeId");
0989: List eventList = new LinkedList();
0990: Locale locale = UtilHttp.getLocale(request);
0991: int i;
0992:
0993: if (UtilValidate.isEmpty(partyId) || roleTypeId.length < 1) {
0994: request.setAttribute("_ERROR_MESSAGE_", UtilProperties
0995: .getMessage(resource_error,
0996: "OrderPartyIdAndOrRoleTypeIdNotDefined",
0997: locale));
0998: return "error";
0999: }
1000:
1001: if (request.getAttribute("_EVENT_MESSAGE_LIST_") != null) {
1002: eventList.addAll((List) request
1003: .getAttribute("_EVENT_MESSAGE_LIST_"));
1004: }
1005:
1006: for (i = 0; i < roleTypeId.length; i++) {
1007: try {
1008: cart.addAdditionalPartyRole(partyId, roleTypeId[i]);
1009: } catch (Exception e) {
1010: eventList.add(e.getLocalizedMessage());
1011: }
1012: }
1013:
1014: request.removeAttribute("_EVENT_MESSAGE_LIST_");
1015: request.setAttribute("_EVENT_MESSAGE_LIST_", eventList);
1016: return "success";
1017: }
1018:
1019: /** Removes a previously associated party to order */
1020: public static String removeAdditionalParty(
1021: HttpServletRequest request, HttpServletResponse response) {
1022: ShoppingCart cart = getCartObject(request);
1023: String partyId = request.getParameter("additionalPartyId");
1024: String roleTypeId[] = request
1025: .getParameterValues("additionalRoleTypeId");
1026: List eventList = new LinkedList();
1027: Locale locale = UtilHttp.getLocale(request);
1028: int i;
1029:
1030: if (UtilValidate.isEmpty(partyId) || roleTypeId.length < 1) {
1031: request.setAttribute("_ERROR_MESSAGE_", UtilProperties
1032: .getMessage(resource_error,
1033: "OrderPartyIdAndOrRoleTypeIdNotDefined",
1034: locale));
1035: return "error";
1036: }
1037:
1038: if (request.getAttribute("_EVENT_MESSAGE_LIST_") != null) {
1039: eventList.addAll((List) request
1040: .getAttribute("_EVENT_MESSAGE_LIST_"));
1041: }
1042:
1043: for (i = 0; i < roleTypeId.length; i++) {
1044: try {
1045: cart.removeAdditionalPartyRole(partyId, roleTypeId[i]);
1046: } catch (Exception e) {
1047: Debug.logInfo(e.getLocalizedMessage(), module);
1048: eventList.add(e.getLocalizedMessage());
1049: }
1050: }
1051:
1052: request.removeAttribute("_EVENT_MESSAGE_LIST_");
1053: request.setAttribute("_EVENT_MESSAGE_LIST_", eventList);
1054: return "success";
1055: }
1056:
1057: /**
1058: * This should be called to translate the error messages of the
1059: * <code>ShoppingCartHelper</code> to an appropriately formatted
1060: * <code>String</code> in the request object and indicate whether
1061: * the result was an error or not and whether the errors were
1062: * critical or not
1063: *
1064: * @param result The result returned from the
1065: * <code>ShoppingCartHelper</code>
1066: * @param request The servlet request instance to set the error messages
1067: * in
1068: * @return one of NON_CRITICAL_ERROR, ERROR or NO_ERROR.
1069: */
1070: private static String processResult(Map result,
1071: HttpServletRequest request) {
1072: //Check for errors
1073: StringBuffer errMsg = new StringBuffer();
1074: if (result.containsKey(ModelService.ERROR_MESSAGE_LIST)) {
1075: List errorMsgs = (List) result
1076: .get(ModelService.ERROR_MESSAGE_LIST);
1077: Iterator iterator = errorMsgs.iterator();
1078: errMsg.append("<ul>");
1079: while (iterator.hasNext()) {
1080: errMsg.append("<li>");
1081: errMsg.append(iterator.next());
1082: errMsg.append("</li>");
1083: }
1084: errMsg.append("</ul>");
1085: } else if (result.containsKey(ModelService.ERROR_MESSAGE)) {
1086: errMsg.append(result.get(ModelService.ERROR_MESSAGE));
1087: request.setAttribute("_ERROR_MESSAGE_", errMsg.toString());
1088: }
1089:
1090: //See whether there was an error
1091: if (errMsg.length() > 0) {
1092: request.setAttribute("_ERROR_MESSAGE_", errMsg.toString());
1093: if (result.get(ModelService.RESPONSE_MESSAGE).equals(
1094: ModelService.RESPOND_SUCCESS)) {
1095: return NON_CRITICAL_ERROR;
1096: } else {
1097: return ERROR;
1098: }
1099: } else {
1100: return NO_ERROR;
1101: }
1102: }
1103:
1104: /** Assign agreement **/
1105: public static String selectAgreement(HttpServletRequest request,
1106: HttpServletResponse response) {
1107: GenericDelegator delegator = (GenericDelegator) request
1108: .getAttribute("delegator");
1109: LocalDispatcher dispatcher = (LocalDispatcher) request
1110: .getAttribute("dispatcher");
1111: ShoppingCart cart = getCartObject(request);
1112: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
1113: delegator, dispatcher, cart);
1114: String agreementId = request.getParameter("agreementId");
1115: Map result = cartHelper.selectAgreement(agreementId);
1116: if (ServiceUtil.isError(result)) {
1117: request.setAttribute("_ERROR_MESSAGE_", ServiceUtil
1118: .getErrorMessage(result));
1119: return "error";
1120: }
1121: return "success";
1122: }
1123:
1124: /** Assign currency **/
1125: public static String setCurrency(HttpServletRequest request,
1126: HttpServletResponse response) {
1127: GenericDelegator delegator = (GenericDelegator) request
1128: .getAttribute("delegator");
1129: LocalDispatcher dispatcher = (LocalDispatcher) request
1130: .getAttribute("dispatcher");
1131: ShoppingCart cart = getCartObject(request);
1132: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
1133: delegator, dispatcher, cart);
1134: String currencyUomId = request.getParameter("currencyUomId");
1135: Map result = cartHelper.setCurrency(currencyUomId);
1136: if (ServiceUtil.isError(result)) {
1137: request.setAttribute("_ERROR_MESSAGE_", ServiceUtil
1138: .getErrorMessage(result));
1139: return "error";
1140: }
1141: return "success";
1142: }
1143:
1144: /**
1145: * set the order name of the cart based on request. right now will always return "success"
1146: *
1147: */
1148: public static String setOrderName(HttpServletRequest request,
1149: HttpServletResponse response) {
1150: ShoppingCart cart = getCartObject(request);
1151: String orderName = request.getParameter("orderName");
1152: cart.setOrderName(orderName);
1153: return "success";
1154: }
1155:
1156: /**
1157: * set the PO number of the cart based on request. right now will always return "success"
1158: *
1159: */
1160: public static String setPoNumber(HttpServletRequest request,
1161: HttpServletResponse response) {
1162: ShoppingCart cart = getCartObject(request);
1163: String correspondingPoId = request
1164: .getParameter("correspondingPoId");
1165: cart.setPoNumber(correspondingPoId);
1166: return "success";
1167: }
1168:
1169: /** Add order term **/
1170: public static String addOrderTerm(HttpServletRequest request,
1171: HttpServletResponse response) {
1172: GenericDelegator delegator = (GenericDelegator) request
1173: .getAttribute("delegator");
1174: LocalDispatcher dispatcher = (LocalDispatcher) request
1175: .getAttribute("dispatcher");
1176: ShoppingCart cart = getCartObject(request);
1177: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
1178: delegator, dispatcher, cart);
1179: String termTypeId = request.getParameter("termTypeId");
1180: String termValue = request.getParameter("termValue");
1181: String termDays = request.getParameter("termDays");
1182: String termIndex = request.getParameter("termIndex");
1183: String description = request.getParameter("description");
1184: Locale locale = UtilHttp.getLocale(request);
1185:
1186: Double dTermValue = null;
1187: Long lTermDays = null;
1188:
1189: if (termValue.trim().equals("")) {
1190: termValue = null;
1191: }
1192: if (termDays.trim().equals("")) {
1193: termDays = null;
1194: }
1195: if (UtilValidate.isEmpty(termTypeId)) {
1196: request.setAttribute("_ERROR_MESSAGE_", UtilProperties
1197: .getMessage(resource_error,
1198: "OrderOrderTermTypeIsRequired", locale));
1199: return "error";
1200: }
1201: if (!UtilValidate.isSignedDouble(termValue)) {
1202: request.setAttribute("_ERROR_MESSAGE_", UtilProperties
1203: .getMessage(resource_error, "OrderOrderTermValue",
1204: UtilMisc.toMap("orderTermValue",
1205: UtilValidate.isSignedFloatMsg),
1206: locale));
1207: return "error";
1208: }
1209: if (termValue != null) {
1210: dTermValue = new Double(termValue);
1211: }
1212: if (!UtilValidate.isInteger(termDays)) {
1213: request.setAttribute("_ERROR_MESSAGE_", UtilProperties
1214: .getMessage(resource_error, "OrderOrderTermDays",
1215: UtilMisc.toMap("orderTermDays",
1216: UtilValidate.isLongMsg), locale));
1217: return "error";
1218: }
1219: if (termDays != null) {
1220: lTermDays = new Long(termDays);
1221: }
1222: if ((termIndex != null) && (!"-1".equals(termIndex))
1223: && (UtilValidate.isInteger(termIndex))) {
1224: cartHelper.removeOrderTerm(Integer.parseInt(termIndex));
1225: }
1226:
1227: Map result = cartHelper.addOrderTerm(termTypeId, dTermValue,
1228: lTermDays, description);
1229: if (ServiceUtil.isError(result)) {
1230: request.setAttribute("_ERROR_MESSAGE_", ServiceUtil
1231: .getErrorMessage(result));
1232: return "error";
1233: }
1234: return "success";
1235: }
1236:
1237: /** Add order term **/
1238: public static String removeOrderTerm(HttpServletRequest request,
1239: HttpServletResponse response) {
1240: GenericDelegator delegator = (GenericDelegator) request
1241: .getAttribute("delegator");
1242: LocalDispatcher dispatcher = (LocalDispatcher) request
1243: .getAttribute("dispatcher");
1244: ShoppingCart cart = getCartObject(request);
1245: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
1246: delegator, dispatcher, cart);
1247: String index = request.getParameter("termIndex");
1248: Map result = cartHelper
1249: .removeOrderTerm(Integer.parseInt(index));
1250: if (ServiceUtil.isError(result)) {
1251: request.setAttribute("_ERROR_MESSAGE_", ServiceUtil
1252: .getErrorMessage(result));
1253: return "error";
1254: }
1255: return "success";
1256: }
1257:
1258: /** Initialize order entry from a shopping list **/
1259: public static String loadCartFromShoppingList(
1260: HttpServletRequest request, HttpServletResponse response) {
1261: LocalDispatcher dispatcher = (LocalDispatcher) request
1262: .getAttribute("dispatcher");
1263: HttpSession session = request.getSession();
1264: GenericValue userLogin = (GenericValue) session
1265: .getAttribute("userLogin");
1266:
1267: String shoppingListId = request.getParameter("shoppingListId");
1268:
1269: ShoppingCart cart = null;
1270: try {
1271: Map outMap = dispatcher.runSync("loadCartFromShoppingList",
1272: UtilMisc.toMap("shoppingListId", shoppingListId,
1273: "userLogin", userLogin));
1274: cart = (ShoppingCart) outMap.get("shoppingCart");
1275: } catch (GenericServiceException exc) {
1276: request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
1277: return "error";
1278: }
1279:
1280: session.setAttribute("shoppingCart", cart);
1281: session
1282: .setAttribute("productStoreId", cart
1283: .getProductStoreId());
1284: session.setAttribute("orderMode", cart.getOrderType());
1285: session.setAttribute("orderPartyId", cart.getOrderPartyId());
1286:
1287: return "success";
1288: }
1289:
1290: /** Initialize order entry from a quote **/
1291: public static String loadCartFromQuote(HttpServletRequest request,
1292: HttpServletResponse response) {
1293: LocalDispatcher dispatcher = (LocalDispatcher) request
1294: .getAttribute("dispatcher");
1295: HttpSession session = request.getSession();
1296: GenericValue userLogin = (GenericValue) session
1297: .getAttribute("userLogin");
1298:
1299: String quoteId = request.getParameter("quoteId");
1300:
1301: ShoppingCart cart = null;
1302: try {
1303: Map outMap = dispatcher.runSync("loadCartFromQuote",
1304: UtilMisc.toMap("quoteId", quoteId,
1305: "applyQuoteAdjustments", "true",
1306: "userLogin", userLogin));
1307: cart = (ShoppingCart) outMap.get("shoppingCart");
1308: } catch (GenericServiceException exc) {
1309: request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
1310: return "error";
1311: }
1312:
1313: // Set the cart's default checkout options for a quick checkout
1314: cart.setDefaultCheckoutOptions(dispatcher);
1315: // Make the cart read-only
1316: cart.setReadOnlyCart(true);
1317:
1318: session.setAttribute("shoppingCart", cart);
1319: session
1320: .setAttribute("productStoreId", cart
1321: .getProductStoreId());
1322: session.setAttribute("orderMode", cart.getOrderType());
1323: session.setAttribute("orderPartyId", cart.getOrderPartyId());
1324:
1325: return "success";
1326: }
1327:
1328: /** Initialize order entry from an existing order **/
1329: public static String loadCartFromOrder(HttpServletRequest request,
1330: HttpServletResponse response) {
1331: LocalDispatcher dispatcher = (LocalDispatcher) request
1332: .getAttribute("dispatcher");
1333: HttpSession session = request.getSession();
1334: GenericValue userLogin = (GenericValue) session
1335: .getAttribute("userLogin");
1336:
1337: String quoteId = request.getParameter("orderId");
1338:
1339: ShoppingCart cart = null;
1340: try {
1341: Map outMap = dispatcher.runSync("loadCartFromOrder",
1342: UtilMisc.toMap("orderId", quoteId, "userLogin",
1343: userLogin));
1344: cart = (ShoppingCart) outMap.get("shoppingCart");
1345: } catch (GenericServiceException exc) {
1346: request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
1347: return "error";
1348: }
1349:
1350: cart.setAttribute("addpty", "Y");
1351: session.setAttribute("shoppingCart", cart);
1352: session
1353: .setAttribute("productStoreId", cart
1354: .getProductStoreId());
1355: session.setAttribute("orderMode", cart.getOrderType());
1356: session.setAttribute("orderPartyId", cart.getOrderPartyId());
1357:
1358: return "success";
1359: }
1360:
1361: public static String createQuoteFromCart(
1362: HttpServletRequest request, HttpServletResponse response) {
1363: LocalDispatcher dispatcher = (LocalDispatcher) request
1364: .getAttribute("dispatcher");
1365: HttpSession session = request.getSession();
1366: GenericValue userLogin = (GenericValue) session
1367: .getAttribute("userLogin");
1368: String destroyCart = request.getParameter("destroyCart");
1369:
1370: ShoppingCart cart = getCartObject(request);
1371: Map result = null;
1372: String quoteId = null;
1373: try {
1374: result = dispatcher.runSync("createQuoteFromCart", UtilMisc
1375: .toMap("cart", cart, "userLogin", userLogin));
1376: quoteId = (String) result.get("quoteId");
1377: } catch (GenericServiceException exc) {
1378: request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
1379: return "error";
1380: }
1381: if (ServiceUtil.isError(result)) {
1382: request.setAttribute("_ERROR_MESSAGE_", ServiceUtil
1383: .getErrorMessage(result));
1384: return "error";
1385: }
1386: request.setAttribute("quoteId", quoteId);
1387: if (destroyCart != null && destroyCart.equals("Y")) {
1388: ShoppingCartEvents.destroyCart(request, response);
1389: }
1390:
1391: return "success";
1392: }
1393:
1394: public static String createCustRequestFromCart(
1395: HttpServletRequest request, HttpServletResponse response) {
1396: LocalDispatcher dispatcher = (LocalDispatcher) request
1397: .getAttribute("dispatcher");
1398: HttpSession session = request.getSession();
1399: GenericValue userLogin = (GenericValue) session
1400: .getAttribute("userLogin");
1401: String destroyCart = request.getParameter("destroyCart");
1402:
1403: ShoppingCart cart = getCartObject(request);
1404: Map result = null;
1405: String custRequestId = null;
1406: try {
1407: result = dispatcher
1408: .runSync("createCustRequestFromCart",
1409: UtilMisc.toMap("cart", cart, "userLogin",
1410: userLogin));
1411: custRequestId = (String) result.get("custRequestId");
1412: } catch (GenericServiceException exc) {
1413: request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
1414: return "error";
1415: }
1416: if (ServiceUtil.isError(result)) {
1417: request.setAttribute("_ERROR_MESSAGE_", ServiceUtil
1418: .getErrorMessage(result));
1419: return "error";
1420: }
1421: request.setAttribute("custRequestId", custRequestId);
1422: if (destroyCart != null && destroyCart.equals("Y")) {
1423: ShoppingCartEvents.destroyCart(request, response);
1424: }
1425:
1426: return "success";
1427: }
1428:
1429: /** Initialize order entry **/
1430: public static String initializeOrderEntry(
1431: HttpServletRequest request, HttpServletResponse response) {
1432: GenericDelegator delegator = (GenericDelegator) request
1433: .getAttribute("delegator");
1434: HttpSession session = request.getSession();
1435: Security security = (Security) request.getAttribute("security");
1436: GenericValue userLogin = (GenericValue) session
1437: .getAttribute("userLogin");
1438: Locale locale = UtilHttp.getLocale(request);
1439:
1440: String productStoreId = request.getParameter("productStoreId");
1441:
1442: if (UtilValidate.isNotEmpty(productStoreId)) {
1443: session.setAttribute("productStoreId", productStoreId);
1444: }
1445: ShoppingCart cart = getCartObject(request);
1446:
1447: // TODO: re-factor and move this inside the ShoppingCart constructor
1448: String orderMode = request.getParameter("orderMode");
1449: if (orderMode != null) {
1450: cart.setOrderType(orderMode);
1451: session.setAttribute("orderMode", orderMode);
1452: } else {
1453: request
1454: .setAttribute(
1455: "_ERROR_MESSAGE_",
1456: UtilProperties
1457: .getMessage(
1458: resource_error,
1459: "OrderPleaseSelectEitherSaleOrPurchaseOrder",
1460: locale));
1461: return "error";
1462: }
1463:
1464: // check the selected product store
1465: GenericValue productStore = null;
1466: if (UtilValidate.isNotEmpty(productStoreId)) {
1467: productStore = ProductStoreWorker.getProductStore(
1468: productStoreId, delegator);
1469: if (productStore != null) {
1470:
1471: // check permission for taking the order
1472: boolean hasPermission = false;
1473: if ((cart.getOrderType().equals("PURCHASE_ORDER"))
1474: && (security.hasEntityPermission("ORDERMGR",
1475: "_PURCHASE_CREATE", session))) {
1476: hasPermission = true;
1477: } else if (cart.getOrderType().equals("SALES_ORDER")) {
1478: if (security.hasEntityPermission("ORDERMGR",
1479: "_SALES_CREATE", session)) {
1480: hasPermission = true;
1481: } else {
1482: // if the user is a rep of the store, then he also has permission
1483: List storeReps = null;
1484: try {
1485: storeReps = delegator
1486: .findByAnd(
1487: "ProductStoreRole",
1488: UtilMisc
1489: .toMap(
1490: "productStoreId",
1491: productStore
1492: .getString("productStoreId"),
1493: "partyId",
1494: userLogin
1495: .getString("partyId"),
1496: "roleTypeId",
1497: "SALES_REP"));
1498: } catch (GenericEntityException gee) {
1499: //
1500: }
1501: storeReps = EntityUtil.filterByDate(storeReps);
1502: if (storeReps != null && storeReps.size() > 0) {
1503: hasPermission = true;
1504: }
1505: }
1506: }
1507:
1508: if (hasPermission) {
1509: cart = ShoppingCartEvents.getCartObject(request,
1510: null, productStore
1511: .getString("defaultCurrencyUomId"));
1512: } else {
1513: request
1514: .setAttribute(
1515: "_ERROR_MESSAGE_",
1516: UtilProperties
1517: .getMessage(
1518: resource_error,
1519: "OrderYouDoNotHavePermissionToTakeOrdersForThisStore",
1520: locale));
1521: cart.clear();
1522: session.removeAttribute("orderMode");
1523: return "error";
1524: }
1525: cart.setProductStoreId(productStoreId);
1526: } else {
1527: cart.setProductStoreId(null);
1528: }
1529: }
1530:
1531: if ("SALES_ORDER".equals(cart.getOrderType())
1532: && UtilValidate.isEmpty(cart.getProductStoreId())) {
1533: request
1534: .setAttribute(
1535: "_ERROR_MESSAGE_",
1536: UtilProperties
1537: .getMessage(
1538: resource_error,
1539: "OrderAProductStoreMustBeSelectedForASalesOrder",
1540: locale));
1541: cart.clear();
1542: session.removeAttribute("orderMode");
1543: return "error";
1544: }
1545:
1546: String salesChannelEnumId = request
1547: .getParameter("salesChannelEnumId");
1548: if (UtilValidate.isNotEmpty(salesChannelEnumId)) {
1549: cart.setChannelType(salesChannelEnumId);
1550: }
1551:
1552: // set party info
1553: String partyId = request.getParameter("supplierPartyId");
1554: if (!UtilValidate.isEmpty(request.getParameter("partyId"))) {
1555: partyId = request.getParameter("partyId");
1556: }
1557: String userLoginId = request.getParameter("userLoginId");
1558: if (partyId != null || userLoginId != null) {
1559: if ((partyId == null || partyId.length() == 0)
1560: && userLoginId != null && userLoginId.length() > 0) {
1561: GenericValue this UserLogin = null;
1562: try {
1563: this UserLogin = delegator.findByPrimaryKey(
1564: "UserLogin", UtilMisc.toMap("userLoginId",
1565: userLoginId));
1566: } catch (GenericEntityException gee) {
1567: //
1568: }
1569: if (this UserLogin != null) {
1570: partyId = this UserLogin.getString("partyId");
1571: } else {
1572: partyId = userLoginId;
1573: }
1574: }
1575: if (partyId != null && partyId.length() > 0) {
1576: GenericValue this Party = null;
1577: try {
1578: this Party = delegator.findByPrimaryKey("Party",
1579: UtilMisc.toMap("partyId", partyId));
1580: } catch (GenericEntityException gee) {
1581: //
1582: }
1583: if (this Party == null) {
1584: request
1585: .setAttribute(
1586: "_ERROR_MESSAGE_",
1587: UtilProperties
1588: .getMessage(
1589: resource_error,
1590: "OrderCouldNotLocateTheSelectedParty",
1591: locale));
1592: return "error";
1593: } else {
1594: cart.setOrderPartyId(partyId);
1595: }
1596: } else if (partyId != null && partyId.length() == 0) {
1597: cart.setOrderPartyId("_NA_");
1598: partyId = null;
1599: }
1600: } else {
1601: partyId = cart.getPartyId();
1602: if (partyId != null && partyId.equals("_NA_"))
1603: partyId = null;
1604: }
1605:
1606: return "success";
1607: }
1608:
1609: /** Route order entry **/
1610: public static String routeOrderEntry(HttpServletRequest request,
1611: HttpServletResponse response) {
1612: HttpSession session = request.getSession();
1613:
1614: // if the order mode is not set in the attributes, then order entry has not been initialized
1615: if (session.getAttribute("orderMode") == null) {
1616: return "init";
1617: }
1618:
1619: // if the request is coming from the init page, then orderMode will be in the request parameters
1620: if (request.getParameter("orderMode") != null) {
1621: return "agreements"; // next page after init is always agreements
1622: }
1623:
1624: // orderMode is set and there is an order in progress, so go straight to the cart
1625: return "cart";
1626: }
1627:
1628: public static String doManualPromotions(HttpServletRequest request,
1629: HttpServletResponse response) {
1630: LocalDispatcher dispatcher = (LocalDispatcher) request
1631: .getAttribute("dispatcher");
1632: GenericDelegator delegator = (GenericDelegator) request
1633: .getAttribute("delegator");
1634: ShoppingCart cart = getCartObject(request);
1635: List manualPromotions = new LinkedList();
1636:
1637: // iterate through the context and find all keys that start with "productPromoId_"
1638: Map context = UtilHttp.getParameterMap(request);
1639: String keyPrefix = "productPromoId_";
1640: for (int i = 1; i <= 50; i++) {
1641: String productPromoId = (String) context.get(keyPrefix + i);
1642: if (UtilValidate.isNotEmpty(productPromoId)) {
1643: try {
1644: GenericValue promo = delegator.findByPrimaryKey(
1645: "ProductPromo", UtilMisc.toMap(
1646: "productPromoId", productPromoId));
1647: if (promo != null) {
1648: manualPromotions.add(promo);
1649: }
1650: } catch (GenericEntityException gee) {
1651: request.setAttribute("_ERROR_MESSAGE_", gee
1652: .getMessage());
1653: return "error";
1654: }
1655: } else {
1656: break;
1657: }
1658: }
1659: ProductPromoWorker.doPromotions(cart, manualPromotions,
1660: dispatcher);
1661: return "success";
1662: }
1663:
1664: public static String bulkAddProducts(HttpServletRequest request,
1665: HttpServletResponse response) {
1666: GenericDelegator delegator = (GenericDelegator) request
1667: .getAttribute("delegator");
1668: LocalDispatcher dispatcher = (LocalDispatcher) request
1669: .getAttribute("dispatcher");
1670: ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
1671: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
1672: delegator, dispatcher, cart);
1673: String controlDirective = null;
1674: Map result = null;
1675: String productId = null;
1676: String productCategoryId = null;
1677: String quantityStr = null;
1678: String itemDesiredDeliveryDateStr = null;
1679: double quantity = 0;
1680: String catalogId = CatalogWorker.getCurrentCatalogId(request);
1681: String itemType = null;
1682: String itemDescription = "";
1683:
1684: String rowCountField = null;
1685: int rowCount = 0; // number of rows of products to add
1686: String DELIMITER = "_o_"; // delimiter, separating field from row number
1687:
1688: // Get the parameters as a MAP, remove the productId and quantity params.
1689: Map paramMap = UtilHttp.getParameterMap(request);
1690:
1691: String itemGroupNumber = request
1692: .getParameter("itemGroupNumber");
1693:
1694: // Get shoppingList info if passed. I think there can only be one shoppingList per request
1695: String shoppingListId = request.getParameter("shoppingListId");
1696: String shoppingListItemSeqId = request
1697: .getParameter("shoppingListItemSeqId");
1698:
1699: // try to get the rowCount information passed in from request
1700: if (paramMap.containsKey("_rowCount")) {
1701: rowCountField = (String) paramMap.remove("_rowCount");
1702: } else {
1703: Debug.logWarning("No _rowCount was passed in",
1704: ShoppingCartEvents.module);
1705: }
1706: try {
1707: rowCount = Integer.parseInt(rowCountField);
1708: } catch (NumberFormatException e) {
1709: Debug.logWarning("Invalid value for rowCount ="
1710: + rowCountField, module);
1711: }
1712:
1713: if (rowCount < 1) {
1714: Debug.logWarning("No rows to process, as rowCount = "
1715: + rowCount, module);
1716: } else {
1717: for (int i = 0; i < rowCount; i++) {
1718: controlDirective = null; // re-initialize each time
1719: String this Suffix = DELIMITER + i; // current suffix after each field id
1720:
1721: // get the productId
1722: if (paramMap.containsKey("productId" + this Suffix)) {
1723: productId = (String) paramMap.remove("productId"
1724: + this Suffix);
1725: }
1726:
1727: if (paramMap.containsKey("quantity" + this Suffix)) {
1728: quantityStr = (String) paramMap.remove("quantity"
1729: + this Suffix);
1730: }
1731: if ((quantityStr == null) || (quantityStr.equals(""))) { // otherwise, every empty value causes an exception and makes the log ugly
1732: quantityStr = "0"; // default quantity is 0, so without a quantity input, this field will not be added
1733: }
1734:
1735: // parse the quantity
1736: try {
1737: quantity = NumberFormat.getNumberInstance().parse(
1738: quantityStr).doubleValue();
1739: } catch (Exception e) {
1740: Debug.logWarning(e,
1741: "Problems parsing quantity string: "
1742: + quantityStr, module);
1743: quantity = 0;
1744: }
1745:
1746: // get the selected amount
1747: String selectedAmountStr = "0.00";
1748: if (paramMap.containsKey("amount" + this Suffix)) {
1749: selectedAmountStr = (String) paramMap
1750: .remove("amount" + this Suffix);
1751: }
1752:
1753: // parse the amount
1754: Double amount = null;
1755: if (selectedAmountStr != null
1756: && selectedAmountStr.length() > 0) {
1757: try {
1758: amount = new Double(NumberFormat
1759: .getNumberInstance().parse(
1760: selectedAmountStr)
1761: .doubleValue());
1762: } catch (Exception e) {
1763: Debug.logWarning(e,
1764: "Problem parsing amount string: "
1765: + selectedAmountStr, module);
1766: amount = null;
1767: }
1768: }
1769:
1770: if (paramMap.containsKey("itemDesiredDeliveryDate"
1771: + this Suffix)) {
1772: itemDesiredDeliveryDateStr = (String) paramMap
1773: .remove("itemDesiredDeliveryDate"
1774: + this Suffix);
1775: }
1776: // get the item type
1777: if (paramMap.containsKey("itemType" + this Suffix)) {
1778: itemType = (String) paramMap.remove("itemType"
1779: + this Suffix);
1780: }
1781:
1782: if (paramMap
1783: .containsKey("itemDescription" + this Suffix)) {
1784: itemDescription = (String) paramMap
1785: .remove("itemDescription" + this Suffix);
1786: }
1787:
1788: Map itemAttributes = UtilMisc.toMap(
1789: "itemDesiredDeliveryDate",
1790: itemDesiredDeliveryDateStr);
1791:
1792: if (quantity > 0) {
1793: Debug.logInfo(
1794: "Attempting to add to cart with productId = "
1795: + productId + ", categoryId = "
1796: + productCategoryId
1797: + ", quantity = " + quantity
1798: + ", itemType = " + itemType
1799: + " and itemDescription = "
1800: + itemDescription, module);
1801: result = cartHelper.addToCart(catalogId,
1802: shoppingListId, shoppingListItemSeqId,
1803: productId, productCategoryId, itemType,
1804: itemDescription, null, amount, quantity,
1805: null, null, null, null, null, null,
1806: itemGroupNumber, itemAttributes, null);
1807: // no values for price and paramMap (a context for adding attributes)
1808: controlDirective = processResult(result, request);
1809: if (controlDirective.equals(ERROR)) { // if the add to cart failed, then get out of this loop right away
1810: return "error";
1811: }
1812: }
1813: }
1814: }
1815:
1816: // Determine where to send the browser
1817: return cart.viewCartOnAdd() ? "viewcart" : "success";
1818: }
1819:
1820: // request method for setting the currency, agreement and shipment dates at once
1821: public static String setOrderCurrencyAgreementShipDates(
1822: HttpServletRequest request, HttpServletResponse response) {
1823: LocalDispatcher dispatcher = (LocalDispatcher) request
1824: .getAttribute("dispatcher");
1825: GenericDelegator delegator = (GenericDelegator) request
1826: .getAttribute("delegator");
1827: ShoppingCart cart = getCartObject(request);
1828: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
1829: delegator, dispatcher, cart);
1830:
1831: String agreementId = request.getParameter("agreementId");
1832: String currencyUomId = request.getParameter("currencyUomId");
1833: String shipBeforeDateStr = request
1834: .getParameter("shipBeforeDate");
1835: String shipAfterDateStr = request.getParameter("shipAfterDate");
1836: String orderName = request.getParameter("orderName");
1837: String correspondingPoId = request
1838: .getParameter("correspondingPoId");
1839: Map result = null;
1840:
1841: // set the agreement if specified otherwise set the currency
1842: if (agreementId != null && agreementId.length() > 0) {
1843: result = cartHelper.selectAgreement(agreementId);
1844: } else {
1845: result = cartHelper.setCurrency(currencyUomId);
1846: }
1847: if (ServiceUtil.isError(result)) {
1848: request.setAttribute("_ERROR_MESSAGE_", ServiceUtil
1849: .getErrorMessage(result));
1850: return "error";
1851: }
1852:
1853: // set the order name
1854: cart.setOrderName(orderName);
1855:
1856: // set the corresponding purchase order id
1857: cart.setPoNumber(correspondingPoId);
1858:
1859: // set the default ship before and after dates if supplied
1860: try {
1861: if (UtilValidate.isNotEmpty(shipBeforeDateStr)) {
1862: if (shipBeforeDateStr.length() == 10)
1863: shipBeforeDateStr += " 00:00:00.000";
1864: cart.setDefaultShipBeforeDate(java.sql.Timestamp
1865: .valueOf(shipBeforeDateStr));
1866: }
1867: if (UtilValidate.isNotEmpty(shipAfterDateStr)) {
1868: if (shipAfterDateStr.length() == 10)
1869: shipAfterDateStr += " 00:00:00.000";
1870: cart.setDefaultShipAfterDate(java.sql.Timestamp
1871: .valueOf(shipAfterDateStr));
1872: }
1873: } catch (IllegalArgumentException e) {
1874: request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
1875: return "error";
1876: }
1877: return "success";
1878: }
1879: }
|