0001: /**
0002: * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
0003: *
0004: * Permission is hereby granted, free of charge, to any person obtaining a copy
0005: * of this software and associated documentation files (the "Software"), to deal
0006: * in the Software without restriction, including without limitation the rights
0007: * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
0008: * copies of the Software, and to permit persons to whom the Software is
0009: * furnished to do so, subject to the following conditions:
0010: *
0011: * The above copyright notice and this permission notice shall be included in
0012: * all copies or substantial portions of the Software.
0013: *
0014: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
0015: * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
0016: * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
0017: * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
0018: * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
0019: * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
0020: * SOFTWARE.
0021: */package com.liferay.portlet.shopping.util;
0022:
0023: import com.liferay.portal.PortalException;
0024: import com.liferay.portal.SystemException;
0025: import com.liferay.portal.kernel.language.LanguageUtil;
0026: import com.liferay.portal.kernel.portlet.LiferayWindowState;
0027: import com.liferay.portal.kernel.util.Constants;
0028: import com.liferay.portal.kernel.util.GetterUtil;
0029: import com.liferay.portal.kernel.util.OrderByComparator;
0030: import com.liferay.portal.kernel.util.StringMaker;
0031: import com.liferay.portal.kernel.util.StringPool;
0032: import com.liferay.portal.kernel.util.StringUtil;
0033: import com.liferay.portal.theme.ThemeDisplay;
0034: import com.liferay.portal.util.WebKeys;
0035: import com.liferay.portlet.shopping.NoSuchCartException;
0036: import com.liferay.portlet.shopping.model.ShoppingCart;
0037: import com.liferay.portlet.shopping.model.ShoppingCartItem;
0038: import com.liferay.portlet.shopping.model.ShoppingCategory;
0039: import com.liferay.portlet.shopping.model.ShoppingCoupon;
0040: import com.liferay.portlet.shopping.model.ShoppingItem;
0041: import com.liferay.portlet.shopping.model.ShoppingItemField;
0042: import com.liferay.portlet.shopping.model.ShoppingItemPrice;
0043: import com.liferay.portlet.shopping.model.ShoppingOrder;
0044: import com.liferay.portlet.shopping.model.ShoppingOrderItem;
0045: import com.liferay.portlet.shopping.model.impl.ShoppingCartImpl;
0046: import com.liferay.portlet.shopping.model.impl.ShoppingCouponImpl;
0047: import com.liferay.portlet.shopping.model.impl.ShoppingItemPriceImpl;
0048: import com.liferay.portlet.shopping.model.impl.ShoppingOrderImpl;
0049: import com.liferay.portlet.shopping.service.ShoppingCartLocalServiceUtil;
0050: import com.liferay.portlet.shopping.service.ShoppingCategoryLocalServiceUtil;
0051: import com.liferay.portlet.shopping.service.ShoppingOrderItemLocalServiceUtil;
0052: import com.liferay.portlet.shopping.service.persistence.ShoppingItemPriceUtil;
0053: import com.liferay.portlet.shopping.util.comparator.ItemMinQuantityComparator;
0054: import com.liferay.portlet.shopping.util.comparator.ItemNameComparator;
0055: import com.liferay.portlet.shopping.util.comparator.ItemPriceComparator;
0056: import com.liferay.portlet.shopping.util.comparator.ItemSKUComparator;
0057: import com.liferay.portlet.shopping.util.comparator.OrderDateComparator;
0058: import com.liferay.util.HttpUtil;
0059: import com.liferay.util.MathUtil;
0060:
0061: import java.text.NumberFormat;
0062:
0063: import java.util.ArrayList;
0064: import java.util.HashMap;
0065: import java.util.HashSet;
0066: import java.util.Iterator;
0067: import java.util.List;
0068: import java.util.Map;
0069: import java.util.Set;
0070:
0071: import javax.portlet.PortletRequest;
0072: import javax.portlet.PortletSession;
0073: import javax.portlet.PortletURL;
0074: import javax.portlet.RenderRequest;
0075: import javax.portlet.RenderResponse;
0076: import javax.portlet.WindowState;
0077:
0078: import javax.servlet.jsp.PageContext;
0079:
0080: /**
0081: * <a href="ShoppingUtil.java.html"><b><i>View Source</i></b></a>
0082: *
0083: * @author Brian Wing Shun Chan
0084: *
0085: */
0086: public class ShoppingUtil {
0087:
0088: public static double calculateActualPrice(ShoppingItem item) {
0089: return item.getPrice() - calculateDiscountPrice(item);
0090: }
0091:
0092: public static double calculateActualPrice(ShoppingItem item,
0093: int count) throws PortalException, SystemException {
0094:
0095: return calculatePrice(item, count)
0096: - calculateDiscountPrice(item, count);
0097: }
0098:
0099: public static double calculateActualPrice(
0100: ShoppingItemPrice itemPrice) {
0101: return itemPrice.getPrice() - calculateDiscountPrice(itemPrice);
0102: }
0103:
0104: public static double calculateActualSubtotal(Map items)
0105: throws PortalException, SystemException {
0106:
0107: return calculateSubtotal(items)
0108: - calculateDiscountSubtotal(items);
0109: }
0110:
0111: public static double calculateActualSubtotal(List orderItems) {
0112: double subtotal = 0.0;
0113:
0114: Iterator itr = orderItems.iterator();
0115:
0116: while (itr.hasNext()) {
0117: ShoppingOrderItem orderItem = (ShoppingOrderItem) itr
0118: .next();
0119:
0120: subtotal += orderItem.getPrice() * orderItem.getQuantity();
0121: }
0122:
0123: return subtotal;
0124: }
0125:
0126: public static double calculateAlternativeShipping(Map items,
0127: int altShipping) throws PortalException, SystemException {
0128:
0129: double shipping = calculateShipping(items);
0130: double alternativeShipping = shipping;
0131:
0132: ShoppingPreferences prefs = null;
0133:
0134: Iterator itr = items.entrySet().iterator();
0135:
0136: while (itr.hasNext()) {
0137: Map.Entry entry = (Map.Entry) itr.next();
0138:
0139: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0140: .getKey();
0141:
0142: ShoppingItem item = cartItem.getItem();
0143:
0144: if (prefs == null) {
0145: ShoppingCategory category = item.getCategory();
0146:
0147: prefs = ShoppingPreferences.getInstance(category
0148: .getCompanyId(), category.getGroupId());
0149:
0150: break;
0151: }
0152: }
0153:
0154: // Calculate alternative shipping if shopping is configured to use
0155: // alternative shipping and shipping price is greater than 0
0156:
0157: if ((prefs != null) && (prefs.useAlternativeShipping())
0158: && (shipping > 0)) {
0159:
0160: double altShippingDelta = 0.0;
0161:
0162: try {
0163: altShippingDelta = GetterUtil.getDouble(prefs
0164: .getAlternativeShipping()[1][altShipping]);
0165: } catch (Exception e) {
0166: return alternativeShipping;
0167: }
0168:
0169: if (altShippingDelta > 0) {
0170: alternativeShipping = shipping * altShippingDelta;
0171: }
0172: }
0173:
0174: return alternativeShipping;
0175: }
0176:
0177: public static double calculateCouponDiscount(Map items,
0178: ShoppingCoupon coupon) throws PortalException,
0179: SystemException {
0180:
0181: return calculateCouponDiscount(items, null, coupon);
0182: }
0183:
0184: public static double calculateCouponDiscount(Map items,
0185: String stateId, ShoppingCoupon coupon)
0186: throws PortalException, SystemException {
0187:
0188: double discount = 0.0;
0189:
0190: if ((coupon == null) || !coupon.isActive()
0191: || !coupon.hasValidDateRange()) {
0192:
0193: return discount;
0194: }
0195:
0196: String[] categoryIds = StringUtil.split(coupon
0197: .getLimitCategories());
0198: String[] skus = StringUtil.split(coupon.getLimitSkus());
0199:
0200: if ((categoryIds.length > 0) || (skus.length > 0)) {
0201: Set categoryIdsSet = new HashSet();
0202:
0203: for (int i = 0; i < categoryIds.length; i++) {
0204: categoryIdsSet.add(categoryIds[i]);
0205: }
0206:
0207: Set skusSet = new HashSet();
0208:
0209: for (int i = 0; i < skus.length; i++) {
0210: skusSet.add(skus[i]);
0211: }
0212:
0213: Map newItems = new HashMap();
0214:
0215: Iterator itr = items.entrySet().iterator();
0216:
0217: while (itr.hasNext()) {
0218: Map.Entry entry = (Map.Entry) itr.next();
0219:
0220: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0221: .getKey();
0222: Integer count = (Integer) entry.getValue();
0223:
0224: ShoppingItem item = cartItem.getItem();
0225:
0226: if (((categoryIdsSet.size() > 0) && (categoryIdsSet
0227: .contains(new Long(item.getCategoryId()))))
0228: || ((skusSet.size() > 0) && (skusSet
0229: .contains(item.getSku())))) {
0230:
0231: newItems.put(cartItem, count);
0232: }
0233: }
0234:
0235: items = newItems;
0236: }
0237:
0238: double actualSubtotal = calculateActualSubtotal(items);
0239:
0240: if ((coupon.getMinOrder() > 0)
0241: && (coupon.getMinOrder() > actualSubtotal)) {
0242:
0243: return discount;
0244: }
0245:
0246: String type = coupon.getDiscountType();
0247:
0248: if (type.equals(ShoppingCouponImpl.DISCOUNT_TYPE_PERCENTAGE)) {
0249: discount = actualSubtotal * coupon.getDiscount();
0250: } else if (type.equals(ShoppingCouponImpl.DISCOUNT_TYPE_ACTUAL)) {
0251: discount = coupon.getDiscount();
0252: } else if (type
0253: .equals(ShoppingCouponImpl.DISCOUNT_TYPE_FREE_SHIPPING)) {
0254: discount = calculateShipping(items);
0255: } else if (type
0256: .equals(ShoppingCouponImpl.DISCOUNT_TYPE_TAX_FREE)) {
0257: if (stateId != null) {
0258: discount = calculateTax(items, stateId);
0259: }
0260: }
0261:
0262: return discount;
0263: }
0264:
0265: public static double calculateDiscountPercent(Map items)
0266: throws PortalException, SystemException {
0267:
0268: double discount = calculateDiscountSubtotal(items)
0269: / calculateSubtotal(items);
0270:
0271: if (Double.isNaN(discount) || Double.isInfinite(discount)) {
0272: discount = 0.0;
0273: }
0274:
0275: return discount;
0276: }
0277:
0278: public static double calculateDiscountPrice(ShoppingItem item) {
0279: return item.getPrice() * item.getDiscount();
0280: }
0281:
0282: public static double calculateDiscountPrice(ShoppingItem item,
0283: int count) throws PortalException, SystemException {
0284:
0285: ShoppingItemPrice itemPrice = _getItemPrice(item, count);
0286:
0287: return itemPrice.getPrice() * itemPrice.getDiscount() * count;
0288: }
0289:
0290: public static double calculateDiscountPrice(
0291: ShoppingItemPrice itemPrice) {
0292: return itemPrice.getPrice() * itemPrice.getDiscount();
0293: }
0294:
0295: public static double calculateDiscountSubtotal(Map items)
0296: throws PortalException, SystemException {
0297:
0298: double subtotal = 0.0;
0299:
0300: Iterator itr = items.entrySet().iterator();
0301:
0302: while (itr.hasNext()) {
0303: Map.Entry entry = (Map.Entry) itr.next();
0304:
0305: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0306: .getKey();
0307: Integer count = (Integer) entry.getValue();
0308:
0309: ShoppingItem item = cartItem.getItem();
0310:
0311: subtotal += calculateDiscountPrice(item, count.intValue());
0312: }
0313:
0314: return subtotal;
0315: }
0316:
0317: public static double calculateInsurance(Map items)
0318: throws PortalException, SystemException {
0319:
0320: double insurance = 0.0;
0321: double subtotal = 0.0;
0322:
0323: ShoppingPreferences prefs = null;
0324:
0325: Iterator itr = items.entrySet().iterator();
0326:
0327: while (itr.hasNext()) {
0328: Map.Entry entry = (Map.Entry) itr.next();
0329:
0330: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0331: .getKey();
0332: Integer count = (Integer) entry.getValue();
0333:
0334: ShoppingItem item = cartItem.getItem();
0335:
0336: if (prefs == null) {
0337: ShoppingCategory category = item.getCategory();
0338:
0339: prefs = ShoppingPreferences.getInstance(category
0340: .getCompanyId(), category.getGroupId());
0341: }
0342:
0343: ShoppingItemPrice itemPrice = _getItemPrice(item, count
0344: .intValue());
0345:
0346: subtotal += calculateActualPrice(itemPrice)
0347: * count.intValue();
0348: }
0349:
0350: if ((prefs != null) && (subtotal > 0)) {
0351: double insuranceRate = 0.0;
0352:
0353: double[] range = ShoppingPreferences.INSURANCE_RANGE;
0354:
0355: for (int i = 0; i < range.length - 1; i++) {
0356: if (subtotal > range[i] && subtotal <= range[i + 1]) {
0357: int rangeId = i / 2;
0358: if (MathUtil.isOdd(i)) {
0359: rangeId = (i + 1) / 2;
0360: }
0361:
0362: insuranceRate = GetterUtil.getDouble(prefs
0363: .getInsurance()[rangeId]);
0364: }
0365: }
0366:
0367: String formula = prefs.getInsuranceFormula();
0368:
0369: if (formula.equals("flat")) {
0370: insurance += insuranceRate;
0371: } else if (formula.equals("percentage")) {
0372: insurance += subtotal * insuranceRate;
0373: }
0374: }
0375:
0376: return insurance;
0377: }
0378:
0379: public static double calculatePrice(ShoppingItem item, int count)
0380: throws PortalException, SystemException {
0381:
0382: ShoppingItemPrice itemPrice = _getItemPrice(item, count);
0383:
0384: return itemPrice.getPrice() * count;
0385: }
0386:
0387: public static double calculateShipping(Map items)
0388: throws PortalException, SystemException {
0389:
0390: double shipping = 0.0;
0391: double subtotal = 0.0;
0392:
0393: ShoppingPreferences prefs = null;
0394:
0395: Iterator itr = items.entrySet().iterator();
0396:
0397: while (itr.hasNext()) {
0398: Map.Entry entry = (Map.Entry) itr.next();
0399:
0400: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0401: .getKey();
0402: Integer count = (Integer) entry.getValue();
0403:
0404: ShoppingItem item = cartItem.getItem();
0405:
0406: if (prefs == null) {
0407: ShoppingCategory category = item.getCategory();
0408:
0409: prefs = ShoppingPreferences.getInstance(category
0410: .getCompanyId(), category.getGroupId());
0411: }
0412:
0413: if (item.isRequiresShipping()) {
0414: ShoppingItemPrice itemPrice = _getItemPrice(item, count
0415: .intValue());
0416:
0417: if (itemPrice.isUseShippingFormula()) {
0418: subtotal += calculateActualPrice(itemPrice)
0419: * count.intValue();
0420: } else {
0421: shipping += itemPrice.getShipping()
0422: * count.intValue();
0423: }
0424: }
0425: }
0426:
0427: if ((prefs != null) && (subtotal > 0)) {
0428: double shippingRate = 0.0;
0429:
0430: double[] range = ShoppingPreferences.SHIPPING_RANGE;
0431:
0432: for (int i = 0; i < range.length - 1; i++) {
0433: if (subtotal > range[i] && subtotal <= range[i + 1]) {
0434: int rangeId = i / 2;
0435: if (MathUtil.isOdd(i)) {
0436: rangeId = (i + 1) / 2;
0437: }
0438:
0439: shippingRate = GetterUtil.getDouble(prefs
0440: .getShipping()[rangeId]);
0441: }
0442: }
0443:
0444: String formula = prefs.getShippingFormula();
0445:
0446: if (formula.equals("flat")) {
0447: shipping += shippingRate;
0448: } else if (formula.equals("percentage")) {
0449: shipping += subtotal * shippingRate;
0450: }
0451: }
0452:
0453: return shipping;
0454: }
0455:
0456: public static double calculateSubtotal(Map items)
0457: throws PortalException, SystemException {
0458:
0459: double subtotal = 0.0;
0460:
0461: Iterator itr = items.entrySet().iterator();
0462:
0463: while (itr.hasNext()) {
0464: Map.Entry entry = (Map.Entry) itr.next();
0465:
0466: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0467: .getKey();
0468: Integer count = (Integer) entry.getValue();
0469:
0470: ShoppingItem item = cartItem.getItem();
0471:
0472: subtotal += calculatePrice(item, count.intValue());
0473: }
0474:
0475: return subtotal;
0476: }
0477:
0478: public static double calculateTax(Map items, String stateId)
0479: throws PortalException, SystemException {
0480:
0481: double tax = 0.0;
0482:
0483: ShoppingPreferences prefs = null;
0484:
0485: Iterator itr = items.entrySet().iterator();
0486:
0487: while (itr.hasNext()) {
0488: Map.Entry entry = (Map.Entry) itr.next();
0489:
0490: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0491: .getKey();
0492:
0493: ShoppingItem item = cartItem.getItem();
0494:
0495: if (prefs == null) {
0496: ShoppingCategory category = item.getCategory();
0497:
0498: prefs = ShoppingPreferences.getInstance(category
0499: .getCompanyId(), category.getGroupId());
0500:
0501: break;
0502: }
0503: }
0504:
0505: if ((prefs != null) && (prefs.getTaxState().equals(stateId))) {
0506:
0507: double subtotal = 0.0;
0508:
0509: itr = items.entrySet().iterator();
0510:
0511: while (itr.hasNext()) {
0512: Map.Entry entry = (Map.Entry) itr.next();
0513:
0514: ShoppingCartItem cartItem = (ShoppingCartItem) entry
0515: .getKey();
0516: Integer count = (Integer) entry.getValue();
0517:
0518: ShoppingItem item = cartItem.getItem();
0519:
0520: if (item.isTaxable()) {
0521: subtotal += calculatePrice(item, count.intValue());
0522: }
0523: }
0524:
0525: tax = prefs.getTaxRate() * subtotal;
0526: }
0527:
0528: return tax;
0529: }
0530:
0531: public static double calculateTotal(Map items, String stateId,
0532: ShoppingCoupon coupon, int altShipping, boolean insure)
0533: throws PortalException, SystemException {
0534:
0535: double actualSubtotal = calculateActualSubtotal(items);
0536: double tax = calculateTax(items, stateId);
0537: double shipping = calculateAlternativeShipping(items,
0538: altShipping);
0539:
0540: double insurance = 0.0;
0541: if (insure) {
0542: insurance = calculateInsurance(items);
0543: }
0544:
0545: double couponDiscount = calculateCouponDiscount(items, stateId,
0546: coupon);
0547:
0548: double total = actualSubtotal + tax + shipping + insurance
0549: - couponDiscount;
0550:
0551: if (total < 0) {
0552: total = 0.0;
0553: }
0554:
0555: return total;
0556: }
0557:
0558: public static double calculateTotal(ShoppingOrder order)
0559: throws PortalException, SystemException {
0560:
0561: List orderItems = ShoppingOrderItemLocalServiceUtil
0562: .getOrderItems(order.getOrderId());
0563:
0564: double total = calculateActualSubtotal(orderItems)
0565: + order.getTax() + order.getShipping()
0566: + order.getInsurance() - order.getCouponDiscount();
0567:
0568: if (total < 0) {
0569: total = 0.0;
0570: }
0571:
0572: return total;
0573: }
0574:
0575: public static String getBreadcrumbs(long categoryId,
0576: PageContext pageContext, RenderRequest req,
0577: RenderResponse res) throws Exception {
0578:
0579: ShoppingCategory category = null;
0580:
0581: try {
0582: category = ShoppingCategoryLocalServiceUtil
0583: .getCategory(categoryId);
0584: } catch (Exception e) {
0585: }
0586:
0587: return getBreadcrumbs(category, pageContext, req, res);
0588: }
0589:
0590: public static String getBreadcrumbs(ShoppingCategory category,
0591: PageContext pageContext, RenderRequest req,
0592: RenderResponse res) throws Exception {
0593:
0594: PortletURL categoriesURL = res.createRenderURL();
0595:
0596: WindowState windowState = req.getWindowState();
0597:
0598: if (windowState.equals(LiferayWindowState.POP_UP)) {
0599: categoriesURL.setWindowState(LiferayWindowState.POP_UP);
0600:
0601: categoriesURL.setParameter("struts_action",
0602: "/shopping/select_category");
0603: } else {
0604: categoriesURL.setWindowState(WindowState.MAXIMIZED);
0605:
0606: categoriesURL.setParameter("struts_action",
0607: "/shopping/view");
0608: categoriesURL.setParameter("tabs1", "categories");
0609: }
0610:
0611: String categoriesLink = "<a href=\"" + categoriesURL.toString()
0612: + "\">" + LanguageUtil.get(pageContext, "categories")
0613: + "</a>";
0614:
0615: if (category == null) {
0616: return categoriesLink;
0617: }
0618:
0619: String breadcrumbs = StringPool.BLANK;
0620:
0621: if (category != null) {
0622: for (int i = 0;; i++) {
0623: category = category.toEscapedModel();
0624:
0625: PortletURL portletURL = res.createRenderURL();
0626:
0627: if (windowState.equals(LiferayWindowState.POP_UP)) {
0628: portletURL
0629: .setWindowState(LiferayWindowState.POP_UP);
0630:
0631: portletURL.setParameter("struts_action",
0632: "/shopping/select_category");
0633: portletURL.setParameter("categoryId", String
0634: .valueOf(category.getCategoryId()));
0635: } else {
0636: portletURL.setWindowState(WindowState.MAXIMIZED);
0637:
0638: portletURL.setParameter("struts_action",
0639: "/shopping/view");
0640: portletURL.setParameter("tabs1", "categories");
0641: portletURL.setParameter("categoryId", String
0642: .valueOf(category.getCategoryId()));
0643: }
0644:
0645: String categoryLink = "<a href=\""
0646: + portletURL.toString() + "\">"
0647: + category.getName() + "</a>";
0648:
0649: if (i == 0) {
0650: breadcrumbs = categoryLink;
0651: } else {
0652: breadcrumbs = categoryLink + " » "
0653: + breadcrumbs;
0654: }
0655:
0656: if (category.isRoot()) {
0657: break;
0658: }
0659:
0660: category = ShoppingCategoryLocalServiceUtil
0661: .getCategory(category.getParentCategoryId());
0662: }
0663: }
0664:
0665: breadcrumbs = categoriesLink + " » " + breadcrumbs;
0666:
0667: return breadcrumbs;
0668: }
0669:
0670: public static ShoppingCart getCart(ThemeDisplay themeDisplay) {
0671: ShoppingCart cart = new ShoppingCartImpl();
0672:
0673: cart.setGroupId(themeDisplay.getPortletGroupId());
0674: cart.setCompanyId(themeDisplay.getCompanyId());
0675: cart.setUserId(themeDisplay.getUserId());
0676: cart.setItemIds(StringPool.BLANK);
0677: cart.setCouponCodes(StringPool.BLANK);
0678: cart.setAltShipping(0);
0679: cart.setInsure(false);
0680:
0681: return cart;
0682: }
0683:
0684: public static ShoppingCart getCart(PortletRequest req)
0685: throws PortalException, SystemException {
0686:
0687: PortletSession ses = req.getPortletSession();
0688:
0689: ThemeDisplay themeDisplay = (ThemeDisplay) req
0690: .getAttribute(WebKeys.THEME_DISPLAY);
0691:
0692: String sesCartId = ShoppingCart.class.getName()
0693: + themeDisplay.getPortletGroupId();
0694:
0695: if (themeDisplay.isSignedIn()) {
0696: ShoppingCart cart = (ShoppingCart) ses
0697: .getAttribute(sesCartId);
0698:
0699: if (cart != null) {
0700: ses.removeAttribute(sesCartId);
0701: }
0702:
0703: if ((cart != null) && (cart.getItemsSize() > 0)) {
0704: cart = ShoppingCartLocalServiceUtil.updateCart(
0705: themeDisplay.getUserId(), themeDisplay
0706: .getPortletGroupId(),
0707: cart.getItemIds(), cart.getCouponCodes(), cart
0708: .getAltShipping(), cart.isInsure());
0709: } else {
0710: try {
0711: cart = ShoppingCartLocalServiceUtil.getCart(
0712: themeDisplay.getUserId(), themeDisplay
0713: .getPortletGroupId());
0714: } catch (NoSuchCartException nsce) {
0715: cart = getCart(themeDisplay);
0716:
0717: cart = ShoppingCartLocalServiceUtil.updateCart(
0718: themeDisplay.getUserId(), themeDisplay
0719: .getPortletGroupId(), cart
0720: .getItemIds(), cart
0721: .getCouponCodes(), cart
0722: .getAltShipping(), cart.isInsure());
0723: }
0724: }
0725:
0726: return cart;
0727: } else {
0728: ShoppingCart cart = (ShoppingCart) ses
0729: .getAttribute(sesCartId);
0730:
0731: if (cart == null) {
0732: cart = getCart(themeDisplay);
0733:
0734: ses.setAttribute(sesCartId, cart);
0735: }
0736:
0737: return cart;
0738: }
0739: }
0740:
0741: public static int getFieldsQuantitiesPos(ShoppingItem item,
0742: ShoppingItemField[] itemFields, String[] fieldsArray) {
0743:
0744: Set fieldsValues = new HashSet();
0745:
0746: for (int i = 0; i < fieldsArray.length; i++) {
0747: int pos = fieldsArray[i].indexOf("=");
0748:
0749: String fieldValue = fieldsArray[i].substring(pos + 1,
0750: fieldsArray[i].length()).trim();
0751:
0752: fieldsValues.add(fieldValue);
0753: }
0754:
0755: List names = new ArrayList();
0756: List values = new ArrayList();
0757:
0758: for (int i = 0; i < itemFields.length; i++) {
0759: names.add(itemFields[i].getName());
0760: values.add(StringUtil.split(itemFields[i].getValues()));
0761: }
0762:
0763: int numOfRows = 1;
0764:
0765: for (int i = 0; i < values.size(); i++) {
0766: String[] vArray = (String[]) values.get(i);
0767:
0768: numOfRows = numOfRows * vArray.length;
0769: }
0770:
0771: int rowPos = 0;
0772:
0773: for (int i = 0; i < numOfRows; i++) {
0774: boolean match = true;
0775:
0776: for (int j = 0; j < names.size(); j++) {
0777: int numOfRepeats = 1;
0778:
0779: for (int k = j + 1; k < values.size(); k++) {
0780: String[] vArray = (String[]) values.get(k);
0781:
0782: numOfRepeats = numOfRepeats * vArray.length;
0783: }
0784:
0785: String[] vArray = (String[]) values.get(j);
0786:
0787: int arrayPos;
0788: for (arrayPos = i / numOfRepeats; arrayPos >= vArray.length; arrayPos = arrayPos
0789: - vArray.length) {
0790: }
0791:
0792: if (!fieldsValues.contains(vArray[arrayPos].trim())) {
0793: match = false;
0794:
0795: break;
0796: }
0797: }
0798:
0799: if (match) {
0800: rowPos = i;
0801:
0802: break;
0803: }
0804: }
0805:
0806: return rowPos;
0807: }
0808:
0809: public static long getItemId(String itemId) {
0810: int pos = itemId.indexOf(StringPool.PIPE);
0811:
0812: if (pos != -1) {
0813: itemId = itemId.substring(0, pos);
0814: }
0815:
0816: return GetterUtil.getLong(itemId);
0817: }
0818:
0819: public static String getItemFields(String itemId) {
0820: int pos = itemId.indexOf(StringPool.PIPE);
0821:
0822: if (pos == -1) {
0823: return StringPool.BLANK;
0824: } else {
0825: return itemId.substring(pos + 1, itemId.length());
0826: }
0827: }
0828:
0829: public static OrderByComparator getItemOrderByComparator(
0830: String orderByCol, String orderByType) {
0831:
0832: boolean orderByAsc = false;
0833:
0834: if (orderByType.equals("asc")) {
0835: orderByAsc = true;
0836: }
0837:
0838: OrderByComparator orderByComparator = null;
0839:
0840: if (orderByCol.equals("min-qty")) {
0841: orderByComparator = new ItemMinQuantityComparator(
0842: orderByAsc);
0843: } else if (orderByCol.equals("name")) {
0844: orderByComparator = new ItemNameComparator(orderByAsc);
0845: } else if (orderByCol.equals("price")) {
0846: orderByComparator = new ItemPriceComparator(orderByAsc);
0847: } else if (orderByCol.equals("sku")) {
0848: orderByComparator = new ItemSKUComparator(orderByAsc);
0849: } else if (orderByCol.equals("order-date")) {
0850: orderByComparator = new OrderDateComparator(orderByAsc);
0851: }
0852:
0853: return orderByComparator;
0854: }
0855:
0856: public static int getMinQuantity(ShoppingItem item)
0857: throws PortalException, SystemException {
0858:
0859: int minQuantity = item.getMinQuantity();
0860:
0861: List itemPrices = item.getItemPrices();
0862:
0863: for (int i = 0; i < itemPrices.size(); i++) {
0864: ShoppingItemPrice itemPrice = (ShoppingItemPrice) itemPrices
0865: .get(i);
0866:
0867: if (minQuantity > itemPrice.getMinQuantity()) {
0868: minQuantity = itemPrice.getMinQuantity();
0869: }
0870: }
0871:
0872: return minQuantity;
0873: }
0874:
0875: public static String getPayPalNotifyURL(ThemeDisplay themeDisplay) {
0876: return themeDisplay.getURLPortal() + themeDisplay.getPathMain()
0877: + "/shopping/notify";
0878: }
0879:
0880: public static String getPayPalRedirectURL(
0881: ShoppingPreferences prefs, ShoppingOrder order,
0882: double total, String returnURL, String notifyURL)
0883: throws PortalException, SystemException {
0884:
0885: String payPalEmailAddress = HttpUtil.encodeURL(prefs
0886: .getPayPalEmailAddress());
0887:
0888: NumberFormat doubleFormat = NumberFormat.getNumberInstance();
0889:
0890: doubleFormat.setMaximumFractionDigits(2);
0891: doubleFormat.setMinimumFractionDigits(2);
0892:
0893: String amount = doubleFormat.format(total);
0894:
0895: returnURL = HttpUtil.encodeURL(returnURL);
0896: notifyURL = HttpUtil.encodeURL(notifyURL);
0897:
0898: String firstName = HttpUtil.encodeURL(order
0899: .getBillingFirstName());
0900: String lastName = HttpUtil
0901: .encodeURL(order.getBillingLastName());
0902: String address1 = HttpUtil.encodeURL(order.getBillingStreet());
0903: String city = HttpUtil.encodeURL(order.getBillingCity());
0904: String state = HttpUtil.encodeURL(order.getBillingState());
0905: String zip = HttpUtil.encodeURL(order.getBillingZip());
0906:
0907: String currencyCode = prefs.getCurrencyId();
0908:
0909: StringMaker sm = new StringMaker();
0910:
0911: sm.append("https://www.paypal.com/cgi-bin/webscr?");
0912: sm.append("cmd=_xclick&");
0913: sm.append("business=").append(payPalEmailAddress).append("&");
0914: sm.append("item_name=").append(order.getOrderId()).append("&");
0915: sm.append("item_number=").append(order.getOrderId())
0916: .append("&");
0917: sm.append("invoice=").append(order.getOrderId()).append("&");
0918: sm.append("amount=").append(amount).append("&");
0919: sm.append("return=").append(returnURL).append("&");
0920: sm.append("notify_url=").append(notifyURL).append("&");
0921: sm.append("first_name=").append(firstName).append("&");
0922: sm.append("last_name=").append(lastName).append("&");
0923: sm.append("address1=").append(address1).append("&");
0924: sm.append("city=").append(city).append("&");
0925: sm.append("state=").append(state).append("&");
0926: sm.append("zip=").append(zip).append("&");
0927: sm.append("no_note=1&");
0928: sm.append("currency_code=").append(currencyCode).append("");
0929:
0930: return sm.toString();
0931: }
0932:
0933: public static String getPayPalReturnURL(PortletURL portletURL,
0934: ShoppingOrder order) {
0935:
0936: portletURL.setParameter("struts_action", "/shopping/checkout");
0937: portletURL.setParameter(Constants.CMD, Constants.VIEW);
0938: portletURL.setParameter("orderId", String.valueOf(order
0939: .getOrderId()));
0940:
0941: return portletURL.toString();
0942: }
0943:
0944: public static String getPpPaymentStatus(String ppPaymentStatus) {
0945: if ((ppPaymentStatus == null) || (ppPaymentStatus.length() < 2)
0946: || (ppPaymentStatus.equals("checkout"))) {
0947:
0948: return ShoppingOrderImpl.STATUS_CHECKOUT;
0949: } else {
0950: return Character.toUpperCase(ppPaymentStatus.charAt(0))
0951: + ppPaymentStatus.substring(1, ppPaymentStatus
0952: .length());
0953: }
0954: }
0955:
0956: public static String getPpPaymentStatus(ShoppingOrder order,
0957: PageContext pageContext) throws PortalException {
0958:
0959: String ppPaymentStatus = order.getPpPaymentStatus();
0960:
0961: if (ppPaymentStatus.equals(ShoppingOrderImpl.STATUS_CHECKOUT)) {
0962: ppPaymentStatus = "checkout";
0963: } else {
0964: ppPaymentStatus = ppPaymentStatus.toLowerCase();
0965: }
0966:
0967: return LanguageUtil.get(pageContext, ppPaymentStatus);
0968: }
0969:
0970: public static boolean isInStock(ShoppingItem item) {
0971: if (!item.isFields()) {
0972: if (item.getStockQuantity() > 0) {
0973: return true;
0974: } else {
0975: return false;
0976: }
0977: } else {
0978: String[] fieldsQuantities = item.getFieldsQuantitiesArray();
0979:
0980: for (int i = 0; i < fieldsQuantities.length; i++) {
0981: if (GetterUtil.getInteger(fieldsQuantities[i]) > 0) {
0982: return true;
0983: }
0984: }
0985:
0986: return false;
0987: }
0988: }
0989:
0990: public static boolean isInStock(ShoppingItem item,
0991: ShoppingItemField[] itemFields, String[] fieldsArray,
0992: Integer orderedQuantity) {
0993:
0994: if (!item.isFields()) {
0995: int stockQuantity = item.getStockQuantity();
0996:
0997: if ((stockQuantity > 0)
0998: && (stockQuantity >= orderedQuantity.intValue())) {
0999:
1000: return true;
1001: } else {
1002: return false;
1003: }
1004: } else {
1005: int rowPos = getFieldsQuantitiesPos(item, itemFields,
1006: fieldsArray);
1007:
1008: String[] fieldsQuantities = item.getFieldsQuantitiesArray();
1009:
1010: int stockQuantity = GetterUtil
1011: .getInteger(fieldsQuantities[rowPos]);
1012:
1013: try {
1014: if ((stockQuantity > 0)
1015: && (stockQuantity >= orderedQuantity.intValue())) {
1016:
1017: return true;
1018: }
1019: } catch (Exception e) {
1020: }
1021:
1022: return false;
1023: }
1024: }
1025:
1026: public static boolean meetsMinOrder(ShoppingPreferences prefs,
1027: Map items) throws PortalException, SystemException {
1028:
1029: if ((prefs.getMinOrder() > 0)
1030: && (calculateSubtotal(items) < prefs.getMinOrder())) {
1031:
1032: return false;
1033: } else {
1034: return true;
1035: }
1036: }
1037:
1038: private static ShoppingItemPrice _getItemPrice(ShoppingItem item,
1039: int count) throws PortalException, SystemException {
1040:
1041: ShoppingItemPrice itemPrice = null;
1042:
1043: List itemPrices = item.getItemPrices();
1044:
1045: for (int i = 0; i < itemPrices.size(); i++) {
1046: ShoppingItemPrice temp = (ShoppingItemPrice) itemPrices
1047: .get(i);
1048:
1049: int minQty = temp.getMinQuantity();
1050: int maxQty = temp.getMaxQuantity();
1051:
1052: if ((temp.getStatus() != ShoppingItemPriceImpl.STATUS_INACTIVE)
1053: && (count >= minQty)
1054: && (count < maxQty || maxQty == 0)) {
1055:
1056: itemPrice = temp;
1057: }
1058: }
1059:
1060: if (itemPrice == null) {
1061: return ShoppingItemPriceUtil.create(0);
1062: }
1063:
1064: return itemPrice;
1065: }
1066:
1067: }
|