0001: /*
0002: * $Id: CheckOutEvents.java,v 1.28 2004/03/08 19:57:56 ajzeneski Exp $
0003: *
0004: * Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
0005: *
0006: * Permission is hereby granted, free of charge, to any person obtaining a
0007: * copy of this software and associated documentation files (the "Software"),
0008: * to deal in the Software without restriction, including without limitation
0009: * the rights to use, copy, modify, merge, publish, distribute, sublicense,
0010: * and/or sell copies of the Software, and to permit persons to whom the
0011: * Software is furnished to do so, subject to the following conditions:
0012: *
0013: * The above copyright notice and this permission notice shall be included
0014: * in all copies or substantial portions of the Software.
0015: *
0016: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
0017: * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
0018: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
0019: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
0020: * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
0021: * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
0022: * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0023: */
0024: package org.ofbiz.order.shoppingcart;
0025:
0026: import java.text.DecimalFormat;
0027: import java.text.ParseException;
0028: import java.util.ArrayList;
0029: import java.util.HashMap;
0030: import java.util.Iterator;
0031: import java.util.List;
0032: import java.util.Locale;
0033: import java.util.Map;
0034:
0035: import javax.servlet.ServletContext;
0036: import javax.servlet.http.HttpServletRequest;
0037: import javax.servlet.http.HttpServletResponse;
0038: import javax.servlet.http.HttpSession;
0039:
0040: import org.ofbiz.base.util.Debug;
0041: import org.ofbiz.base.util.GeneralException;
0042: import org.ofbiz.base.util.GeneralRuntimeException;
0043: import org.ofbiz.base.util.UtilHttp;
0044: import org.ofbiz.base.util.UtilMisc;
0045: import org.ofbiz.base.util.UtilProperties;
0046: import org.ofbiz.content.stats.VisitHandler;
0047: import org.ofbiz.entity.GenericDelegator;
0048: import org.ofbiz.entity.GenericEntityException;
0049: import org.ofbiz.entity.GenericValue;
0050: import org.ofbiz.marketing.tracking.TrackingCodeEvents;
0051: import org.ofbiz.product.catalog.CatalogWorker;
0052: import org.ofbiz.product.store.ProductStoreWorker;
0053: import org.ofbiz.service.GenericServiceException;
0054: import org.ofbiz.service.LocalDispatcher;
0055: import org.ofbiz.service.ModelService;
0056: import org.ofbiz.service.ServiceUtil;
0057:
0058: /**
0059: * Events used for processing checkout and orders.
0060: *
0061: * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
0062: * @author <a href="mailto:cnelson@einnovation.com">Chris Nelson</a>
0063: * @author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
0064: * @author <a href="mailto:tristana@twibble.org">Tristan Austin</a>
0065: * @version $Revision: 1.28 $
0066: * @since 2.0
0067: */
0068: public class CheckOutEvents {
0069:
0070: public static final String module = CheckOutEvents.class.getName();
0071: public static final String resource = "OrderUiLabels";
0072:
0073: public static String cartNotEmpty(HttpServletRequest request,
0074: HttpServletResponse response) {
0075: ShoppingCart cart = (ShoppingCart) request.getSession()
0076: .getAttribute("shoppingCart");
0077: Locale locale = UtilHttp.getLocale(request);
0078: String errMsg = null;
0079:
0080: if (cart != null && cart.size() > 0) {
0081: return "success";
0082: } else {
0083: errMsg = UtilProperties.getMessage(resource,
0084: "checkevents.cart_empty", (cart != null ? cart
0085: .getLocale() : Locale.getDefault()));
0086: request.setAttribute("_ERROR_MESSAGE_", errMsg);
0087: return "error";
0088: }
0089: }
0090:
0091: public static String cancelOrderItem(HttpServletRequest request,
0092: HttpServletResponse response) {
0093: ShoppingCart cart = (ShoppingCart) request.getSession()
0094: .getAttribute("shoppingCart");
0095: LocalDispatcher dispatcher = (LocalDispatcher) request
0096: .getAttribute("dispatcher");
0097: GenericValue userLogin = (GenericValue) request.getSession()
0098: .getAttribute("userLogin");
0099: String orderId = request.getParameter("order_id");
0100: String itemSeqId = request.getParameter("item_seq");
0101: Locale locale = UtilHttp.getLocale(request);
0102:
0103: Map fields = UtilMisc.toMap("orderId", orderId,
0104: "orderItemSeqId", itemSeqId, "userLogin", userLogin);
0105: Map result = null;
0106: String errMsg = null;
0107:
0108: try {
0109: result = dispatcher.runSync("cancelOrderItem", fields);
0110: } catch (GenericServiceException e) {
0111: Debug.logError(e, module);
0112: errMsg = UtilProperties.getMessage(resource,
0113: "checkevents.cannot_cancel_item",
0114: (cart != null ? cart.getLocale() : Locale
0115: .getDefault()));
0116: request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
0117: return "error";
0118: }
0119:
0120: if (result.containsKey(ModelService.ERROR_MESSAGE)) {
0121: request.setAttribute("_ERROR_MESSAGE_", result
0122: .get(ModelService.ERROR_MESSAGE));
0123: return "error";
0124: }
0125:
0126: return "success";
0127: }
0128:
0129: public static String setCheckOutPages(HttpServletRequest request,
0130: HttpServletResponse response) {
0131: if ("error".equals(CheckOutEvents.cartNotEmpty(request,
0132: response)) == true) {
0133: return "error";
0134: }
0135:
0136: Locale locale = UtilHttp.getLocale(request);
0137: String curPage = request.getParameter("checkoutpage");
0138: Debug.logInfo("CheckoutPage: " + curPage, module);
0139:
0140: Map callResult = null;
0141: String errMsg = null;
0142:
0143: ShoppingCart cart = (ShoppingCart) request.getSession()
0144: .getAttribute("shoppingCart");
0145: LocalDispatcher dispatcher = (LocalDispatcher) request
0146: .getAttribute("dispatcher");
0147: GenericDelegator delegator = (GenericDelegator) request
0148: .getAttribute("delegator");
0149: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0150: delegator, cart);
0151:
0152: if ("shippingaddress".equals(curPage) == true) {
0153: // Set the shipping address options
0154: String shippingContactMechId = request
0155: .getParameter("shipping_contact_mech_id");
0156: callResult = checkOutHelper
0157: .setCheckOutShippingAddress(shippingContactMechId);
0158:
0159: ServiceUtil.getMessages(request, callResult, null, "<li>",
0160: "</li>", "<ul>", "</ul>", null, null);
0161:
0162: if (!(callResult.get(ModelService.RESPONSE_MESSAGE)
0163: .equals(ModelService.RESPOND_ERROR))) {
0164: // No errors so push the user onto the next page
0165: curPage = "shippingoptions";
0166: }
0167: } else if ("shippingoptions".equals(curPage) == true) {
0168: // Set the general shipping options
0169: String shippingMethod = request
0170: .getParameter("shipping_method");
0171: String correspondingPoId = request
0172: .getParameter("corresponding_po_id");
0173: String shippingInstructions = request
0174: .getParameter("shipping_instructions");
0175: String orderAdditionalEmails = request
0176: .getParameter("order_additional_emails");
0177: String maySplit = request.getParameter("may_split");
0178: String giftMessage = request.getParameter("gift_message");
0179: String isGift = request.getParameter("is_gift");
0180: callResult = checkOutHelper.setCheckOutShippingOptions(
0181: shippingMethod, correspondingPoId,
0182: shippingInstructions, orderAdditionalEmails,
0183: maySplit, giftMessage, isGift);
0184:
0185: ServiceUtil.getMessages(request, callResult, null, "<li>",
0186: "</li>", "<ul>", "</ul>", null, null);
0187:
0188: if (!(callResult.get(ModelService.RESPONSE_MESSAGE)
0189: .equals(ModelService.RESPOND_ERROR))) {
0190: // No errors so push the user onto the next page
0191: curPage = "payment";
0192: }
0193: } else if ("payment".equals(curPage) == true) {
0194: // get the currency format
0195: String currencyFormat = UtilProperties.getPropertyValue(
0196: "general.properties", "currency.decimal.format",
0197: "##0.00");
0198: DecimalFormat formatter = new DecimalFormat(currencyFormat);
0199:
0200: // Set the payment options
0201: Map selectedPaymentMethods = getSelectedPaymentMethods(request);
0202: if (selectedPaymentMethods == null) {
0203: return "error";
0204: }
0205:
0206: String billingAccountId = request
0207: .getParameter("billingAccountId");
0208: String billingAcctAmtStr = request.getParameter("amount_"
0209: + billingAccountId);
0210: Double billingAccountAmt = null;
0211: // parse the amount to a decimal
0212: if (billingAcctAmtStr != null) {
0213: try {
0214: billingAccountAmt = new Double(formatter.parse(
0215: billingAcctAmtStr).doubleValue());
0216: } catch (ParseException e) {
0217: Debug.logError(e, module);
0218: Map messageMap = UtilMisc.toMap("billingAccountId",
0219: billingAccountId);
0220: errMsg = UtilProperties
0221: .getMessage(
0222: resource,
0223: "checkevents.invalid_amount_set_for_billing_account",
0224: messageMap, (cart != null ? cart
0225: .getLocale() : Locale
0226: .getDefault()));
0227: request.setAttribute("_ERROR_MESSAGE_", "<li>"
0228: + errMsg);
0229: return "error";
0230: }
0231: }
0232:
0233: List singleUsePayments = new ArrayList();
0234:
0235: // check for gift card not on file
0236: Map params = UtilHttp.getParameterMap(request);
0237: Map gcResult = checkOutHelper.checkGiftCard(params,
0238: selectedPaymentMethods);
0239: ServiceUtil.getMessages(request, gcResult, null, "<li>",
0240: "</li>", "<ul>", "</ul>", null, null);
0241: if (gcResult.get(ModelService.RESPONSE_MESSAGE).equals(
0242: ModelService.RESPOND_ERROR)) {
0243: return "error";
0244: } else {
0245: String gcPaymentMethodId = (String) gcResult
0246: .get("paymentMethodId");
0247: Double gcAmount = (Double) gcResult.get("amount");
0248: if (gcPaymentMethodId != null) {
0249: selectedPaymentMethods.put(gcPaymentMethodId,
0250: gcAmount);
0251: if ("Y".equalsIgnoreCase(request
0252: .getParameter("singleUseGiftCard"))) {
0253: singleUsePayments.add(gcPaymentMethodId);
0254: }
0255: }
0256: }
0257:
0258: callResult = checkOutHelper.setCheckOutPayment(
0259: selectedPaymentMethods, singleUsePayments,
0260: billingAccountId, billingAccountAmt);
0261:
0262: ServiceUtil.getMessages(request, callResult, null, "<li>",
0263: "</li>", "<ul>", "</ul>", null, null);
0264:
0265: if (!(callResult.get(ModelService.RESPONSE_MESSAGE)
0266: .equals(ModelService.RESPOND_ERROR))) {
0267: // No errors so push the user onto the next page
0268: curPage = "confirm";
0269: }
0270: } else {
0271: curPage = "shippingaddress";
0272: }
0273:
0274: return curPage;
0275: }
0276:
0277: public static String setCheckOutError(HttpServletRequest request,
0278: HttpServletResponse response) {
0279: String currentPage = request.getParameter("checkoutpage");
0280: if (currentPage == null || currentPage.length() == 0) {
0281: return "error";
0282: } else {
0283: return currentPage;
0284: }
0285: }
0286:
0287: public static String setPartialCheckOutOptions(
0288: HttpServletRequest request, HttpServletResponse response) {
0289: String resp = setCheckOutOptions(request, response);
0290: request.setAttribute("_ERROR_MESSAGE_", null);
0291: return "success";
0292: }
0293:
0294: public static String checkPaymentMethods(
0295: HttpServletRequest request, HttpServletResponse response) {
0296: ShoppingCart cart = (ShoppingCart) request.getSession()
0297: .getAttribute("shoppingCart");
0298: LocalDispatcher dispatcher = (LocalDispatcher) request
0299: .getAttribute("dispatcher");
0300: GenericDelegator delegator = (GenericDelegator) request
0301: .getAttribute("delegator");
0302: Locale locale = UtilHttp.getLocale(request);
0303:
0304: String errMsg = null;
0305:
0306: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0307: delegator, cart);
0308: String billingAccountId = cart.getBillingAccountId();
0309: double billingAccountAmt = cart.getBillingAccountAmount();
0310: double availableAmount = checkOutHelper
0311: .availableAccountBalance(billingAccountId);
0312: if (billingAccountAmt > availableAmount) {
0313: Map messageMap = UtilMisc.toMap("billingAccountId",
0314: billingAccountId);
0315: errMsg = UtilProperties.getMessage(resource,
0316: "checkevents.not_enough_available_on_account",
0317: messageMap, (cart != null ? cart.getLocale()
0318: : Locale.getDefault()));
0319: request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
0320: return "error";
0321: }
0322:
0323: // payment by billing account only requires more checking
0324: List paymentMethods = cart.getPaymentMethodIds();
0325: List paymentTypes = cart.getPaymentMethodTypeIds();
0326: if (paymentTypes.contains("EXT_BILLACT")
0327: && paymentTypes.size() == 1
0328: && paymentMethods.size() == 0) {
0329: if (cart.getGrandTotal() > availableAmount) {
0330: errMsg = UtilProperties
0331: .getMessage(
0332: resource,
0333: "checkevents.insufficient_credit_available_on_account",
0334: (cart != null ? cart.getLocale()
0335: : Locale.getDefault()));
0336: request
0337: .setAttribute("_ERROR_MESSAGE_", "<li>"
0338: + errMsg);
0339: return "error";
0340: }
0341: }
0342:
0343: // validate any gift card balances
0344: CheckOutEvents.validateGiftCardAmounts(request);
0345:
0346: // update the selected payment methods amount with valid numbers
0347: if (paymentMethods != null) {
0348: List nullPaymentIds = new ArrayList();
0349: Iterator i = paymentMethods.iterator();
0350: while (i.hasNext()) {
0351: String paymentMethodId = (String) i.next();
0352: Double paymentAmount = cart
0353: .getPaymentMethodAmount(paymentMethodId);
0354: if (paymentAmount == null
0355: || paymentAmount.doubleValue() == 0) {
0356: nullPaymentIds.add(paymentMethodId);
0357: }
0358: }
0359: Iterator npi = nullPaymentIds.iterator();
0360: while (npi.hasNext()) {
0361: String paymentMethodId = (String) npi.next();
0362: double requiredAmount = cart.getGrandTotal()
0363: - cart.getBillingAccountAmount();
0364: double selectedPaymentTotal = cart
0365: .getSelectedPaymentMethodsTotal();
0366: double nullAmount = requiredAmount
0367: - selectedPaymentTotal;
0368: if (nullAmount > 0) {
0369: cart.setPaymentMethodAmount(paymentMethodId,
0370: new Double(nullAmount));
0371: }
0372: }
0373: }
0374:
0375: // verify the selected payment method amounts will cover the total
0376: double requiredAmount = cart.getGrandTotal()
0377: - cart.getBillingAccountAmount();
0378: double selectedPaymentTotal = cart
0379: .getSelectedPaymentMethodsTotal();
0380: if (paymentMethods != null && paymentMethods.size() > 0
0381: && requiredAmount > selectedPaymentTotal) {
0382: Debug.logError("Required Amount : " + requiredAmount
0383: + " / Selected Amount : " + selectedPaymentTotal,
0384: module);
0385: errMsg = UtilProperties.getMessage(resource,
0386: "checkevents.payment_not_cover_this_order",
0387: (cart != null ? cart.getLocale() : Locale
0388: .getDefault()));
0389: request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
0390: return "error";
0391: }
0392:
0393: return "success";
0394: }
0395:
0396: public static Map getSelectedPaymentMethods(
0397: HttpServletRequest request) {
0398: ShoppingCart cart = (ShoppingCart) request.getSession()
0399: .getAttribute("shoppingCart");
0400: Locale locale = UtilHttp.getLocale(request);
0401: String currencyFormat = UtilProperties.getPropertyValue(
0402: "general.properties", "currency.decimal.format",
0403: "##0.00");
0404: DecimalFormat formatter = new DecimalFormat(currencyFormat);
0405: Map selectedPaymentMethods = new HashMap();
0406: String[] paymentMethods = request
0407: .getParameterValues("checkOutPaymentId");
0408: String errMsg = null;
0409:
0410: if (paymentMethods != null) {
0411: for (int i = 0; i < paymentMethods.length; i++) {
0412: String amountStr = request.getParameter("amount_"
0413: + paymentMethods[i]);
0414: Double amount = null;
0415: if (amountStr != null && amountStr.length() > 0
0416: && !"REMAINING".equals(amountStr)) {
0417: try {
0418: amount = new Double(formatter.parse(amountStr)
0419: .doubleValue());
0420: } catch (ParseException e) {
0421: Debug.logError(e, module);
0422: errMsg = UtilProperties
0423: .getMessage(
0424: resource,
0425: "checkevents.invalid_amount_set_for_payment_method",
0426: (cart != null ? cart
0427: .getLocale() : Locale
0428: .getDefault()));
0429: request.setAttribute("_ERROR_MESSAGE_", "<li>"
0430: + errMsg);
0431: return null;
0432: }
0433: }
0434: selectedPaymentMethods.put(paymentMethods[i], amount);
0435: }
0436: }
0437: Debug.logInfo("Selected Payment Methods : "
0438: + selectedPaymentMethods, module);
0439: return selectedPaymentMethods;
0440: }
0441:
0442: private static void validateGiftCardAmounts(
0443: HttpServletRequest request) {
0444: ShoppingCart cart = (ShoppingCart) request.getSession()
0445: .getAttribute("shoppingCart");
0446: GenericDelegator delegator = (GenericDelegator) request
0447: .getAttribute("delegator");
0448: LocalDispatcher dispatcher = (LocalDispatcher) request
0449: .getAttribute("dispatcher");
0450:
0451: // get the product store
0452: GenericValue productStore = ProductStoreWorker.getProductStore(
0453: cart.getProductStoreId(), delegator);
0454: if (productStore != null
0455: && "N".equalsIgnoreCase(productStore
0456: .getString("checkGcBalance"))) {
0457: return;
0458: }
0459:
0460: // get the payment config
0461: String paymentConfig = ProductStoreWorker
0462: .getProductStorePaymentProperties(delegator, cart
0463: .getProductStoreId(), "GIFT_CARD", null, true);
0464:
0465: // get the gift card objects to check
0466: Iterator i = cart.getGiftCards().iterator();
0467: while (i.hasNext()) {
0468: GenericValue gc = (GenericValue) i.next();
0469: Map gcBalanceMap = null;
0470: double gcBalance = 0.00;
0471: try {
0472: Map ctx = UtilMisc
0473: .toMap("paymentConfig", paymentConfig);
0474: ctx.put("currency", cart.getCurrency());
0475: ctx.put("cardNumber", gc.getString("cardNumber"));
0476: ctx.put("pin", gc.getString("pinNumber"));
0477: gcBalanceMap = dispatcher.runSync(
0478: "balanceInquireGiftCard", ctx);
0479: } catch (GenericServiceException e) {
0480: Debug.logError(e, module);
0481: }
0482: if (gcBalanceMap != null) {
0483: Double bal = (Double) gcBalanceMap.get("balance");
0484: if (bal != null) {
0485: gcBalance = bal.doubleValue();
0486: }
0487: }
0488:
0489: // get the bill-up to amount
0490: Double billUpTo = cart.getPaymentMethodAmount(gc
0491: .getString("paymentMethodId"));
0492:
0493: // null bill-up to means use the full balance || update the bill-up to with the balance
0494: if (billUpTo == null || billUpTo.doubleValue() == 0
0495: || gcBalance < billUpTo.doubleValue()) {
0496: cart.setPaymentMethodAmount(gc
0497: .getString("paymentMethodId"), new Double(
0498: gcBalance));
0499: }
0500: }
0501: }
0502:
0503: public static String setCheckOutOptions(HttpServletRequest request,
0504: HttpServletResponse response) {
0505: ShoppingCart cart = (ShoppingCart) request.getSession()
0506: .getAttribute("shoppingCart");
0507: LocalDispatcher dispatcher = (LocalDispatcher) request
0508: .getAttribute("dispatcher");
0509: GenericDelegator delegator = (GenericDelegator) request
0510: .getAttribute("delegator");
0511:
0512: String errMsg = null;
0513:
0514: // get the currency format
0515: String currencyFormat = UtilProperties.getPropertyValue(
0516: "general.properties", "currency.decimal.format",
0517: "##0.00");
0518: DecimalFormat formatter = new DecimalFormat(currencyFormat);
0519:
0520: // Set the payment options
0521: Map selectedPaymentMethods = getSelectedPaymentMethods(request);
0522: if (selectedPaymentMethods == null) {
0523: return "error";
0524: }
0525:
0526: String shippingMethod = request.getParameter("shipping_method");
0527: String shippingContactMechId = request
0528: .getParameter("shipping_contact_mech_id");
0529: String correspondingPoId = request
0530: .getParameter("corresponding_po_id");
0531: String shippingInstructions = request
0532: .getParameter("shipping_instructions");
0533: String orderAdditionalEmails = request
0534: .getParameter("order_additional_emails");
0535: String maySplit = request.getParameter("may_split");
0536: String giftMessage = request.getParameter("gift_message");
0537: String isGift = request.getParameter("is_gift");
0538: List singleUsePayments = new ArrayList();
0539:
0540: // get the billing account and amount
0541: String billingAccountId = request
0542: .getParameter("billingAccountId");
0543: String billingAcctAmtStr = request.getParameter("amount_"
0544: + billingAccountId);
0545: Double billingAccountAmt = null;
0546: // parse the amount to a decimal
0547: if (billingAcctAmtStr != null) {
0548: try {
0549: billingAccountAmt = new Double(formatter.parse(
0550: billingAcctAmtStr).doubleValue());
0551: } catch (ParseException e) {
0552: Debug.logError(e, module);
0553: Map messageMap = UtilMisc.toMap("billingAccountId",
0554: billingAccountId);
0555: errMsg = UtilProperties
0556: .getMessage(
0557: resource,
0558: "checkevents.invalid_amount_set_for_billing_account",
0559: messageMap, (cart != null ? cart
0560: .getLocale() : Locale
0561: .getDefault()));
0562: request
0563: .setAttribute("_ERROR_MESSAGE_", "<li>"
0564: + errMsg);
0565: // request.setAttribute("_ERROR_MESSAGE_", "<li>Invalid amount set for Billing Account #" + billingAccountId);
0566: return "error";
0567: }
0568: }
0569:
0570: // get a request map of parameters
0571: Map params = UtilHttp.getParameterMap(request);
0572: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0573: delegator, cart);
0574:
0575: // check for gift card not on file
0576: Map gcResult = checkOutHelper.checkGiftCard(params,
0577: selectedPaymentMethods);
0578: ServiceUtil.getMessages(request, gcResult, null, "<li>",
0579: "</li>", "<ul>", "</ul>", null, null);
0580: if (gcResult.get(ModelService.RESPONSE_MESSAGE).equals(
0581: ModelService.RESPOND_ERROR)) {
0582: return "error";
0583: } else {
0584: String gcPaymentMethodId = (String) gcResult
0585: .get("paymentMethodId");
0586: Double gcAmount = (Double) gcResult.get("amount");
0587: if (gcPaymentMethodId != null) {
0588: selectedPaymentMethods.put(gcPaymentMethodId, gcAmount);
0589: if ("Y".equalsIgnoreCase(request
0590: .getParameter("singleUseGiftCard"))) {
0591: singleUsePayments.add(gcPaymentMethodId);
0592: }
0593: }
0594: }
0595:
0596: Map optResult = checkOutHelper.setCheckOutOptions(
0597: shippingMethod, shippingContactMechId,
0598: selectedPaymentMethods, singleUsePayments,
0599: billingAccountId, billingAccountAmt, correspondingPoId,
0600: shippingInstructions, orderAdditionalEmails, maySplit,
0601: giftMessage, isGift);
0602:
0603: ServiceUtil.getMessages(request, optResult, null, "<li>",
0604: "</li>", "<ul>", "</ul>", null, null);
0605: if (optResult.get(ModelService.RESPONSE_MESSAGE).equals(
0606: ModelService.RESPOND_ERROR)) {
0607: return "error";
0608: } else {
0609: return "success";
0610: }
0611: }
0612:
0613: // Create order event - uses createOrder service for processing
0614: public static String createOrder(HttpServletRequest request,
0615: HttpServletResponse response) {
0616: HttpSession session = request.getSession();
0617: ServletContext application = ((ServletContext) request
0618: .getAttribute("servletContext"));
0619: ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
0620: LocalDispatcher dispatcher = (LocalDispatcher) request
0621: .getAttribute("dispatcher");
0622: GenericDelegator delegator = (GenericDelegator) request
0623: .getAttribute("delegator");
0624: GenericValue userLogin = (GenericValue) session
0625: .getAttribute("userLogin");
0626: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0627: delegator, cart);
0628: Map callResult;
0629:
0630: // remove this whenever creating an order so quick reorder cache will refresh/recalc
0631: session.removeAttribute("_QUICK_REORDER_PRODUCTS_");
0632:
0633: boolean areOrderItemsExploded = explodeOrderItems(delegator,
0634: cart);
0635:
0636: //get the TrackingCodeOrder List
0637: List trackingCodeOrders = TrackingCodeEvents
0638: .makeTrackingCodeOrders(request);
0639: String distributorId = (String) session
0640: .getAttribute("_DISTRIBUTOR_ID_");
0641: String affiliateId = (String) session
0642: .getAttribute("_AFFILIATE_ID_");
0643: String visitId = VisitHandler.getVisitId(session);
0644: String webSiteId = CatalogWorker.getWebSiteId(request);
0645:
0646: callResult = checkOutHelper.createOrder(userLogin,
0647: distributorId, affiliateId, trackingCodeOrders,
0648: areOrderItemsExploded, visitId, webSiteId);
0649:
0650: if (callResult != null) {
0651: ServiceUtil.getMessages(request, callResult, null, "<li>",
0652: "</li>", "<ul>", "</ul>", null, null);
0653:
0654: if (callResult.get(ModelService.RESPONSE_MESSAGE).equals(
0655: ModelService.RESPOND_SUCCESS)) {
0656: // set the orderId for use by chained events
0657: String orderId = cart.getOrderId();
0658: request.setAttribute("order_id", orderId);
0659: request.setAttribute("orderId", orderId);
0660: request.setAttribute("orderAdditionalEmails", cart
0661: .getOrderAdditionalEmails());
0662: }
0663: }
0664:
0665: return cart.getOrderType().toLowerCase();
0666: }
0667:
0668: // Event wrapper for the tax calc.
0669: public static String calcTax(HttpServletRequest request,
0670: HttpServletResponse response) {
0671: try {
0672: calcTax(request);
0673: } catch (GeneralException e) {
0674: request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
0675: return "error";
0676: }
0677: return "success";
0678: }
0679:
0680: // Invoke the taxCalc
0681: private static void calcTax(HttpServletRequest request)
0682: throws GeneralException {
0683: LocalDispatcher dispatcher = (LocalDispatcher) request
0684: .getAttribute("dispatcher");
0685: GenericDelegator delegator = (GenericDelegator) request
0686: .getAttribute("delegator");
0687: ShoppingCart cart = (ShoppingCart) request.getSession()
0688: .getAttribute("shoppingCart");
0689: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0690: delegator, cart);
0691:
0692: //Calculate and add the tax adjustments
0693: checkOutHelper.calcAndAddTax();
0694: }
0695:
0696: public static boolean explodeOrderItems(GenericDelegator delegator,
0697: ShoppingCart cart) {
0698: if (cart == null)
0699: return false;
0700: GenericValue productStore = ProductStoreWorker.getProductStore(
0701: cart.getProductStoreId(), delegator);
0702: if (productStore == null
0703: || productStore.get("explodeOrderItems") == null) {
0704: return false;
0705: }
0706: return productStore.getBoolean("explodeOrderItems")
0707: .booleanValue();
0708: }
0709:
0710: // Event wrapper for processPayment.
0711: public static String processPayment(HttpServletRequest request,
0712: HttpServletResponse response) {
0713: // run the process payment process + approve order when complete; may also run sync fulfillments
0714: int failureCode = 0;
0715: try {
0716: if (!processPayment(request)) {
0717: failureCode = 1;
0718: }
0719: } catch (GeneralException e) {
0720: Debug.logError(e, module);
0721: ServiceUtil.setMessages(request, "<li>" + e.getMessage()
0722: + "</li>", null, null);
0723: failureCode = 2;
0724: } catch (GeneralRuntimeException e) {
0725: Debug.logError(e, module);
0726: ServiceUtil.setMessages(request, "<li>" + e.getMessage()
0727: + "</li>", null, null);
0728: }
0729:
0730: // event return based on failureCode
0731: switch (failureCode) {
0732: case 0:
0733: return "success";
0734: case 1:
0735: return "fail";
0736: default:
0737: return "error";
0738: }
0739: }
0740:
0741: private static boolean processPayment(HttpServletRequest request)
0742: throws GeneralException {
0743: HttpSession session = request.getSession();
0744: LocalDispatcher dispatcher = (LocalDispatcher) request
0745: .getAttribute("dispatcher");
0746: GenericDelegator delegator = (GenericDelegator) request
0747: .getAttribute("delegator");
0748: ShoppingCart cart = (ShoppingCart) request.getSession()
0749: .getAttribute("shoppingCart");
0750: GenericValue userLogin = (GenericValue) session
0751: .getAttribute("userLogin");
0752: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0753: delegator, cart);
0754:
0755: // load the ProductStore settings
0756: GenericValue productStore = ProductStoreWorker.getProductStore(
0757: cart.getProductStoreId(), delegator);
0758: Map callResult = checkOutHelper.processPayment(productStore,
0759: userLogin);
0760:
0761: // generate any messages required
0762: ServiceUtil.getMessages(request, callResult, null, "<li>",
0763: "</li>", "<ul>", "</ul>", null, null);
0764:
0765: // determine whether it was a success or failure
0766: return (callResult.get(ModelService.RESPONSE_MESSAGE)
0767: .equals(ModelService.RESPOND_SUCCESS));
0768: }
0769:
0770: public static String checkOrderBlacklist(
0771: HttpServletRequest request, HttpServletResponse response) {
0772: HttpSession session = request.getSession();
0773: ShoppingCart cart = (ShoppingCart) session
0774: .getAttribute("shoppingCart");
0775: GenericDelegator delegator = (GenericDelegator) request
0776: .getAttribute("delegator");
0777: GenericValue userLogin = (GenericValue) session
0778: .getAttribute("userLogin");
0779: CheckOutHelper checkOutHelper = new CheckOutHelper(null,
0780: delegator, cart);
0781: String result;
0782:
0783: Map callResult = checkOutHelper.checkOrderBlacklist(userLogin);
0784: if (callResult.get(ModelService.RESPONSE_MESSAGE).equals(
0785: ModelService.RESPOND_ERROR)) {
0786: result = (String) callResult
0787: .get(ModelService.ERROR_MESSAGE);
0788: } else {
0789: result = (String) callResult
0790: .get(ModelService.SUCCESS_MESSAGE);
0791: }
0792:
0793: return result;
0794: }
0795:
0796: public static String failedBlacklistCheck(
0797: HttpServletRequest request, HttpServletResponse response) {
0798: HttpSession session = request.getSession();
0799: ShoppingCart cart = (ShoppingCart) session
0800: .getAttribute("shoppingCart");
0801: GenericDelegator delegator = (GenericDelegator) request
0802: .getAttribute("delegator");
0803: LocalDispatcher dispatcher = (LocalDispatcher) request
0804: .getAttribute("dispatcher");
0805: GenericValue userLogin = (GenericValue) session
0806: .getAttribute("userLogin");
0807: String result;
0808:
0809: // Load the properties store
0810: GenericValue productStore = ProductStoreWorker.getProductStore(
0811: cart.getProductStoreId(), delegator);
0812: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0813: delegator, cart);
0814: Map callResult = checkOutHelper.failedBlacklistCheck(userLogin,
0815: productStore);
0816:
0817: //Generate any messages required
0818: ServiceUtil.getMessages(request, callResult, null, "<li>",
0819: "</li>", "<ul>", "</ul>", null, null);
0820:
0821: // wipe the session
0822: session.invalidate();
0823:
0824: //Determine whether it was a success or not
0825: if (callResult.get(ModelService.RESPONSE_MESSAGE).equals(
0826: ModelService.RESPOND_ERROR)) {
0827: result = (String) callResult
0828: .get(ModelService.ERROR_MESSAGE);
0829: request.setAttribute("_ERROR_MESSAGE_", result);
0830: result = "error";
0831: } else {
0832: result = (String) callResult
0833: .get(ModelService.ERROR_MESSAGE);
0834: request.setAttribute("_ERROR_MESSAGE_", result);
0835: result = "success";
0836: }
0837: return result;
0838: }
0839:
0840: public static String checkExternalPayment(
0841: HttpServletRequest request, HttpServletResponse response) {
0842: // warning there can only be ONE payment preference for this to work
0843: // you cannot accept multiple payment type when using an external gateway
0844: GenericDelegator delegator = (GenericDelegator) request
0845: .getAttribute("delegator");
0846: String result;
0847:
0848: String orderId = (String) request.getAttribute("order_id");
0849: CheckOutHelper checkOutHelper = new CheckOutHelper(null,
0850: delegator, null);
0851: Map callResult = checkOutHelper.checkExternalPayment(orderId);
0852:
0853: //Generate any messages required
0854: ServiceUtil.getMessages(request, callResult, null, "<li>",
0855: "</li>", "<ul>", "</ul>", null, null);
0856:
0857: // any error messages have prepared for display, return the type ('error' if failed)
0858: result = (String) callResult.get("type");
0859: return result;
0860: }
0861:
0862: public static String finalizeOrderEntry(HttpServletRequest request,
0863: HttpServletResponse response) {
0864: ShoppingCart cart = (ShoppingCart) request.getSession()
0865: .getAttribute("shoppingCart");
0866: GenericDelegator delegator = (GenericDelegator) request
0867: .getAttribute("delegator");
0868: LocalDispatcher dispatcher = (LocalDispatcher) request
0869: .getAttribute("dispatcher");
0870: Map paramMap = UtilHttp.getParameterMap(request);
0871: Boolean offlinePayments;
0872: String shippingContactMechId = null;
0873: String shippingMethod = null;
0874: String shippingInstructions = null;
0875: String maySplit = null;
0876: String giftMessage = null;
0877: String isGift = null;
0878: String methodType = null;
0879: String checkOutPaymentId = null;
0880: String singleUsePayment = null;
0881: String appendPayment = null;
0882:
0883: String mode = request.getParameter("finalizeMode");
0884: Debug.logInfo("FinalizeMode: " + mode, module);
0885:
0886: // check the userLogin object
0887: GenericValue userLogin = (GenericValue) request.getSession()
0888: .getAttribute("userLogin");
0889:
0890: // if null then we must be an anonymous shopper
0891: if (userLogin == null) {
0892: // remove auto-login fields
0893: request.getSession().removeAttribute("autoUserLogin");
0894: request.getSession().removeAttribute("autoName");
0895: }
0896:
0897: // set the customer info
0898: if (mode != null && mode.equals("cust")) {
0899: String partyId = (String) request.getAttribute("partyId");
0900: if (partyId != null) {
0901: request.getSession().setAttribute("orderPartyId",
0902: partyId);
0903: // no userLogin means we are an anonymous shopper; fake the UL for service calls
0904: if (userLogin == null) {
0905: try {
0906: userLogin = delegator.findByPrimaryKey(
0907: "UserLogin", UtilMisc.toMap(
0908: "userLoginId", "anonymous"));
0909: } catch (GenericEntityException e) {
0910: Debug.logError(e, module);
0911: }
0912: if (userLogin != null) {
0913: userLogin.set("partyId", partyId);
0914: }
0915: request.getSession().setAttribute("userLogin",
0916: userLogin);
0917: }
0918: }
0919: }
0920:
0921: // get the shipping method
0922: shippingContactMechId = request
0923: .getParameter("shipping_contact_mech_id");
0924: if (shippingContactMechId == null) {
0925: shippingContactMechId = (String) request
0926: .getAttribute("contactMechId");
0927: }
0928:
0929: // get the options
0930: shippingMethod = request.getParameter("shipping_method");
0931: shippingInstructions = request
0932: .getParameter("shipping_instructions");
0933: maySplit = request.getParameter("may_split");
0934: giftMessage = request.getParameter("gift_message");
0935: isGift = request.getParameter("is_gift");
0936:
0937: // payment option; if offline we skip the payment screen
0938: methodType = request.getParameter("paymentMethodType");
0939:
0940: // get the payment
0941: checkOutPaymentId = request.getParameter("checkOutPaymentId");
0942: if (checkOutPaymentId == null) {
0943: checkOutPaymentId = (String) request
0944: .getAttribute("paymentMethodId");
0945: }
0946: singleUsePayment = request.getParameter("singleUsePayment");
0947: appendPayment = request.getParameter("appendPayment");
0948: boolean isSingleUsePayment = singleUsePayment != null
0949: && "Y".equalsIgnoreCase(singleUsePayment) ? true
0950: : false;
0951: boolean doAppendPayment = appendPayment != null
0952: && "Y".equalsIgnoreCase(appendPayment) ? true : false;
0953:
0954: CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher,
0955: delegator, cart);
0956:
0957: // get the currency format
0958: String currencyFormat = UtilProperties.getPropertyValue(
0959: "general.properties", "currency.decimal.format",
0960: "##0.00");
0961: DecimalFormat formatter = new DecimalFormat(currencyFormat);
0962:
0963: // Set the payment options
0964: Map selectedPaymentMethods = getSelectedPaymentMethods(request);
0965: if (selectedPaymentMethods == null) {
0966: return "error";
0967: }
0968:
0969: String billingAccountId = request
0970: .getParameter("billingAccountId");
0971: String billingAcctAmtStr = request.getParameter("amount_"
0972: + billingAccountId);
0973: Double billingAccountAmt = null;
0974:
0975: // parse the amount to a decimal
0976: if (billingAcctAmtStr != null) {
0977: try {
0978: billingAccountAmt = new Double(formatter.parse(
0979: billingAcctAmtStr).doubleValue());
0980: } catch (ParseException e) {
0981: Debug.logError(e, module);
0982: request.setAttribute("_ERROR_MESSAGE_",
0983: "<li>Invalid amount set for Billing Account #"
0984: + billingAccountId);
0985: return "error";
0986: }
0987: }
0988:
0989: checkOutHelper.setCheckOutPayment(selectedPaymentMethods, null,
0990: billingAccountId, billingAccountAmt);
0991:
0992: Map callResult = checkOutHelper.finalizeOrderEntry(mode,
0993: shippingContactMechId, shippingMethod,
0994: shippingInstructions, maySplit, giftMessage, isGift,
0995: methodType, checkOutPaymentId, isSingleUsePayment,
0996: doAppendPayment, paramMap);
0997:
0998: // generate any messages required
0999: ServiceUtil.getMessages(request, callResult, null, "<li>",
1000: "</li>", "<ul>", "</ul>", null, null);
1001:
1002: // determine whether it was a success or not
1003: if (callResult.get(ModelService.RESPONSE_MESSAGE).equals(
1004: ModelService.RESPOND_ERROR)) {
1005: return "error";
1006: } else {
1007: // seems a bit suspicious that these properties have slightly different names
1008: offlinePayments = (Boolean) callResult
1009: .get("OFFLINE_PAYMENT");
1010: request.setAttribute("OFFLINE_PAYMENT", offlinePayments);
1011: offlinePayments = (Boolean) callResult
1012: .get("OFFLINE_PAYMENTS");
1013: request.getSession().setAttribute("OFFLINE_PAYMENTS",
1014: offlinePayments);
1015: }
1016:
1017: // determine where to direct the browser
1018: String requireCustomer = null;
1019: String requireShipping = null;
1020: String requireOptions = null;
1021: String requirePayment = null;
1022:
1023: // these options are not available to anonymous shoppers (security)
1024: if (userLogin != null
1025: && !"anonymous".equals(userLogin
1026: .getString("userLoginId"))) {
1027: requireCustomer = request
1028: .getParameter("finalizeReqCustInfo");
1029: requireShipping = request
1030: .getParameter("finalizeReqShipInfo");
1031: requireOptions = request.getParameter("finalizeReqOptions");
1032: requirePayment = request.getParameter("finalizeReqPayInfo");
1033: }
1034:
1035: // these are the default values
1036: if (requireCustomer == null)
1037: requireCustomer = "true";
1038: if (requireShipping == null)
1039: requireShipping = "true";
1040: if (requireOptions == null)
1041: requireOptions = "true";
1042: if (requirePayment == null)
1043: requirePayment = "true";
1044:
1045: String shipContactMechId = cart.getShippingContactMechId();
1046: String customerPartyId = cart.getPartyId();
1047: String shipmentMethodTypeId = cart.getShipmentMethodTypeId();
1048: List paymentMethodIds = cart.getPaymentMethodIds();
1049: List paymentMethodTypeIds = cart.getPaymentMethodTypeIds();
1050:
1051: if (requireCustomer.equalsIgnoreCase("true")
1052: && (customerPartyId == null || customerPartyId
1053: .equals("_NA_"))) {
1054: return "customer";
1055: }
1056:
1057: if (requireShipping.equalsIgnoreCase("true")
1058: && shipContactMechId == null) {
1059: return "shipping";
1060: }
1061:
1062: if (requireOptions.equalsIgnoreCase("true")
1063: && shipmentMethodTypeId == null) {
1064: return "options";
1065: }
1066:
1067: if (requirePayment.equalsIgnoreCase("true")) {
1068: if (paymentMethodIds == null
1069: || paymentMethodIds.size() == 0) {
1070: if (paymentMethodTypeIds == null
1071: || paymentMethodTypeIds.size() == 0) {
1072: return "payment";
1073: }
1074: }
1075: }
1076:
1077: if (isSingleUsePayment) {
1078: return "paysplit";
1079: }
1080:
1081: if ("SALES_ORDER".equals(cart.getOrderType())) {
1082: return "sales";
1083: } else {
1084: return "po";
1085: }
1086: }
1087:
1088: public static String finalizeOrderEntryError(
1089: HttpServletRequest request, HttpServletResponse response) {
1090: String finalizePage = request.getParameter("finalizeMode");
1091: if (finalizePage == null || finalizePage.length() == 0) {
1092: return "error";
1093: } else {
1094: return finalizePage;
1095: }
1096: }
1097: }
|