001: /*
002: * $Id: ShoppingCartEvents.java,v 1.12 2003/12/05 23:07:13 ajzeneski Exp $
003: *
004: * Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
005: *
006: * Permission is hereby granted, free of charge, to any person obtaining a
007: * copy of this software and associated documentation files (the "Software"),
008: * to deal in the Software without restriction, including without limitation
009: * the rights to use, copy, modify, merge, publish, distribute, sublicense,
010: * and/or sell copies of the Software, and to permit persons to whom the
011: * Software is furnished to do so, subject to the following conditions:
012: *
013: * The above copyright notice and this permission notice shall be included
014: * in all copies or substantial portions of the Software.
015: *
016: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
017: * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
018: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
019: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
020: * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
021: * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
022: * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023: */
024: package org.ofbiz.order.shoppingcart;
025:
026: import java.text.NumberFormat;
027: import java.util.Iterator;
028: import java.util.List;
029: import java.util.Map;
030: import java.util.Locale;
031:
032: import javax.servlet.http.HttpServletRequest;
033: import javax.servlet.http.HttpServletResponse;
034: import javax.servlet.http.HttpSession;
035:
036: import org.ofbiz.base.util.*;
037: import org.ofbiz.entity.GenericDelegator;
038: import org.ofbiz.entity.GenericValue;
039: import org.ofbiz.entity.util.EntityUtil;
040: import org.ofbiz.product.catalog.CatalogWorker;
041: import org.ofbiz.product.store.ProductStoreWorker;
042: import org.ofbiz.product.store.ProductStoreSurveyWrapper;
043: import org.ofbiz.security.Security;
044: import org.ofbiz.service.LocalDispatcher;
045: import org.ofbiz.service.ModelService;
046: import org.ofbiz.content.webapp.control.RequestHandler;
047:
048: /**
049: * Shopping cart events.
050: *
051: * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
052: * @author <a href="mailto:tristana@twibble.org">Tristan Austin</a>
053: * @version $Revision: 1.12 $
054: * @since 2.0
055: */
056: public class ShoppingCartEvents {
057:
058: public static String module = ShoppingCartEvents.class.getName();
059: public static final String resource = "OrderUiLabels";
060:
061: private static final String NO_ERROR = "noerror";
062: private static final String NON_CRITICAL_ERROR = "noncritical";
063: private static final String ERROR = "error";
064:
065: public static String addProductPromoCode(
066: HttpServletRequest request, HttpServletResponse response) {
067: LocalDispatcher dispatcher = (LocalDispatcher) request
068: .getAttribute("dispatcher");
069: ShoppingCart cart = getCartObject(request);
070: String productPromoCodeId = request
071: .getParameter("productPromoCodeId");
072: if (UtilValidate.isNotEmpty(productPromoCodeId)) {
073: String checkResult = cart.addProductPromoCode(
074: productPromoCodeId, dispatcher);
075: if (UtilValidate.isNotEmpty(checkResult)) {
076: request.setAttribute("_ERROR_MESSAGE_", checkResult);
077: return "error";
078: }
079: }
080: return "success";
081: }
082:
083: /** Event to add an item to the shopping cart. */
084: public static String addToCart(HttpServletRequest request,
085: HttpServletResponse response) {
086: GenericDelegator delegator = (GenericDelegator) request
087: .getAttribute("delegator");
088: LocalDispatcher dispatcher = (LocalDispatcher) request
089: .getAttribute("dispatcher");
090: ShoppingCart cart = getCartObject(request);
091: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
092: delegator, dispatcher, cart);
093: String controlDirective = null;
094: Map result = null;
095: String productId = null;
096: String itemType = null;
097: String itemDescription = null;
098: String productCategoryId = null;
099: String priceStr = null;
100: double price = 0.00;
101:
102: String quantityStr = null;
103: double quantity = 0;
104: // not used right now: Map attributes = null;
105: String catalogId = CatalogWorker.getCurrentCatalogId(request);
106: Locale locale = UtilHttp.getLocale(request);
107:
108: // Get the parameters as a MAP, remove the productId and quantity params.
109: Map paramMap = UtilHttp.getParameterMap(request);
110:
111: // Get shoppingList info if passed
112: String shoppingListId = request.getParameter("shoppingListId");
113: String shoppingListItemSeqId = request
114: .getParameter("shoppingListItemSeqId");
115:
116: if (paramMap.containsKey("ADD_PRODUCT_ID")) {
117: productId = (String) paramMap.remove("ADD_PRODUCT_ID");
118: } else if (paramMap.containsKey("add_product_id")) {
119: productId = (String) paramMap.remove("add_product_id");
120: }
121:
122: if (paramMap.containsKey("ADD_CATEGORY_ID")) {
123: productCategoryId = (String) paramMap
124: .remove("ADD_CATEGORY_ID");
125: } else if (paramMap.containsKey("add_category_id")) {
126: productCategoryId = (String) paramMap
127: .remove("add_category_id");
128: }
129: if (productCategoryId != null
130: && productCategoryId.length() == 0) {
131: productCategoryId = null;
132: }
133:
134: if (productId == null) {
135: // before returning error; check make sure we aren't adding a special item type
136: if (paramMap.containsKey("ADD_ITEM_TYPE")) {
137: itemType = (String) paramMap.remove("ADD_ITEM_TYPE");
138: } else if (paramMap.containsKey("add_item_type")) {
139: itemType = (String) paramMap.remove("add_item_type");
140: } else {
141: request.setAttribute("_ERROR_MESSAGE_", UtilProperties
142: .getMessage(resource,
143: "cart.addToCart.noProductInfoPassed",
144: locale));
145: return "success"; // not critical return to same page
146: }
147: }
148:
149: // check for an itemDescription
150: if (paramMap.containsKey("ADD_ITEM_DESCRIPTION")) {
151: itemDescription = (String) paramMap
152: .remove("ADD_ITEM_DESCRIPTION");
153: } else if (paramMap.containsKey("add_item_description")) {
154: itemDescription = (String) paramMap
155: .remove("add_item_description");
156: }
157: if (itemDescription != null && itemDescription.length() == 0) {
158: itemDescription = null;
159: }
160:
161: // get the override price
162: if (paramMap.containsKey("PRICE")) {
163: priceStr = (String) paramMap.remove("PRICE");
164: } else if (paramMap.containsKey("price")) {
165: priceStr = (String) paramMap.remove("price");
166: }
167: if (priceStr == null) {
168: priceStr = "0.00"; // default price is 0.00
169: }
170:
171: // get the quantity
172: if (paramMap.containsKey("QUANTITY")) {
173: quantityStr = (String) paramMap.remove("QUANTITY");
174: } else if (paramMap.containsKey("quantity")) {
175: quantityStr = (String) paramMap.remove("quantity");
176: }
177: if (quantityStr == null) {
178: quantityStr = "1"; // default quantity is 1
179: }
180:
181: // parse the price
182: try {
183: price = NumberFormat.getNumberInstance().parse(priceStr)
184: .doubleValue();
185: } catch (Exception e) {
186: Debug.logWarning(e, "Problems parsing price string: "
187: + priceStr, module);
188: price = 0.00;
189: }
190:
191: // parse the quantity
192: try {
193: quantity = NumberFormat.getNumberInstance().parse(
194: quantityStr).doubleValue();
195: } catch (Exception e) {
196: Debug.logWarning(e, "Problems parsing quantity string: "
197: + quantityStr, module);
198: quantity = 1;
199: }
200:
201: // get the selected amount
202: String selectedAmountStr = "0.00";
203: if (paramMap.containsKey("ADD_AMOUNT")) {
204: selectedAmountStr = (String) paramMap.remove("ADD_AMOUNT");
205: } else if (paramMap.containsKey("add_amount")) {
206: selectedAmountStr = (String) paramMap.remove("add_amount");
207: }
208:
209: // parse the amount
210: double amount = 0.00;
211: if (selectedAmountStr != null && selectedAmountStr.length() > 0) {
212: try {
213: amount = NumberFormat.getNumberInstance().parse(
214: selectedAmountStr).doubleValue();
215: } catch (Exception e) {
216: Debug.logWarning(e, "Problem parsing amount string: "
217: + selectedAmountStr, module);
218: amount = 0.00;
219: }
220: }
221:
222: // check for an add-to cart survey
223: List surveyResponses = null;
224: if (productId != null) {
225: String productStoreId = ProductStoreWorker
226: .getProductStoreId(request);
227: List productSurvey = ProductStoreWorker.getProductSurveys(
228: delegator, productStoreId, productId, "CART_ADD");
229: if (productSurvey != null && productSurvey.size() > 0) {
230: // TODO: implement multiple survey per product
231: GenericValue survey = EntityUtil
232: .getFirst(productSurvey);
233: String surveyResponseId = (String) request
234: .getAttribute("surveyResponseId");
235: if (surveyResponseId != null) {
236: surveyResponses = UtilMisc.toList(surveyResponseId);
237: } else {
238: Map surveyContext = UtilHttp
239: .getParameterMap(request);
240: GenericValue userLogin = cart.getUserLogin();
241: String partyId = null;
242: if (userLogin != null) {
243: partyId = userLogin.getString("partyId");
244: }
245: String formAction = "/additemsurvey";
246: String nextPage = RequestHandler
247: .getNextPageUri(request.getPathInfo());
248: if (nextPage != null) {
249: formAction = formAction + "/" + nextPage;
250: }
251: ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(
252: survey, partyId, surveyContext);
253: request.setAttribute("surveyWrapper", wrapper);
254: request.setAttribute("surveyAction", formAction); // will be used as the form action of the survey
255: return "survey";
256: }
257: }
258: }
259: if (surveyResponses != null) {
260: paramMap.put("surveyResponses", surveyResponses);
261: }
262:
263: // Translate the parameters and add to the cart
264: result = cartHelper.addToCart(catalogId, shoppingListId,
265: shoppingListItemSeqId, productId, productCategoryId,
266: itemType, itemDescription, price, amount, quantity,
267: paramMap);
268: controlDirective = processResult(result, request);
269:
270: // Determine where to send the browser
271: if (controlDirective.equals(NON_CRITICAL_ERROR)) {
272: return "success";
273: } else if (controlDirective.equals(ERROR)) {
274: return "error";
275: } else if (cart.viewCartOnAdd()) {
276: return "viewcart";
277: } else {
278: return "success";
279: }
280: }
281:
282: public static String addToCartFromOrder(HttpServletRequest request,
283: HttpServletResponse response) {
284: String orderId = request.getParameter("order_id");
285: String[] itemIds = request.getParameterValues("item_id");
286: // not used yet: Locale locale = UtilHttp.getLocale(request);
287:
288: ShoppingCart cart = getCartObject(request);
289: GenericDelegator delegator = (GenericDelegator) request
290: .getAttribute("delegator");
291: LocalDispatcher dispatcher = (LocalDispatcher) request
292: .getAttribute("dispatcher");
293: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
294: delegator, dispatcher, cart);
295: String catalogId = CatalogWorker.getCurrentCatalogId(request);
296: Map result;
297: String controlDirective;
298:
299: boolean addAll = ("true"
300: .equals(request.getParameter("add_all")));
301: result = cartHelper.addToCartFromOrder(catalogId, orderId,
302: itemIds, addAll);
303: controlDirective = processResult(result, request);
304:
305: //Determine where to send the browser
306: if (controlDirective.equals(ERROR)) {
307: return "error";
308: } else {
309: return "success";
310: }
311: }
312:
313: /** Adds all products in a category according to quantity request parameter
314: * for each; if no parameter for a certain product in the category, or if
315: * quantity is 0, do not add
316: */
317: public static String addToCartBulk(HttpServletRequest request,
318: HttpServletResponse response) {
319: String categoryId = request.getParameter("category_id");
320: ShoppingCart cart = getCartObject(request);
321: GenericDelegator delegator = (GenericDelegator) request
322: .getAttribute("delegator");
323: LocalDispatcher dispatcher = (LocalDispatcher) request
324: .getAttribute("dispatcher");
325: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
326: delegator, dispatcher, cart);
327: String controlDirective;
328: Map result;
329: // not used yet: Locale locale = UtilHttp.getLocale(request);
330:
331: //Convert the params to a map to pass in
332: Map paramMap = UtilHttp.getParameterMap(request);
333: String catalogId = CatalogWorker.getCurrentCatalogId(request);
334: result = cartHelper.addToCartBulk(catalogId, categoryId,
335: paramMap);
336: controlDirective = processResult(result, request);
337:
338: //Determine where to send the browser
339: if (controlDirective.equals(ERROR)) {
340: return "error";
341: } else {
342: return "success";
343: }
344: }
345:
346: /** Adds all products in a category according to default quantity on ProductCategoryMember
347: * for each; if no default for a certain product in the category, or if
348: * quantity is 0, do not add
349: */
350: public static String addCategoryDefaults(
351: HttpServletRequest request, HttpServletResponse response) {
352: String categoryId = request.getParameter("category_id");
353: String catalogId = CatalogWorker.getCurrentCatalogId(request);
354: ShoppingCart cart = getCartObject(request);
355: GenericDelegator delegator = (GenericDelegator) request
356: .getAttribute("delegator");
357: LocalDispatcher dispatcher = (LocalDispatcher) request
358: .getAttribute("dispatcher");
359: ShoppingCartHelper cartHelper = new ShoppingCartHelper(
360: delegator, dispatcher, cart);
361: String controlDirective;
362: Map result;
363: Double totalQuantity;
364: Locale locale = UtilHttp.getLocale(request);
365:
366: result = cartHelper.addCategoryDefaults(catalogId, categoryId);
367: controlDirective = processResult(result, request);
368:
369: //Determine where to send the browser
370: if (controlDirective.equals(ERROR)) {
371: return "error";
372: } else {
373: totalQuantity = (Double) result.get("totalQuantity");
374: Map messageMap = UtilMisc.toMap("totalQuantity",
375: UtilFormatOut.formatQuantity(totalQuantity));
376:
377: request.setAttribute("_EVENT_MESSAGE_", UtilProperties
378: .getMessage(resource, "cart.add_category_defaults",
379: messageMap, locale));
380:
381: return "success";
382: }
383: }
384:
385: /** Delete an item from the shopping cart. */
386: public static String deleteFromCart(HttpServletRequest request,
387: HttpServletResponse response) {
388: ShoppingCart cart = getCartObject(request);
389: LocalDispatcher dispatcher = (LocalDispatcher) request
390: .getAttribute("dispatcher");
391: ShoppingCartHelper cartHelper = new ShoppingCartHelper(null,
392: dispatcher, cart);
393: String controlDirective;
394: Map result;
395: Map paramMap = UtilHttp.getParameterMap(request);
396: // not used yet: Locale locale = UtilHttp.getLocale(request);
397:
398: //Delegate the cart helper
399: result = cartHelper.deleteFromCart(paramMap);
400: controlDirective = processResult(result, request);
401:
402: //Determine where to send the browser
403: if (controlDirective.equals(ERROR)) {
404: return "error";
405: } else {
406: return "success";
407: }
408: }
409:
410: /** Update the items in the shopping cart. */
411: public static String modifyCart(HttpServletRequest request,
412: HttpServletResponse response) {
413: HttpSession session = request.getSession();
414: ShoppingCart cart = getCartObject(request);
415: GenericValue userLogin = (GenericValue) session
416: .getAttribute("userLogin");
417: LocalDispatcher dispatcher = (LocalDispatcher) request
418: .getAttribute("dispatcher");
419: Security security = (Security) request.getAttribute("security");
420: ShoppingCartHelper cartHelper = new ShoppingCartHelper(null,
421: dispatcher, cart);
422: String controlDirective;
423: Map result;
424: // not used yet: Locale locale = UtilHttp.getLocale(request);
425:
426: Map paramMap = UtilHttp.getParameterMap(request);
427:
428: String removeSelectedFlag = request
429: .getParameter("removeSelected");
430: String selectedItems[] = request
431: .getParameterValues("selectedItem");
432: boolean removeSelected = ("true".equals(removeSelectedFlag)
433: && selectedItems != null && selectedItems.length > 0);
434: result = cartHelper.modifyCart(security, userLogin, paramMap,
435: removeSelected, selectedItems);
436: controlDirective = processResult(result, request);
437:
438: //Determine where to send the browser
439: if (controlDirective.equals(ERROR)) {
440: return "error";
441: } else {
442: return "success";
443: }
444: }
445:
446: /** Empty the shopping cart. */
447: public static String clearCart(HttpServletRequest request,
448: HttpServletResponse response) {
449: ShoppingCart cart = getCartObject(request);
450: cart.clear();
451: return "success";
452: }
453:
454: /** Totally wipe out the cart, removes all stored info. */
455: public static String destroyCart(HttpServletRequest request,
456: HttpServletResponse response) {
457: HttpSession session = request.getSession();
458: clearCart(request, response);
459: session.removeAttribute("shoppingCart");
460: session.removeAttribute("orderPartyId");
461: session.removeAttribute("orderMode");
462: return "success";
463: }
464:
465: /** Gets the shopping cart from the session. Used by all events. */
466: public static ShoppingCart getCartObject(HttpServletRequest request) {
467: HttpSession session = request.getSession(true);
468: ShoppingCart cart = (ShoppingCart) session
469: .getAttribute("shoppingCart");
470:
471: if (cart == null) {
472: cart = new WebShoppingCart(request);
473: session.setAttribute("shoppingCart", cart);
474: }
475: return cart;
476: }
477:
478: /**
479: * This should be called to translate the error messages of the
480: * <code>ShoppingCartHelper</code> to an appropriately formatted
481: * <code>String</code> in the request object and indicate whether
482: * the result was an error or not and whether the errors were
483: * critical or not
484: *
485: * @param result The result returned from the
486: * <code>ShoppingCartHelper</code>
487: * @param request The servlet request instance to set the error messages
488: * in
489: * @return one of NON_CRITICAL_ERROR, ERROR or NO_ERROR.
490: */
491: private static String processResult(Map result,
492: HttpServletRequest request) {
493: //Check for errors
494: StringBuffer errMsg = new StringBuffer();
495: if (result.containsKey(ModelService.ERROR_MESSAGE_LIST)) {
496: List errorMsgs = (List) result
497: .get(ModelService.ERROR_MESSAGE_LIST);
498: Iterator iterator = errorMsgs.iterator();
499: errMsg.append("<ul>");
500: while (iterator.hasNext()) {
501: errMsg.append("<li>");
502: errMsg.append(iterator.next());
503: errMsg.append("</li>");
504: }
505: errMsg.append("</ul>");
506: } else if (result.containsKey(ModelService.ERROR_MESSAGE)) {
507: errMsg.append(result.get(ModelService.ERROR_MESSAGE));
508: request.setAttribute("_ERROR_MESSAGE_", errMsg.toString());
509: }
510:
511: //See whether there was an error
512: if (errMsg.length() > 0) {
513: request.setAttribute("_ERROR_MESSAGE_", errMsg.toString());
514: if (result.get(ModelService.RESPONSE_MESSAGE).equals(
515: ModelService.RESPOND_SUCCESS)) {
516: return NON_CRITICAL_ERROR;
517: } else {
518: return ERROR;
519: }
520: } else {
521: return NO_ERROR;
522: }
523: }
524: }
|