001
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
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
145
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) && skusSet.contains(item.getSku()))) {
222
223 newItems.put(cartItem, count);
224 }
225 }
226
227 items = newItems;
228 }
229
230 double actualSubtotal = calculateActualSubtotal(items);
231
232 if ((coupon.getMinOrder() > 0) &&
233 (coupon.getMinOrder() > actualSubtotal)) {
234
235 return discount;
236 }
237
238 String type = coupon.getDiscountType();
239
240 if (type.equals(ShoppingCouponConstants.DISCOUNT_TYPE_PERCENTAGE)) {
241 discount = actualSubtotal * coupon.getDiscount();
242 }
243 else if (type.equals(ShoppingCouponConstants.DISCOUNT_TYPE_ACTUAL)) {
244 discount = coupon.getDiscount();
245 }
246 else if (type.equals(
247 ShoppingCouponConstants.DISCOUNT_TYPE_FREE_SHIPPING)) {
248
249 discount = calculateShipping(items);
250 }
251 else if (type.equals(ShoppingCouponConstants.DISCOUNT_TYPE_TAX_FREE)) {
252 if (stateId != null) {
253 discount = calculateTax(items, stateId);
254 }
255 }
256
257 return discount;
258 }
259
260 public static double calculateDiscountPercent(
261 Map<ShoppingCartItem, Integer> items)
262 throws PortalException, SystemException {
263
264 double discount = calculateDiscountSubtotal(
265 items) / calculateSubtotal(items);
266
267 if (Double.isNaN(discount) || Double.isInfinite(discount)) {
268 discount = 0.0;
269 }
270
271 return discount;
272 }
273
274 public static double calculateDiscountPrice(ShoppingItem item) {
275 return item.getPrice() * item.getDiscount();
276 }
277
278 public static double calculateDiscountPrice(ShoppingItem item, int count)
279 throws PortalException, SystemException {
280
281 ShoppingItemPrice itemPrice = _getItemPrice(item, count);
282
283 return itemPrice.getPrice() * itemPrice.getDiscount() * count;
284 }
285
286 public static double calculateDiscountPrice(ShoppingItemPrice itemPrice) {
287 return itemPrice.getPrice() * itemPrice.getDiscount();
288 }
289
290 public static double calculateDiscountSubtotal(
291 Map<ShoppingCartItem, Integer> items)
292 throws PortalException, SystemException {
293
294 double subtotal = 0.0;
295
296 Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
297 items.entrySet().iterator();
298
299 while (itr.hasNext()) {
300 Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
301
302 ShoppingCartItem cartItem = entry.getKey();
303 Integer count = entry.getValue();
304
305 ShoppingItem item = cartItem.getItem();
306
307 subtotal += calculateDiscountPrice(item, count.intValue());
308 }
309
310 return subtotal;
311 }
312
313 public static double calculateInsurance(
314 Map<ShoppingCartItem, Integer> items)
315 throws PortalException, SystemException {
316
317 double insurance = 0.0;
318 double subtotal = 0.0;
319
320 ShoppingPreferences preferences = null;
321
322 Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
323 items.entrySet().iterator();
324
325 while (itr.hasNext()) {
326 Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
327
328 ShoppingCartItem cartItem = entry.getKey();
329 Integer count = entry.getValue();
330
331 ShoppingItem item = cartItem.getItem();
332
333 if (preferences == null) {
334 ShoppingCategory category = item.getCategory();
335
336 preferences = ShoppingPreferences.getInstance(
337 category.getCompanyId(), category.getGroupId());
338 }
339
340 ShoppingItemPrice itemPrice = _getItemPrice(item, count.intValue());
341
342 subtotal += calculateActualPrice(itemPrice) * count.intValue();
343 }
344
345 if ((preferences != null) && (subtotal > 0)) {
346 double insuranceRate = 0.0;
347
348 double[] range = ShoppingPreferences.INSURANCE_RANGE;
349
350 for (int i = 0; i < range.length - 1; i++) {
351 if ((subtotal > range[i]) && (subtotal <= range[i + 1])) {
352 int rangeId = i / 2;
353 if (MathUtil.isOdd(i)) {
354 rangeId = (i + 1) / 2;
355 }
356
357 insuranceRate = GetterUtil.getDouble(
358 preferences.getInsurance()[rangeId]);
359 }
360 }
361
362 String formula = preferences.getInsuranceFormula();
363
364 if (formula.equals("flat")) {
365 insurance += insuranceRate;
366 }
367 else if (formula.equals("percentage")) {
368 insurance += subtotal * insuranceRate;
369 }
370 }
371
372 return insurance;
373 }
374
375 public static double calculatePrice(ShoppingItem item, int count)
376 throws PortalException, SystemException {
377
378 ShoppingItemPrice itemPrice = _getItemPrice(item, count);
379
380 return itemPrice.getPrice() * count;
381 }
382
383 public static double calculateShipping(Map<ShoppingCartItem, Integer> items)
384 throws PortalException, SystemException {
385
386 double shipping = 0.0;
387 double subtotal = 0.0;
388
389 ShoppingPreferences preferences = null;
390
391 Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
392 items.entrySet().iterator();
393
394 while (itr.hasNext()) {
395 Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
396
397 ShoppingCartItem cartItem = entry.getKey();
398 Integer count = entry.getValue();
399
400 ShoppingItem item = cartItem.getItem();
401
402 if (preferences == null) {
403 ShoppingCategory category = item.getCategory();
404
405 preferences = ShoppingPreferences.getInstance(
406 category.getCompanyId(), category.getGroupId());
407 }
408
409 if (item.isRequiresShipping()) {
410 ShoppingItemPrice itemPrice = _getItemPrice(
411 item, count.intValue());
412
413 if (itemPrice.isUseShippingFormula()) {
414 subtotal +=
415 calculateActualPrice(itemPrice) * count.intValue();
416 }
417 else {
418 shipping += itemPrice.getShipping() * count.intValue();
419 }
420 }
421 }
422
423 if ((preferences != null) && (subtotal > 0)) {
424 double shippingRate = 0.0;
425
426 double[] range = ShoppingPreferences.SHIPPING_RANGE;
427
428 for (int i = 0; i < range.length - 1; i++) {
429 if ((subtotal > range[i]) && (subtotal <= range[i + 1])) {
430 int rangeId = i / 2;
431 if (MathUtil.isOdd(i)) {
432 rangeId = (i + 1) / 2;
433 }
434
435 shippingRate = GetterUtil.getDouble(
436 preferences.getShipping()[rangeId]);
437 }
438 }
439
440 String formula = preferences.getShippingFormula();
441
442 if (formula.equals("flat")) {
443 shipping += shippingRate;
444 }
445 else if (formula.equals("percentage")) {
446 shipping += subtotal * shippingRate;
447 }
448 }
449
450 return shipping;
451 }
452
453 public static double calculateSubtotal(Map<ShoppingCartItem, Integer> items)
454 throws PortalException, SystemException {
455
456 double subtotal = 0.0;
457
458 Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
459 items.entrySet().iterator();
460
461 while (itr.hasNext()) {
462 Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
463
464 ShoppingCartItem cartItem = entry.getKey();
465 Integer count = entry.getValue();
466
467 ShoppingItem item = cartItem.getItem();
468
469 subtotal += calculatePrice(item, count.intValue());
470 }
471
472 return subtotal;
473 }
474
475 public static double calculateTax(
476 Map<ShoppingCartItem, Integer> items, String stateId)
477 throws PortalException, SystemException {
478
479 double tax = 0.0;
480
481 ShoppingPreferences preferences = null;
482
483 Iterator<Map.Entry<ShoppingCartItem, Integer>> itr =
484 items.entrySet().iterator();
485
486 while (itr.hasNext()) {
487 Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
488
489 ShoppingCartItem cartItem = entry.getKey();
490
491 ShoppingItem item = cartItem.getItem();
492
493 if (preferences == null) {
494 ShoppingCategory category = item.getCategory();
495
496 preferences = ShoppingPreferences.getInstance(
497 category.getCompanyId(), category.getGroupId());
498
499 break;
500 }
501 }
502
503 if ((preferences != null) &&
504 preferences.getTaxState().equals(stateId)) {
505
506 double subtotal = 0.0;
507
508 itr = items.entrySet().iterator();
509
510 while (itr.hasNext()) {
511 Map.Entry<ShoppingCartItem, Integer> entry = itr.next();
512
513 ShoppingCartItem cartItem = entry.getKey();
514 Integer count = entry.getValue();
515
516 ShoppingItem item = cartItem.getItem();
517
518 if (item.isTaxable()) {
519 subtotal += calculatePrice(item, count.intValue());
520 }
521 }
522
523 tax = preferences.getTaxRate() * subtotal;
524 }
525
526 return tax;
527 }
528
529 public static double calculateTotal(
530 Map<ShoppingCartItem, Integer> items, String stateId,
531 ShoppingCoupon coupon, int altShipping, boolean insure)
532 throws PortalException, SystemException {
533
534 double actualSubtotal = calculateActualSubtotal(items);
535 double tax = calculateTax(items, stateId);
536 double shipping = calculateAlternativeShipping(items, altShipping);
537
538 double insurance = 0.0;
539 if (insure) {
540 insurance = calculateInsurance(items);
541 }
542
543 double couponDiscount = calculateCouponDiscount(items, stateId, coupon);
544
545 double total =
546 actualSubtotal + tax + shipping + insurance - couponDiscount;
547
548 if (total < 0) {
549 total = 0.0;
550 }
551
552 return total;
553 }
554
555 public static double calculateTotal(ShoppingOrder order)
556 throws SystemException {
557
558 List<ShoppingOrderItem> orderItems =
559 ShoppingOrderItemLocalServiceUtil.getOrderItems(order.getOrderId());
560
561 double total =
562 calculateActualSubtotal(orderItems) + order.getTax() +
563 order.getShipping() + order.getInsurance() -
564 order.getCouponDiscount();
565
566 if (total < 0) {
567 total = 0.0;
568 }
569
570 return total;
571 }
572
573 public static String getBreadcrumbs(
574 long categoryId, PageContext pageContext,
575 RenderRequest renderRequest, RenderResponse renderResponse)
576 throws Exception {
577
578 ShoppingCategory category = null;
579
580 try {
581 category = ShoppingCategoryLocalServiceUtil.getCategory(categoryId);
582 }
583 catch (Exception e) {
584 }
585
586 return getBreadcrumbs(
587 category, pageContext, renderRequest, renderResponse);
588 }
589
590 public static String getBreadcrumbs(
591 ShoppingCategory category, PageContext pageContext,
592 RenderRequest renderRequest, RenderResponse renderResponse)
593 throws Exception {
594
595 PortletURL categoriesURL = renderResponse.createRenderURL();
596
597 WindowState windowState = renderRequest.getWindowState();
598
599 if (windowState.equals(LiferayWindowState.POP_UP)) {
600 categoriesURL.setWindowState(LiferayWindowState.POP_UP);
601
602 categoriesURL.setParameter(
603 "struts_action", "/shopping/select_category");
604 }
605 else {
606
607
608 categoriesURL.setParameter("struts_action", "/shopping/view");
609 categoriesURL.setParameter("tabs1", "categories");
610 }
611
612 String categoriesLink =
613 "<a href=\"" + categoriesURL.toString() + "\">" +
614 LanguageUtil.get(pageContext, "categories") + "</a>";
615
616 if (category == null) {
617 return "<span class=\"first last\">" + categoriesLink + "</span>";
618 }
619
620 String breadcrumbs = StringPool.BLANK;
621
622 if (category != null) {
623 for (int i = 0;; i++) {
624 category = category.toEscapedModel();
625
626 PortletURL portletURL = renderResponse.createRenderURL();
627
628 if (windowState.equals(LiferayWindowState.POP_UP)) {
629 portletURL.setWindowState(LiferayWindowState.POP_UP);
630
631 portletURL.setParameter(
632 "struts_action", "/shopping/select_category");
633 portletURL.setParameter(
634 "categoryId", String.valueOf(category.getCategoryId()));
635 }
636 else {
637
638
639 portletURL.setParameter("struts_action", "/shopping/view");
640 portletURL.setParameter("tabs1", "categories");
641 portletURL.setParameter(
642 "categoryId", String.valueOf(category.getCategoryId()));
643 }
644
645 String categoryLink =
646 "<a href=\"" + portletURL.toString() + "\">" +
647 category.getName() + "</a>";
648
649 if (i == 0) {
650 breadcrumbs =
651 "<span class=\"last\">" + categoryLink + "</span>";
652 }
653 else {
654 breadcrumbs = categoryLink + " » " + breadcrumbs;
655 }
656
657 if (category.isRoot()) {
658 break;
659 }
660
661 category = ShoppingCategoryLocalServiceUtil.getCategory(
662 category.getParentCategoryId());
663 }
664 }
665
666 breadcrumbs =
667 "<span class=\"first\">" + categoriesLink + " » </span>" +
668 breadcrumbs;
669
670 return breadcrumbs;
671 }
672
673 public static ShoppingCart getCart(PortletRequest portletRequest)
674 throws PortalException, SystemException {
675
676 PortletSession portletSession = portletRequest.getPortletSession();
677
678 ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
679 WebKeys.THEME_DISPLAY);
680
681 String sessionCartId =
682 ShoppingCart.class.getName() + themeDisplay.getScopeGroupId();
683
684 if (themeDisplay.isSignedIn()) {
685 ShoppingCart cart = (ShoppingCart)portletSession.getAttribute(
686 sessionCartId);
687
688 if (cart != null) {
689 portletSession.removeAttribute(sessionCartId);
690 }
691
692 if ((cart != null) && (cart.getItemsSize() > 0)) {
693 cart = ShoppingCartLocalServiceUtil.updateCart(
694 themeDisplay.getUserId(), themeDisplay.getScopeGroupId(),
695 cart.getItemIds(), cart.getCouponCodes(),
696 cart.getAltShipping(), cart.isInsure());
697 }
698 else {
699 try {
700 cart = ShoppingCartLocalServiceUtil.getCart(
701 themeDisplay.getUserId(),
702 themeDisplay.getScopeGroupId());
703 }
704 catch (NoSuchCartException nsce) {
705 cart = getCart(themeDisplay);
706
707 cart = ShoppingCartLocalServiceUtil.updateCart(
708 themeDisplay.getUserId(),
709 themeDisplay.getScopeGroupId(), cart.getItemIds(),
710 cart.getCouponCodes(), cart.getAltShipping(),
711 cart.isInsure());
712 }
713 }
714
715 return cart;
716 }
717 else {
718 ShoppingCart cart = (ShoppingCart)portletSession.getAttribute(
719 sessionCartId);
720
721 if (cart == null) {
722 cart = getCart(themeDisplay);
723
724 portletSession.setAttribute(sessionCartId, cart);
725 }
726
727 return cart;
728 }
729 }
730
731 public static ShoppingCart getCart(ThemeDisplay themeDisplay) {
732 ShoppingCart cart = new ShoppingCartImpl();
733
734 cart.setGroupId(themeDisplay.getScopeGroupId());
735 cart.setCompanyId(themeDisplay.getCompanyId());
736 cart.setUserId(themeDisplay.getUserId());
737 cart.setItemIds(StringPool.BLANK);
738 cart.setCouponCodes(StringPool.BLANK);
739 cart.setAltShipping(0);
740 cart.setInsure(false);
741
742 return cart;
743 }
744
745 public static int getFieldsQuantitiesPos(
746 ShoppingItem item, ShoppingItemField[] itemFields,
747 String[] fieldsArray) {
748
749 Set<String> fieldsValues = new HashSet<String>();
750
751 for (String fields : fieldsArray) {
752 int pos = fields.indexOf("=");
753
754 String fieldValue = fields.substring(
755 pos + 1, fields.length()).trim();
756
757 fieldsValues.add(fieldValue);
758 }
759
760 List<String> names = new ArrayList<String>();
761 List<String[]> values = new ArrayList<String[]>();
762
763 for (int i = 0; i < itemFields.length; i++) {
764 names.add(itemFields[i].getName());
765 values.add(StringUtil.split(itemFields[i].getValues()));
766 }
767
768 int numOfRows = 1;
769
770 for (String[] vArray : values) {
771 numOfRows = numOfRows * vArray.length;
772 }
773
774 int rowPos = 0;
775
776 for (int i = 0; i < numOfRows; i++) {
777 boolean match = true;
778
779 for (int j = 0; j < names.size(); j++) {
780 int numOfRepeats = 1;
781
782 for (int k = j + 1; k < values.size(); k++) {
783 String[] vArray = values.get(k);
784
785 numOfRepeats = numOfRepeats * vArray.length;
786 }
787
788 String[] vArray = values.get(j);
789
790 int arrayPos;
791 for (arrayPos = i / numOfRepeats;
792 arrayPos >= vArray.length;
793 arrayPos = arrayPos - vArray.length) {
794 }
795
796 if (!fieldsValues.contains(vArray[arrayPos].trim())) {
797 match = false;
798
799 break;
800 }
801 }
802
803 if (match) {
804 rowPos = i;
805
806 break;
807 }
808 }
809
810 return rowPos;
811 }
812
813 public static String getItemFields(String itemId) {
814 int pos = itemId.indexOf(CharPool.PIPE);
815
816 if (pos == -1) {
817 return StringPool.BLANK;
818 }
819 else {
820 return itemId.substring(pos + 1);
821 }
822 }
823
824 public static long getItemId(String itemId) {
825 int pos = itemId.indexOf(CharPool.PIPE);
826
827 if (pos != -1) {
828 itemId = itemId.substring(0, pos);
829 }
830
831 return GetterUtil.getLong(itemId);
832 }
833
834 public static OrderByComparator getItemOrderByComparator(
835 String orderByCol, String orderByType) {
836
837 boolean orderByAsc = false;
838
839 if (orderByType.equals("asc")) {
840 orderByAsc = true;
841 }
842
843 OrderByComparator orderByComparator = null;
844
845 if (orderByCol.equals("min-qty")) {
846 orderByComparator = new ItemMinQuantityComparator(orderByAsc);
847 }
848 else if (orderByCol.equals("name")) {
849 orderByComparator = new ItemNameComparator(orderByAsc);
850 }
851 else if (orderByCol.equals("price")) {
852 orderByComparator = new ItemPriceComparator(orderByAsc);
853 }
854 else if (orderByCol.equals("sku")) {
855 orderByComparator = new ItemSKUComparator(orderByAsc);
856 }
857 else if (orderByCol.equals("order-date")) {
858 orderByComparator = new OrderDateComparator(orderByAsc);
859 }
860
861 return orderByComparator;
862 }
863
864 public static int getMinQuantity(ShoppingItem item)
865 throws PortalException, SystemException {
866
867 int minQuantity = item.getMinQuantity();
868
869 List<ShoppingItemPrice> itemPrices = item.getItemPrices();
870
871 for (ShoppingItemPrice itemPrice : itemPrices) {
872 if (minQuantity > itemPrice.getMinQuantity()) {
873 minQuantity = itemPrice.getMinQuantity();
874 }
875 }
876
877 return minQuantity;
878 }
879
880 public static String getPayPalNotifyURL(ThemeDisplay themeDisplay) {
881 return themeDisplay.getPortalURL() + themeDisplay.getPathMain() +
882 "/shopping/notify";
883 }
884
885 public static String getPayPalRedirectURL(
886 ShoppingPreferences preferences, ShoppingOrder order, double total,
887 String returnURL, String notifyURL) {
888
889 String payPalEmailAddress = HttpUtil.encodeURL(
890 preferences.getPayPalEmailAddress());
891
892 NumberFormat doubleFormat = NumberFormat.getNumberInstance(
893 Locale.ENGLISH);
894
895 doubleFormat.setMaximumFractionDigits(2);
896 doubleFormat.setMinimumFractionDigits(2);
897
898 String amount = doubleFormat.format(total);
899
900 returnURL = HttpUtil.encodeURL(returnURL);
901 notifyURL = HttpUtil.encodeURL(notifyURL);
902
903 String firstName = HttpUtil.encodeURL(order.getBillingFirstName());
904 String lastName = HttpUtil.encodeURL(order.getBillingLastName());
905 String address1 = HttpUtil.encodeURL(order.getBillingStreet());
906 String city = HttpUtil.encodeURL(order.getBillingCity());
907 String state = HttpUtil.encodeURL(order.getBillingState());
908 String zip = HttpUtil.encodeURL(order.getBillingZip());
909
910 String currencyCode = preferences.getCurrencyId();
911
912 StringBundler sb = new StringBundler(45);
913
914 sb.append("https:
915 sb.append("cmd=_xclick&");
916 sb.append("business=").append(payPalEmailAddress).append("&");
917 sb.append("item_name=").append(order.getNumber()).append("&");
918 sb.append("item_number=").append(order.getNumber()).append("&");
919 sb.append("invoice=").append(order.getNumber()).append("&");
920 sb.append("amount=").append(amount).append("&");
921 sb.append("return=").append(returnURL).append("&");
922 sb.append("notify_url=").append(notifyURL).append("&");
923 sb.append("first_name=").append(firstName).append("&");
924 sb.append("last_name=").append(lastName).append("&");
925 sb.append("address1=").append(address1).append("&");
926 sb.append("city=").append(city).append("&");
927 sb.append("state=").append(state).append("&");
928 sb.append("zip=").append(zip).append("&");
929 sb.append("no_note=1&");
930 sb.append("currency_code=").append(currencyCode).append("");
931
932 return sb.toString();
933 }
934
935 public static String getPayPalReturnURL(
936 PortletURL portletURL, ShoppingOrder order) {
937
938 portletURL.setParameter("struts_action", "/shopping/checkout");
939 portletURL.setParameter(Constants.CMD, Constants.VIEW);
940 portletURL.setParameter("orderId", String.valueOf(order.getOrderId()));
941
942 return portletURL.toString();
943 }
944
945 public static String getPpPaymentStatus(
946 ShoppingOrder order, PageContext pageContext) {
947
948 String ppPaymentStatus = order.getPpPaymentStatus();
949
950 if (ppPaymentStatus.equals(ShoppingOrderConstants.STATUS_CHECKOUT)) {
951 ppPaymentStatus = "checkout";
952 }
953 else {
954 ppPaymentStatus = ppPaymentStatus.toLowerCase();
955 }
956
957 return LanguageUtil.get(pageContext, ppPaymentStatus);
958 }
959
960 public static String getPpPaymentStatus(String ppPaymentStatus) {
961 if ((ppPaymentStatus == null) || (ppPaymentStatus.length() < 2) ||
962 ppPaymentStatus.equals("checkout")) {
963
964 return ShoppingOrderConstants.STATUS_CHECKOUT;
965 }
966 else {
967 return Character.toUpperCase(ppPaymentStatus.charAt(0)) +
968 ppPaymentStatus.substring(1);
969 }
970 }
971
972 public static boolean isInStock(ShoppingItem item) {
973 if (!item.isFields()) {
974 if (item.getStockQuantity() > 0) {
975 return true;
976 }
977 else {
978 return false;
979 }
980 }
981 else {
982 String[] fieldsQuantities = item.getFieldsQuantitiesArray();
983
984 for (int i = 0; i < fieldsQuantities.length; i++) {
985 if (GetterUtil.getInteger(fieldsQuantities[i]) > 0) {
986 return true;
987 }
988 }
989
990 return false;
991 }
992 }
993
994 public static boolean isInStock(
995 ShoppingItem item, ShoppingItemField[] itemFields, String[] fieldsArray,
996 Integer orderedQuantity) {
997
998 if (!item.isFields()) {
999 int stockQuantity = item.getStockQuantity();
1000
1001 if ((stockQuantity > 0) &&
1002 (stockQuantity >= orderedQuantity.intValue())) {
1003
1004 return true;
1005 }
1006 else {
1007 return false;
1008 }
1009 }
1010 else {
1011 String[] fieldsQuantities = item.getFieldsQuantitiesArray();
1012
1013 int stockQuantity = 0;
1014
1015 if (fieldsQuantities.length > 0) {
1016 int rowPos = getFieldsQuantitiesPos(
1017 item, itemFields, fieldsArray);
1018
1019 stockQuantity = GetterUtil.getInteger(fieldsQuantities[rowPos]);
1020 }
1021
1022 try {
1023 if ((stockQuantity > 0) &&
1024 (stockQuantity >= orderedQuantity.intValue())) {
1025
1026 return true;
1027 }
1028 }
1029 catch (Exception e) {
1030 }
1031
1032 return false;
1033 }
1034 }
1035
1036 public static boolean meetsMinOrder(
1037 ShoppingPreferences preferences,
1038 Map<ShoppingCartItem, Integer> items)
1039 throws PortalException, SystemException {
1040
1041 if ((preferences.getMinOrder() > 0) &&
1042 (calculateSubtotal(items) < preferences.getMinOrder())) {
1043
1044 return false;
1045 }
1046 else {
1047 return true;
1048 }
1049 }
1050
1051 private static ShoppingItemPrice _getItemPrice(ShoppingItem item, int count)
1052 throws PortalException, SystemException {
1053
1054 ShoppingItemPrice itemPrice = null;
1055
1056 List<ShoppingItemPrice> itemPrices = item.getItemPrices();
1057
1058 for (ShoppingItemPrice temp : itemPrices) {
1059 int minQty = temp.getMinQuantity();
1060 int maxQty = temp.getMaxQuantity();
1061
1062 if (temp.getStatus() !=
1063 ShoppingItemPriceConstants.STATUS_INACTIVE) {
1064
1065 if ((count >= minQty) && ((count <= maxQty) || (maxQty == 0))) {
1066 return temp;
1067 }
1068
1069 if ((count > maxQty) &&
1070 ((itemPrice == null) ||
1071 (itemPrice.getMaxQuantity() < maxQty))) {
1072
1073 itemPrice = temp;
1074 }
1075 }
1076 }
1077
1078 if (itemPrice == null) {
1079 return ShoppingItemPriceUtil.create(0);
1080 }
1081
1082 return itemPrice;
1083 }
1084
1085 }