001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.shopping.util;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.language.LanguageUtil;
020    import com.liferay.portal.kernel.portlet.LiferayWindowState;
021    import com.liferay.portal.kernel.util.CharPool;
022    import com.liferay.portal.kernel.util.Constants;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.HttpUtil;
025    import com.liferay.portal.kernel.util.MathUtil;
026    import com.liferay.portal.kernel.util.OrderByComparator;
027    import com.liferay.portal.kernel.util.StringBundler;
028    import com.liferay.portal.kernel.util.StringPool;
029    import com.liferay.portal.kernel.util.StringUtil;
030    import com.liferay.portal.theme.ThemeDisplay;
031    import com.liferay.portal.util.WebKeys;
032    import com.liferay.portlet.shopping.NoSuchCartException;
033    import com.liferay.portlet.shopping.model.ShoppingCart;
034    import com.liferay.portlet.shopping.model.ShoppingCartItem;
035    import com.liferay.portlet.shopping.model.ShoppingCategory;
036    import com.liferay.portlet.shopping.model.ShoppingCoupon;
037    import com.liferay.portlet.shopping.model.ShoppingCouponConstants;
038    import com.liferay.portlet.shopping.model.ShoppingItem;
039    import com.liferay.portlet.shopping.model.ShoppingItemField;
040    import com.liferay.portlet.shopping.model.ShoppingItemPrice;
041    import com.liferay.portlet.shopping.model.ShoppingItemPriceConstants;
042    import com.liferay.portlet.shopping.model.ShoppingOrder;
043    import com.liferay.portlet.shopping.model.ShoppingOrderConstants;
044    import com.liferay.portlet.shopping.model.ShoppingOrderItem;
045    import com.liferay.portlet.shopping.model.impl.ShoppingCartImpl;
046    import com.liferay.portlet.shopping.service.ShoppingCartLocalServiceUtil;
047    import com.liferay.portlet.shopping.service.ShoppingCategoryLocalServiceUtil;
048    import com.liferay.portlet.shopping.service.ShoppingOrderItemLocalServiceUtil;
049    import com.liferay.portlet.shopping.service.persistence.ShoppingItemPriceUtil;
050    import com.liferay.portlet.shopping.util.comparator.ItemMinQuantityComparator;
051    import com.liferay.portlet.shopping.util.comparator.ItemNameComparator;
052    import com.liferay.portlet.shopping.util.comparator.ItemPriceComparator;
053    import com.liferay.portlet.shopping.util.comparator.ItemSKUComparator;
054    import com.liferay.portlet.shopping.util.comparator.OrderDateComparator;
055    
056    import java.text.NumberFormat;
057    
058    import java.util.ArrayList;
059    import java.util.HashMap;
060    import java.util.HashSet;
061    import java.util.Iterator;
062    import java.util.List;
063    import java.util.Locale;
064    import java.util.Map;
065    import java.util.Set;
066    
067    import javax.portlet.PortletRequest;
068    import javax.portlet.PortletSession;
069    import javax.portlet.PortletURL;
070    import javax.portlet.RenderRequest;
071    import javax.portlet.RenderResponse;
072    import javax.portlet.WindowState;
073    
074    import javax.servlet.jsp.PageContext;
075    
076    /**
077     * @author Brian Wing Shun Chan
078     */
079    public class ShoppingUtil {
080    
081            public static double calculateActualPrice(ShoppingItem item) {
082                    return item.getPrice() - calculateDiscountPrice(item);
083            }
084    
085            public static double calculateActualPrice(ShoppingItem item, int count)
086                    throws PortalException, SystemException {
087    
088                    return calculatePrice(item, count) -
089                            calculateDiscountPrice(item, count);
090            }
091    
092            public static double calculateActualPrice(ShoppingItemPrice itemPrice) {
093                    return itemPrice.getPrice() - calculateDiscountPrice(itemPrice);
094            }
095    
096            public static double calculateActualSubtotal(
097                    List<ShoppingOrderItem> orderItems) {
098    
099                    double subtotal = 0.0;
100    
101                    for (ShoppingOrderItem orderItem : orderItems) {
102                            subtotal += orderItem.getPrice() * orderItem.getQuantity();
103                    }
104    
105                    return subtotal;
106            }
107    
108            public static double calculateActualSubtotal(
109                            Map<ShoppingCartItem, Integer> items)
110                    throws PortalException, SystemException {
111    
112                    return calculateSubtotal(items) - calculateDiscountSubtotal(items);
113            }
114    
115            public static double calculateAlternativeShipping(
116                            Map<ShoppingCartItem, Integer> items, int altShipping)
117                    throws PortalException, SystemException {
118    
119                    double shipping = calculateShipping(items);
120                    double alternativeShipping = shipping;
121    
122                    ShoppingPreferences preferences = null;
123    
124                    Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
125                            items.entrySet().iterator();
126    
127                    while (itr.hasNext()) {
128                            Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
129    
130                            ShoppingCartItem cartItem = entry.getKey();
131    
132                            ShoppingItem item = cartItem.getItem();
133    
134                            if (preferences == null) {
135                                    ShoppingCategory category = item.getCategory();
136    
137                                    preferences = ShoppingPreferences.getInstance(
138                                            category.getCompanyId(), category.getGroupId());
139    
140                                    break;
141                            }
142                    }
143    
144                    // Calculate alternative shipping if shopping is configured to use
145                    // alternative shipping and shipping price is greater than 0
146    
147                    if ((preferences != null) &&
148                            (preferences.useAlternativeShipping()) && (shipping > 0)) {
149    
150                            double altShippingDelta = 0.0;
151    
152                            try {
153                                    altShippingDelta = GetterUtil.getDouble(
154                                            preferences.getAlternativeShipping()[1][altShipping]);
155                            }
156                            catch (Exception e) {
157                                    return alternativeShipping;
158                            }
159    
160                            if (altShippingDelta > 0) {
161                                    alternativeShipping = shipping * altShippingDelta;
162                            }
163                    }
164    
165                    return alternativeShipping;
166            }
167    
168            public static double calculateCouponDiscount(
169                            Map<ShoppingCartItem, Integer> items, ShoppingCoupon coupon)
170                    throws PortalException, SystemException {
171    
172                    return calculateCouponDiscount(items, null, coupon);
173            }
174    
175            public static double calculateCouponDiscount(
176                            Map<ShoppingCartItem, Integer> items, String stateId,
177                            ShoppingCoupon coupon)
178                    throws PortalException, SystemException {
179    
180                    double discount = 0.0;
181    
182                    if ((coupon == null) || !coupon.isActive() ||
183                            !coupon.hasValidDateRange()) {
184    
185                            return discount;
186                    }
187    
188                    String[] categoryIds = StringUtil.split(coupon.getLimitCategories());
189                    String[] skus = StringUtil.split(coupon.getLimitSkus());
190    
191                    if ((categoryIds.length > 0) || (skus.length > 0)) {
192                            Set<String> categoryIdsSet = new HashSet<String>();
193    
194                            for (String categoryId : categoryIds) {
195                                    categoryIdsSet.add(categoryId);
196                            }
197    
198                            Set<String> skusSet = new HashSet<String>();
199    
200                            for (String sku : skus) {
201                                    skusSet.add(sku);
202                            }
203    
204                            Map<ShoppingCartItem, Integer> newItems =
205                                    new HashMap<ShoppingCartItem, Integer>();
206    
207                            Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
208                                    items.entrySet().iterator();
209    
210                            while (itr.hasNext()) {
211                                    Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
212    
213                                    ShoppingCartItem cartItem = entry.getKey();
214                                    Integer count = entry.getValue();
215    
216                                    ShoppingItem item = cartItem.getItem();
217    
218                                    if (((categoryIdsSet.size() > 0) &&
219                                             (categoryIdsSet.contains(
220                                                    String.valueOf(item.getCategoryId())))) ||
221                                            ((skusSet.size() > 0) &&
222                                             (skusSet.contains(item.getSku())))) {
223    
224                                            newItems.put(cartItem, count);
225                                    }
226                            }
227    
228                            items = newItems;
229                    }
230    
231                    double actualSubtotal = calculateActualSubtotal(items);
232    
233                    if ((coupon.getMinOrder() > 0) &&
234                            (coupon.getMinOrder() > actualSubtotal)) {
235    
236                            return discount;
237                    }
238    
239                    String type = coupon.getDiscountType();
240    
241                    if (type.equals(ShoppingCouponConstants.DISCOUNT_TYPE_PERCENTAGE)) {
242                            discount = actualSubtotal * coupon.getDiscount();
243                    }
244                    else if (type.equals(ShoppingCouponConstants.DISCOUNT_TYPE_ACTUAL)) {
245                            discount = coupon.getDiscount();
246                    }
247                    else if (type.equals(
248                                            ShoppingCouponConstants.DISCOUNT_TYPE_FREE_SHIPPING)) {
249    
250                            discount = calculateShipping(items);
251                    }
252                    else if (type.equals(ShoppingCouponConstants.DISCOUNT_TYPE_TAX_FREE)) {
253                            if (stateId != null) {
254                                    discount = calculateTax(items, stateId);
255                            }
256                    }
257    
258                    return discount;
259            }
260    
261            public static double calculateDiscountPercent(
262                            Map<ShoppingCartItem, Integer> items)
263                    throws PortalException, SystemException {
264    
265                    double discount = calculateDiscountSubtotal(
266                            items) / calculateSubtotal(items);
267    
268                    if (Double.isNaN(discount) || Double.isInfinite(discount)) {
269                            discount = 0.0;
270                    }
271    
272                    return discount;
273            }
274    
275            public static double calculateDiscountPrice(ShoppingItem item) {
276                    return item.getPrice() * item.getDiscount();
277            }
278    
279            public static double calculateDiscountPrice(ShoppingItem item, int count)
280                    throws PortalException, SystemException {
281    
282                    ShoppingItemPrice itemPrice = _getItemPrice(item, count);
283    
284                    return itemPrice.getPrice() * itemPrice.getDiscount() * count;
285            }
286    
287            public static double calculateDiscountPrice(ShoppingItemPrice itemPrice) {
288                    return itemPrice.getPrice() * itemPrice.getDiscount();
289            }
290    
291            public static double calculateDiscountSubtotal(
292                            Map<ShoppingCartItem, Integer> items)
293                    throws PortalException, SystemException {
294    
295                    double subtotal = 0.0;
296    
297                    Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
298                            items.entrySet().iterator();
299    
300                    while (itr.hasNext()) {
301                            Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
302    
303                            ShoppingCartItem cartItem = entry.getKey();
304                            Integer count = entry.getValue();
305    
306                            ShoppingItem item = cartItem.getItem();
307    
308                            subtotal += calculateDiscountPrice(item, count.intValue());
309                    }
310    
311                    return subtotal;
312            }
313    
314            public static double calculateInsurance(
315                            Map<ShoppingCartItem, Integer> items)
316                    throws PortalException, SystemException {
317    
318                    double insurance = 0.0;
319                    double subtotal = 0.0;
320    
321                    ShoppingPreferences preferences = null;
322    
323                    Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
324                            items.entrySet().iterator();
325    
326                    while (itr.hasNext()) {
327                            Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
328    
329                            ShoppingCartItem cartItem = entry.getKey();
330                            Integer count = entry.getValue();
331    
332                            ShoppingItem item = cartItem.getItem();
333    
334                            if (preferences == null) {
335                                    ShoppingCategory category = item.getCategory();
336    
337                                    preferences = ShoppingPreferences.getInstance(
338                                            category.getCompanyId(), category.getGroupId());
339                            }
340    
341                            ShoppingItemPrice itemPrice = _getItemPrice(item, count.intValue());
342    
343                            subtotal += calculateActualPrice(itemPrice) * count.intValue();
344                    }
345    
346                    if ((preferences != null) && (subtotal > 0)) {
347                            double insuranceRate = 0.0;
348    
349                            double[] range = ShoppingPreferences.INSURANCE_RANGE;
350    
351                            for (int i = 0; i < range.length - 1; i++) {
352                                    if (subtotal > range[i] && subtotal <= range[i + 1]) {
353                                            int rangeId = i / 2;
354                                            if (MathUtil.isOdd(i)) {
355                                                    rangeId = (i + 1) / 2;
356                                            }
357    
358                                            insuranceRate = GetterUtil.getDouble(
359                                                    preferences.getInsurance()[rangeId]);
360                                    }
361                            }
362    
363                            String formula = preferences.getInsuranceFormula();
364    
365                            if (formula.equals("flat")) {
366                                    insurance += insuranceRate;
367                            }
368                            else if (formula.equals("percentage")) {
369                                    insurance += subtotal * insuranceRate;
370                            }
371                    }
372    
373                    return insurance;
374            }
375    
376            public static double calculatePrice(ShoppingItem item, int count)
377                    throws PortalException, SystemException {
378    
379                    ShoppingItemPrice itemPrice = _getItemPrice(item, count);
380    
381                    return itemPrice.getPrice() * count;
382            }
383    
384            public static double calculateShipping(Map<ShoppingCartItem, Integer> items)
385                    throws PortalException, SystemException {
386    
387                    double shipping = 0.0;
388                    double subtotal = 0.0;
389    
390                    ShoppingPreferences preferences = null;
391    
392                    Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
393                            items.entrySet().iterator();
394    
395                    while (itr.hasNext()) {
396                            Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
397    
398                            ShoppingCartItem cartItem = entry.getKey();
399                            Integer count = entry.getValue();
400    
401                            ShoppingItem item = cartItem.getItem();
402    
403                            if (preferences == null) {
404                                    ShoppingCategory category = item.getCategory();
405    
406                                    preferences = ShoppingPreferences.getInstance(
407                                            category.getCompanyId(), category.getGroupId());
408                            }
409    
410                            if (item.isRequiresShipping()) {
411                                    ShoppingItemPrice itemPrice = _getItemPrice(
412                                            item, count.intValue());
413    
414                                    if (itemPrice.isUseShippingFormula()) {
415                                            subtotal +=
416                                                    calculateActualPrice(itemPrice) * count.intValue();
417                                    }
418                                    else {
419                                            shipping += itemPrice.getShipping() * count.intValue();
420                                    }
421                            }
422                    }
423    
424                    if ((preferences != null) && (subtotal > 0)) {
425                            double shippingRate = 0.0;
426    
427                            double[] range = ShoppingPreferences.SHIPPING_RANGE;
428    
429                            for (int i = 0; i < range.length - 1; i++) {
430                                    if (subtotal > range[i] && subtotal <= range[i + 1]) {
431                                            int rangeId = i / 2;
432                                            if (MathUtil.isOdd(i)) {
433                                                    rangeId = (i + 1) / 2;
434                                            }
435    
436                                            shippingRate = GetterUtil.getDouble(
437                                                    preferences.getShipping()[rangeId]);
438                                    }
439                            }
440    
441                            String formula = preferences.getShippingFormula();
442    
443                            if (formula.equals("flat")) {
444                                    shipping += shippingRate;
445                            }
446                            else if (formula.equals("percentage")) {
447                                    shipping += subtotal * shippingRate;
448                            }
449                    }
450    
451                    return shipping;
452            }
453    
454            public static double calculateSubtotal(Map<ShoppingCartItem, Integer> items)
455                    throws PortalException, SystemException {
456    
457                    double subtotal = 0.0;
458    
459                    Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
460                            items.entrySet().iterator();
461    
462                    while (itr.hasNext()) {
463                            Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
464    
465                            ShoppingCartItem cartItem = entry.getKey();
466                            Integer count = entry.getValue();
467    
468                            ShoppingItem item = cartItem.getItem();
469    
470                            subtotal += calculatePrice(item, count.intValue());
471                    }
472    
473                    return subtotal;
474            }
475    
476            public static double calculateTax(
477                            Map<ShoppingCartItem, Integer> items, String stateId)
478                    throws PortalException, SystemException {
479    
480                    double tax = 0.0;
481    
482                    ShoppingPreferences preferences = null;
483    
484                    Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
485                            items.entrySet().iterator();
486    
487                    while (itr.hasNext()) {
488                            Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
489    
490                            ShoppingCartItem cartItem = entry.getKey();
491    
492                            ShoppingItem item = cartItem.getItem();
493    
494                            if (preferences == null) {
495                                    ShoppingCategory category = item.getCategory();
496    
497                                    preferences = ShoppingPreferences.getInstance(
498                                            category.getCompanyId(), category.getGroupId());
499    
500                                    break;
501                            }
502                    }
503    
504                    if ((preferences != null) &&
505                            (preferences.getTaxState().equals(stateId))) {
506    
507                            double subtotal = 0.0;
508    
509                            itr = items.entrySet().iterator();
510    
511                            while (itr.hasNext()) {
512                                    Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
513    
514                                    ShoppingCartItem cartItem = entry.getKey();
515                                    Integer count = entry.getValue();
516    
517                                    ShoppingItem item = cartItem.getItem();
518    
519                                    if (item.isTaxable()) {
520                                            subtotal += calculatePrice(item, count.intValue());
521                                    }
522                            }
523    
524                            tax = preferences.getTaxRate() * subtotal;
525                    }
526    
527                    return tax;
528            }
529    
530            public static double calculateTotal(
531                            Map<ShoppingCartItem, Integer> items, String stateId,
532                            ShoppingCoupon coupon, int altShipping, boolean insure)
533                    throws PortalException, SystemException {
534    
535                    double actualSubtotal = calculateActualSubtotal(items);
536                    double tax = calculateTax(items, stateId);
537                    double shipping = calculateAlternativeShipping(items, altShipping);
538    
539                    double insurance = 0.0;
540                    if (insure) {
541                            insurance = calculateInsurance(items);
542                    }
543    
544                    double couponDiscount = calculateCouponDiscount(items, stateId, coupon);
545    
546                    double total =
547                            actualSubtotal + tax + shipping + insurance - couponDiscount;
548    
549                    if (total < 0) {
550                            total = 0.0;
551                    }
552    
553                    return total;
554            }
555    
556            public static double calculateTotal(ShoppingOrder order)
557                    throws SystemException {
558    
559                    List<ShoppingOrderItem> orderItems =
560                            ShoppingOrderItemLocalServiceUtil.getOrderItems(order.getOrderId());
561    
562                    double total =
563                            calculateActualSubtotal(orderItems) + order.getTax() +
564                                    order.getShipping() + order.getInsurance() -
565                                            order.getCouponDiscount();
566    
567                    if (total < 0) {
568                            total = 0.0;
569                    }
570    
571                    return total;
572            }
573    
574            public static String getBreadcrumbs(
575                            long categoryId, PageContext pageContext,
576                            RenderRequest renderRequest, RenderResponse renderResponse)
577                    throws Exception {
578    
579                    ShoppingCategory category = null;
580    
581                    try {
582                            category = ShoppingCategoryLocalServiceUtil.getCategory(categoryId);
583                    }
584                    catch (Exception e) {
585                    }
586    
587                    return getBreadcrumbs(
588                            category, pageContext, renderRequest, renderResponse);
589            }
590    
591            public static String getBreadcrumbs(
592                            ShoppingCategory category, PageContext pageContext,
593                            RenderRequest renderRequest, RenderResponse renderResponse)
594                    throws Exception {
595    
596                    PortletURL categoriesURL = renderResponse.createRenderURL();
597    
598                    WindowState windowState = renderRequest.getWindowState();
599    
600                    if (windowState.equals(LiferayWindowState.POP_UP)) {
601                            categoriesURL.setWindowState(LiferayWindowState.POP_UP);
602    
603                            categoriesURL.setParameter(
604                                    "struts_action", "/shopping/select_category");
605                    }
606                    else {
607                            //categoriesURL.setWindowState(WindowState.MAXIMIZED);
608    
609                            categoriesURL.setParameter("struts_action", "/shopping/view");
610                            categoriesURL.setParameter("tabs1", "categories");
611                    }
612    
613                    String categoriesLink =
614                            "<a href=\"" + categoriesURL.toString() + "\">" +
615                                    LanguageUtil.get(pageContext, "categories") + "</a>";
616    
617                    if (category == null) {
618                            return "<span class=\"first last\">" + categoriesLink + "</span>";
619                    }
620    
621                    String breadcrumbs = StringPool.BLANK;
622    
623                    if (category != null) {
624                            for (int i = 0;; i++) {
625                                    category = category.toEscapedModel();
626    
627                                    PortletURL portletURL = renderResponse.createRenderURL();
628    
629                                    if (windowState.equals(LiferayWindowState.POP_UP)) {
630                                            portletURL.setWindowState(LiferayWindowState.POP_UP);
631    
632                                            portletURL.setParameter(
633                                                    "struts_action", "/shopping/select_category");
634                                            portletURL.setParameter(
635                                                    "categoryId", String.valueOf(category.getCategoryId()));
636                                    }
637                                    else {
638                                            //portletURL.setWindowState(WindowState.MAXIMIZED);
639    
640                                            portletURL.setParameter("struts_action", "/shopping/view");
641                                            portletURL.setParameter("tabs1", "categories");
642                                            portletURL.setParameter(
643                                                    "categoryId", String.valueOf(category.getCategoryId()));
644                                    }
645    
646                                    String categoryLink =
647                                            "<a href=\"" + portletURL.toString() + "\">" +
648                                                    category.getName() + "</a>";
649    
650                                    if (i == 0) {
651                                            breadcrumbs =
652                                                    "<span class=\"last\">" + categoryLink + "</span>";
653                                    }
654                                    else {
655                                            breadcrumbs = categoryLink + " &raquo; " + breadcrumbs;
656                                    }
657    
658                                    if (category.isRoot()) {
659                                            break;
660                                    }
661    
662                                    category = ShoppingCategoryLocalServiceUtil.getCategory(
663                                            category.getParentCategoryId());
664                            }
665                    }
666    
667                    breadcrumbs =
668                            "<span class=\"first\">" + categoriesLink + " &raquo; </span>" +
669                                    breadcrumbs;
670    
671                    return breadcrumbs;
672            }
673    
674            public static ShoppingCart getCart(PortletRequest portletRequest)
675                    throws PortalException, SystemException {
676    
677                    PortletSession portletSession = portletRequest.getPortletSession();
678    
679                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
680                            WebKeys.THEME_DISPLAY);
681    
682                    String sessionCartId =
683                            ShoppingCart.class.getName() + themeDisplay.getScopeGroupId();
684    
685                    if (themeDisplay.isSignedIn()) {
686                            ShoppingCart cart = (ShoppingCart)portletSession.getAttribute(
687                                    sessionCartId);
688    
689                            if (cart != null) {
690                                    portletSession.removeAttribute(sessionCartId);
691                            }
692    
693                            if ((cart != null) && (cart.getItemsSize() > 0)) {
694                                    cart = ShoppingCartLocalServiceUtil.updateCart(
695                                            themeDisplay.getUserId(), themeDisplay.getScopeGroupId(),
696                                            cart.getItemIds(), cart.getCouponCodes(),
697                                            cart.getAltShipping(), cart.isInsure());
698                            }
699                            else {
700                                    try {
701                                            cart = ShoppingCartLocalServiceUtil.getCart(
702                                                    themeDisplay.getUserId(),
703                                                    themeDisplay.getScopeGroupId());
704                                    }
705                                    catch (NoSuchCartException nsce) {
706                                            cart = getCart(themeDisplay);
707    
708                                            cart = ShoppingCartLocalServiceUtil.updateCart(
709                                                    themeDisplay.getUserId(),
710                                                    themeDisplay.getScopeGroupId(), cart.getItemIds(),
711                                                    cart.getCouponCodes(), cart.getAltShipping(),
712                                                    cart.isInsure());
713                                    }
714                            }
715    
716                            return cart;
717                    }
718                    else {
719                            ShoppingCart cart = (ShoppingCart)portletSession.getAttribute(
720                                    sessionCartId);
721    
722                            if (cart == null) {
723                                    cart = getCart(themeDisplay);
724    
725                                    portletSession.setAttribute(sessionCartId, cart);
726                            }
727    
728                            return cart;
729                    }
730            }
731    
732            public static ShoppingCart getCart(ThemeDisplay themeDisplay) {
733                    ShoppingCart cart = new ShoppingCartImpl();
734    
735                    cart.setGroupId(themeDisplay.getScopeGroupId());
736                    cart.setCompanyId(themeDisplay.getCompanyId());
737                    cart.setUserId(themeDisplay.getUserId());
738                    cart.setItemIds(StringPool.BLANK);
739                    cart.setCouponCodes(StringPool.BLANK);
740                    cart.setAltShipping(0);
741                    cart.setInsure(false);
742    
743                    return cart;
744            }
745    
746            public static int getFieldsQuantitiesPos(
747                    ShoppingItem item, ShoppingItemField[] itemFields,
748                    String[] fieldsArray) {
749    
750                    Set<String> fieldsValues = new HashSet<String>();
751    
752                    for (String fields : fieldsArray) {
753                            int pos = fields.indexOf("=");
754    
755                            String fieldValue = fields.substring(
756                                    pos + 1, fields.length()).trim();
757    
758                            fieldsValues.add(fieldValue);
759                    }
760    
761                    List<String> names = new ArrayList<String>();
762                    List<String[]> values = new ArrayList<String[]>();
763    
764                    for (int i = 0; i < itemFields.length; i++) {
765                            names.add(itemFields[i].getName());
766                            values.add(StringUtil.split(itemFields[i].getValues()));
767                    }
768    
769                    int numOfRows = 1;
770    
771                    for (String[] vArray : values) {
772                            numOfRows = numOfRows * vArray.length;
773                    }
774    
775                    int rowPos = 0;
776    
777                    for (int i = 0; i < numOfRows; i++) {
778                            boolean match = true;
779    
780                            for (int j = 0; j < names.size(); j++) {
781                                    int numOfRepeats = 1;
782    
783                                    for (int k = j + 1; k < values.size(); k++) {
784                                            String[] vArray = values.get(k);
785    
786                                            numOfRepeats = numOfRepeats * vArray.length;
787                                    }
788    
789                                    String[] vArray = values.get(j);
790    
791                                    int arrayPos;
792                                    for (arrayPos = i / numOfRepeats;
793                                             arrayPos >= vArray.length;
794                                             arrayPos = arrayPos - vArray.length) {
795                                    }
796    
797                                    if (!fieldsValues.contains(vArray[arrayPos].trim())) {
798                                            match = false;
799    
800                                            break;
801                                    }
802                            }
803    
804                            if (match) {
805                                    rowPos = i;
806    
807                                    break;
808                            }
809                    }
810    
811                    return rowPos;
812            }
813    
814            public static String getItemFields(String itemId) {
815                    int pos = itemId.indexOf(CharPool.PIPE);
816    
817                    if (pos == -1) {
818                            return StringPool.BLANK;
819                    }
820                    else {
821                            return itemId.substring(pos + 1, itemId.length());
822                    }
823            }
824    
825            public static long getItemId(String itemId) {
826                    int pos = itemId.indexOf(CharPool.PIPE);
827    
828                    if (pos != -1) {
829                            itemId = itemId.substring(0, pos);
830                    }
831    
832                    return GetterUtil.getLong(itemId);
833            }
834    
835            public static OrderByComparator getItemOrderByComparator(
836                    String orderByCol, String orderByType) {
837    
838                    boolean orderByAsc = false;
839    
840                    if (orderByType.equals("asc")) {
841                            orderByAsc = true;
842                    }
843    
844                    OrderByComparator orderByComparator = null;
845    
846                    if (orderByCol.equals("min-qty")) {
847                            orderByComparator = new ItemMinQuantityComparator(orderByAsc);
848                    }
849                    else if (orderByCol.equals("name")) {
850                            orderByComparator = new ItemNameComparator(orderByAsc);
851                    }
852                    else if (orderByCol.equals("price")) {
853                            orderByComparator = new ItemPriceComparator(orderByAsc);
854                    }
855                    else if (orderByCol.equals("sku")) {
856                            orderByComparator = new ItemSKUComparator(orderByAsc);
857                    }
858                    else if (orderByCol.equals("order-date")) {
859                            orderByComparator = new OrderDateComparator(orderByAsc);
860                    }
861    
862                    return orderByComparator;
863            }
864    
865            public static int getMinQuantity(ShoppingItem item)
866                    throws PortalException, SystemException {
867    
868                    int minQuantity = item.getMinQuantity();
869    
870                    List<ShoppingItemPrice> itemPrices = item.getItemPrices();
871    
872                    for (ShoppingItemPrice itemPrice : itemPrices) {
873                            if (minQuantity > itemPrice.getMinQuantity()) {
874                                    minQuantity = itemPrice.getMinQuantity();
875                            }
876                    }
877    
878                    return minQuantity;
879            }
880    
881            public static String getPayPalNotifyURL(ThemeDisplay themeDisplay) {
882                    return themeDisplay.getPortalURL() + themeDisplay.getPathMain() +
883                            "/shopping/notify";
884            }
885    
886            public static String getPayPalRedirectURL(
887                    ShoppingPreferences preferences, ShoppingOrder order, double total,
888                    String returnURL, String notifyURL) {
889    
890                    String payPalEmailAddress = HttpUtil.encodeURL(
891                            preferences.getPayPalEmailAddress());
892    
893                    NumberFormat doubleFormat = NumberFormat.getNumberInstance(
894                            Locale.ENGLISH);
895    
896                    doubleFormat.setMaximumFractionDigits(2);
897                    doubleFormat.setMinimumFractionDigits(2);
898    
899                    String amount = doubleFormat.format(total);
900    
901                    returnURL = HttpUtil.encodeURL(returnURL);
902                    notifyURL = HttpUtil.encodeURL(notifyURL);
903    
904                    String firstName = HttpUtil.encodeURL(order.getBillingFirstName());
905                    String lastName = HttpUtil.encodeURL(order.getBillingLastName());
906                    String address1 = HttpUtil.encodeURL(order.getBillingStreet());
907                    String city = HttpUtil.encodeURL(order.getBillingCity());
908                    String state = HttpUtil.encodeURL(order.getBillingState());
909                    String zip = HttpUtil.encodeURL(order.getBillingZip());
910    
911                    String currencyCode = preferences.getCurrencyId();
912    
913                    StringBundler sb = new StringBundler(45);
914    
915                    sb.append("https://www.paypal.com/cgi-bin/webscr?");
916                    sb.append("cmd=_xclick&");
917                    sb.append("business=").append(payPalEmailAddress).append("&");
918                    sb.append("item_name=").append(order.getNumber()).append("&");
919                    sb.append("item_number=").append(order.getNumber()).append("&");
920                    sb.append("invoice=").append(order.getNumber()).append("&");
921                    sb.append("amount=").append(amount).append("&");
922                    sb.append("return=").append(returnURL).append("&");
923                    sb.append("notify_url=").append(notifyURL).append("&");
924                    sb.append("first_name=").append(firstName).append("&");
925                    sb.append("last_name=").append(lastName).append("&");
926                    sb.append("address1=").append(address1).append("&");
927                    sb.append("city=").append(city).append("&");
928                    sb.append("state=").append(state).append("&");
929                    sb.append("zip=").append(zip).append("&");
930                    sb.append("no_note=1&");
931                    sb.append("currency_code=").append(currencyCode).append("");
932    
933                    return sb.toString();
934            }
935    
936            public static String getPayPalReturnURL(
937                    PortletURL portletURL, ShoppingOrder order) {
938    
939                    portletURL.setParameter("struts_action", "/shopping/checkout");
940                    portletURL.setParameter(Constants.CMD, Constants.VIEW);
941                    portletURL.setParameter("orderId", String.valueOf(order.getOrderId()));
942    
943                    return portletURL.toString();
944            }
945    
946            public static String getPpPaymentStatus(
947                    ShoppingOrder order, PageContext pageContext) {
948    
949                    String ppPaymentStatus = order.getPpPaymentStatus();
950    
951                    if (ppPaymentStatus.equals(ShoppingOrderConstants.STATUS_CHECKOUT)) {
952                            ppPaymentStatus = "checkout";
953                    }
954                    else {
955                            ppPaymentStatus = ppPaymentStatus.toLowerCase();
956                    }
957    
958                    return LanguageUtil.get(pageContext, ppPaymentStatus);
959            }
960    
961            public static String getPpPaymentStatus(String ppPaymentStatus) {
962                    if ((ppPaymentStatus == null) || (ppPaymentStatus.length() < 2) ||
963                            (ppPaymentStatus.equals("checkout"))) {
964    
965                            return ShoppingOrderConstants.STATUS_CHECKOUT;
966                    }
967                    else {
968                            return Character.toUpperCase(ppPaymentStatus.charAt(0)) +
969                                    ppPaymentStatus.substring(1, ppPaymentStatus.length());
970                    }
971            }
972    
973            public static boolean isInStock(ShoppingItem item) {
974                    if (!item.isFields()) {
975                            if (item.getStockQuantity() > 0) {
976                                    return true;
977                            }
978                            else {
979                                    return false;
980                            }
981                    }
982                    else {
983                            String[] fieldsQuantities = item.getFieldsQuantitiesArray();
984    
985                            for (int i = 0; i < fieldsQuantities.length; i++) {
986                                    if (GetterUtil.getInteger(fieldsQuantities[i]) > 0) {
987                                            return true;
988                                    }
989                            }
990    
991                            return false;
992                    }
993            }
994    
995            public static boolean isInStock(
996                    ShoppingItem item, ShoppingItemField[] itemFields, String[] fieldsArray,
997                    Integer orderedQuantity) {
998    
999                    if (!item.isFields()) {
1000                            int stockQuantity = item.getStockQuantity();
1001    
1002                            if ((stockQuantity > 0) &&
1003                                    (stockQuantity >= orderedQuantity.intValue())) {
1004    
1005                                    return true;
1006                            }
1007                            else {
1008                                    return false;
1009                            }
1010                    }
1011                    else {
1012                            String[] fieldsQuantities = item.getFieldsQuantitiesArray();
1013    
1014                            int stockQuantity = 0;
1015    
1016                            if (fieldsQuantities.length > 0) {
1017                                    int rowPos = getFieldsQuantitiesPos(
1018                                            item, itemFields, fieldsArray);
1019    
1020                                    stockQuantity = GetterUtil.getInteger(fieldsQuantities[rowPos]);
1021                            }
1022    
1023                            try {
1024                                    if ((stockQuantity > 0) &&
1025                                            (stockQuantity >= orderedQuantity.intValue())) {
1026    
1027                                            return true;
1028                                    }
1029                            }
1030                            catch (Exception e) {
1031                            }
1032    
1033                            return false;
1034                    }
1035            }
1036    
1037            public static boolean meetsMinOrder(
1038                            ShoppingPreferences preferences,
1039                            Map<ShoppingCartItem, Integer> items)
1040                    throws PortalException, SystemException {
1041    
1042                    if ((preferences.getMinOrder() > 0) &&
1043                            (calculateSubtotal(items) < preferences.getMinOrder())) {
1044    
1045                            return false;
1046                    }
1047                    else {
1048                            return true;
1049                    }
1050            }
1051    
1052            private static ShoppingItemPrice _getItemPrice(ShoppingItem item, int count)
1053                    throws PortalException, SystemException {
1054    
1055                    ShoppingItemPrice itemPrice = null;
1056    
1057                    List<ShoppingItemPrice> itemPrices = item.getItemPrices();
1058    
1059                    for (ShoppingItemPrice temp : itemPrices) {
1060                            int minQty = temp.getMinQuantity();
1061                            int maxQty = temp.getMaxQuantity();
1062    
1063                            if ((temp.getStatus() !=
1064                                            ShoppingItemPriceConstants.STATUS_INACTIVE)) {
1065    
1066                                    if ((count >= minQty) && ((count <= maxQty) || (maxQty == 0))) {
1067                                            return temp;
1068                                    }
1069    
1070                                    if ((count > maxQty) &&
1071                                            ((itemPrice == null) ||
1072                                             (itemPrice.getMaxQuantity() < maxQty))) {
1073    
1074                                            itemPrice = temp;
1075                                    }
1076                            }
1077                    }
1078    
1079                    if (itemPrice == null) {
1080                            return ShoppingItemPriceUtil.create(0);
1081                    }
1082    
1083                    return itemPrice;
1084            }
1085    
1086    }