KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > order > shoppingcart > product > ProductDisplayWorker


1 /*
2  * $Id: ProductDisplayWorker.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.order.shoppingcart.product;
25
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Collections JavaDoc;
29 import java.util.Comparator JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34
35 import javax.servlet.ServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37
38 import org.ofbiz.base.util.Debug;
39 import org.ofbiz.base.util.UtilMisc;
40 import org.ofbiz.entity.GenericDelegator;
41 import org.ofbiz.entity.GenericEntity;
42 import org.ofbiz.entity.GenericEntityException;
43 import org.ofbiz.entity.GenericValue;
44 import org.ofbiz.entity.util.EntityUtil;
45 import org.ofbiz.order.shoppingcart.ShoppingCart;
46 import org.ofbiz.order.shoppingcart.ShoppingCartItem;
47 import org.ofbiz.product.catalog.CatalogWorker;
48 import org.ofbiz.product.category.CategoryWorker;
49
50 /**
51  * @author ajzeneski
52  */

53 public class ProductDisplayWorker {
54     
55     public static final String JavaDoc module = ProductDisplayWorker.class.getName();
56
57     /* ========================================================================================*/
58     
59     /* ============================= Special Data Retreival Methods ===========================*/
60         
61     public static List JavaDoc getRandomCartProductAssoc(ServletRequest JavaDoc request, boolean checkViewAllow) {
62         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
63         HttpServletRequest JavaDoc httpRequest = (HttpServletRequest JavaDoc) request;
64         ShoppingCart cart = (ShoppingCart) httpRequest.getSession().getAttribute("shoppingCart");
65
66         if (cart == null || cart.size() <= 0) return null;
67
68         ArrayList JavaDoc cartAssocs = null;
69         try {
70             Map JavaDoc products = new HashMap JavaDoc();
71
72             Iterator JavaDoc cartiter = cart.iterator();
73
74             while (cartiter != null && cartiter.hasNext()) {
75                 ShoppingCartItem item = (ShoppingCartItem) cartiter.next();
76                 // Collection upgradeProducts = delegator.findByAndCache("ProductAssoc", UtilMisc.toMap("productId", item.getProductId(), "productAssocTypeId", "PRODUCT_UPGRADE"), null);
77
List JavaDoc complementProducts = delegator.findByAndCache("ProductAssoc", UtilMisc.toMap("productId", item.getProductId(), "productAssocTypeId", "PRODUCT_COMPLEMENT"), null);
78                 // since ProductAssoc records have a fromDate and thruDate, we can filter by now so that only assocs in the date range are included
79
complementProducts = EntityUtil.filterByDate(complementProducts, true);
80                 
81                 List JavaDoc productsCategories = delegator.findByAndCache("ProductCategoryMember", UtilMisc.toMap("productId", item.getProductId()), null);
82                 productsCategories = EntityUtil.filterByDate(productsCategories, true);
83                 if (productsCategories != null) {
84                     Iterator JavaDoc productsCategoriesIter = productsCategories.iterator();
85                     while (productsCategoriesIter.hasNext()) {
86                         GenericValue productsCategoryMember = (GenericValue) productsCategoriesIter.next();
87                         GenericValue productsCategory = productsCategoryMember.getRelatedOneCache("ProductCategory");
88                         if ("CROSS_SELL_CATEGORY".equals(productsCategory.getString("productCategoryTypeId"))) {
89                             List JavaDoc curPcms = productsCategory.getRelatedCache("ProductCategoryMember");
90                             if (curPcms != null) {
91                                 Iterator JavaDoc curPcmsIter = curPcms.iterator();
92                                 while (curPcmsIter.hasNext()) {
93                                     GenericValue curPcm = (GenericValue) curPcmsIter.next();
94                                     if (!products.containsKey(curPcm.getString("productId"))) {
95                                         GenericValue product = curPcm.getRelatedOneCache("Product");
96                                         products.put(product.getString("productId"), product);
97                                     }
98                                 }
99                             }
100                         }
101                     }
102                 }
103
104                 if (complementProducts != null && complementProducts.size() > 0) {
105                     Iterator JavaDoc complIter = complementProducts.iterator();
106                     while (complIter.hasNext()) {
107                         GenericValue productAssoc = (GenericValue) complIter.next();
108                         if (!products.containsKey(productAssoc.getString("productIdTo"))) {
109                             GenericValue product = productAssoc.getRelatedOneCache("AssocProduct");
110                             products.put(product.getString("productId"), product);
111                         }
112                     }
113                 }
114             }
115
116             // remove all products that are already in the cart
117
cartiter = cart.iterator();
118             while (cartiter != null && cartiter.hasNext()) {
119                 ShoppingCartItem item = (ShoppingCartItem) cartiter.next();
120                 products.remove(item.getProductId());
121             }
122
123             // if desired check view allow category
124
if (checkViewAllow) {
125                 String JavaDoc currentCatalogId = CatalogWorker.getCurrentCatalogId(request);
126                 String JavaDoc viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, currentCatalogId);
127                 if (viewProductCategoryId != null) {
128                     List JavaDoc tempList = new ArrayList JavaDoc(products.values());
129                     tempList = CategoryWorker.filterProductsInCategory(delegator, tempList, viewProductCategoryId, "productId");
130                     cartAssocs = new ArrayList JavaDoc(tempList);
131                 }
132             }
133             
134             if (cartAssocs == null) {
135                 cartAssocs = new ArrayList JavaDoc(products.values());
136             }
137
138             // randomly remove products while there are more than 3
139
while (cartAssocs.size() > 3) {
140                 int toRemove = (int) (Math.random() * (double) (cartAssocs.size()));
141                 cartAssocs.remove(toRemove);
142             }
143         } catch (GenericEntityException e) {
144             Debug.logWarning(e, module);
145         }
146         
147         if (cartAssocs != null && cartAssocs.size() > 0) {
148             return cartAssocs;
149         } else {
150             return null;
151         }
152     }
153                 
154     public static Map JavaDoc getQuickReorderProducts(ServletRequest JavaDoc request) {
155         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
156         HttpServletRequest JavaDoc httpRequest = (HttpServletRequest JavaDoc) request;
157         GenericValue userLogin = (GenericValue) httpRequest.getSession().getAttribute("userLogin");
158         Map JavaDoc results = new HashMap JavaDoc();
159
160         if (userLogin == null) userLogin = (GenericValue) httpRequest.getSession().getAttribute("autoUserLogin");
161         if (userLogin == null) return results;
162
163         try {
164             Map JavaDoc products = (Map JavaDoc) httpRequest.getSession().getAttribute("_QUICK_REORDER_PRODUCTS_");
165             Map JavaDoc productQuantities = (Map JavaDoc) httpRequest.getSession().getAttribute("_QUICK_REORDER_PRODUCT_QUANTITIES_");
166             Map JavaDoc productOccurances = (Map JavaDoc) httpRequest.getSession().getAttribute("_QUICK_REORDER_PRODUCT_OCCURANCES_");
167
168             if (products == null || productQuantities == null || productOccurances == null) {
169                 products = new HashMap JavaDoc();
170                 productQuantities = new HashMap JavaDoc();
171                 // keep track of how many times a product occurs in order to find averages and rank by purchase amount
172
productOccurances = new HashMap JavaDoc();
173
174                 // get all order role entities for user by customer role type
175
// final String[] USER_ORDER_ROLE_TYPES = {"END_USER_CUSTOMER", "SHIP_TO_CUSTOMER", "BILL_TO_CUSTOMER", "PLACING_CUSTOMER"};
176
final String JavaDoc[] USER_ORDER_ROLE_TYPES = {"PLACING_CUSTOMER"};
177
178                 for (int i = 0; i < USER_ORDER_ROLE_TYPES.length; i++) {
179                     Collection JavaDoc orderRoles = delegator.findByAnd("OrderRole", UtilMisc.toMap("partyId", userLogin.get("partyId"), "roleTypeId", USER_ORDER_ROLE_TYPES[i]), null);
180                     Iterator JavaDoc ordersIter = UtilMisc.toIterator(orderRoles);
181
182                     while (ordersIter != null && ordersIter.hasNext()) {
183                         GenericValue orderRole = (GenericValue) ordersIter.next();
184                         // for each order role get all order items
185
Collection JavaDoc orderItems = orderRole.getRelated("OrderItem");
186                         Iterator JavaDoc orderItemsIter = UtilMisc.toIterator(orderItems);
187
188                         while (orderItemsIter != null && orderItemsIter.hasNext()) {
189                             GenericValue orderItem = (GenericValue) orderItemsIter.next();
190                             // for each order item get the associated product
191
GenericValue product = orderItem.getRelatedOneCache("Product");
192
193                             products.put(product.get("productId"), product);
194
195                             Integer JavaDoc curQuant = (Integer JavaDoc) productQuantities.get(product.get("productId"));
196
197                             if (curQuant == null) curQuant = new Integer JavaDoc(0);
198                             Double JavaDoc orderQuant = orderItem.getDouble("quantity");
199
200                             if (orderQuant == null) orderQuant = new Double JavaDoc(0.0);
201                             productQuantities.put(product.get("productId"), new Integer JavaDoc(curQuant.intValue() + orderQuant.intValue()));
202
203                             Integer JavaDoc curOcc = (Integer JavaDoc) productOccurances.get(product.get("productId"));
204
205                             if (curOcc == null) curOcc = new Integer JavaDoc(0);
206                             productOccurances.put(product.get("productId"), new Integer JavaDoc(curOcc.intValue() + 1));
207                         }
208                     }
209                 }
210
211                 // go through each product quantity and divide it by the occurances to get the average
212
Iterator JavaDoc quantEntries = productQuantities.entrySet().iterator();
213
214                 while (quantEntries.hasNext()) {
215                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) quantEntries.next();
216                     Object JavaDoc prodId = entry.getKey();
217                     Integer JavaDoc quantity = (Integer JavaDoc) entry.getValue();
218                     Integer JavaDoc occs = (Integer JavaDoc) productOccurances.get(prodId);
219                     int nqint = quantity.intValue() / occs.intValue();
220
221                     if (nqint < 1) nqint = 1;
222                     productQuantities.put(prodId, new Integer JavaDoc(nqint));
223                 }
224
225                 httpRequest.getSession().setAttribute("_QUICK_REORDER_PRODUCTS_", new HashMap JavaDoc(products));
226                 httpRequest.getSession().setAttribute("_QUICK_REORDER_PRODUCT_QUANTITIES_", new HashMap JavaDoc(productQuantities));
227                 httpRequest.getSession().setAttribute("_QUICK_REORDER_PRODUCT_OCCURANCES_", new HashMap JavaDoc(productOccurances));
228             } else {
229                 // make a copy since we are going to change them
230
products = new HashMap JavaDoc(products);
231                 productQuantities = new HashMap JavaDoc(productQuantities);
232                 productOccurances = new HashMap JavaDoc(productOccurances);
233             }
234
235             // remove all products that are already in the cart
236
ShoppingCart cart = (ShoppingCart) httpRequest.getSession().getAttribute("shoppingCart");
237             if (cart != null && cart.size() > 0) {
238                 Iterator JavaDoc cartiter = cart.iterator();
239                 while (cartiter.hasNext()) {
240                     ShoppingCartItem item = (ShoppingCartItem) cartiter.next();
241                     String JavaDoc productId = item.getProductId();
242                     products.remove(productId);
243                     productQuantities.remove(productId);
244                     productOccurances.remove(productId);
245                 }
246             }
247
248             // if desired check view allow category
249
//if (checkViewAllow) {
250
List JavaDoc prodKeyList = new ArrayList JavaDoc(products.keySet());
251                 //Set prodKeySet = products.keySet();
252
String JavaDoc currentCatalogId = CatalogWorker.getCurrentCatalogId(request);
253                 String JavaDoc viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, currentCatalogId);
254                 if (viewProductCategoryId != null) {
255                     Iterator JavaDoc valIter = prodKeyList.iterator();
256                     while (valIter.hasNext()) {
257                         String JavaDoc productId = (String JavaDoc) valIter.next();
258                         if (!CategoryWorker.isProductInCategory(delegator, productId, viewProductCategoryId)) {
259                             products.remove(productId);
260                             productQuantities.remove(productId);
261                             productOccurances.remove(productId);
262                         }
263                     }
264                 }
265             //}
266

267             List JavaDoc reorderProds = new ArrayList JavaDoc(products.values());
268
269             /*
270              //randomly remove products while there are more than 5
271              while (reorderProds.size() > 5) {
272              int toRemove = (int)(Math.random()*(double)(reorderProds.size()));
273              reorderProds.remove(toRemove);
274              }
275              */

276
277             // sort descending by new metric...
278
double occurancesModifier = 1.0;
279             double quantityModifier = 1.0;
280             Map JavaDoc newMetric = new HashMap JavaDoc();
281             Iterator JavaDoc occurEntries = productOccurances.entrySet().iterator();
282
283             while (occurEntries.hasNext()) {
284                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) occurEntries.next();
285                 Object JavaDoc prodId = entry.getKey();
286                 Integer JavaDoc quantity = (Integer JavaDoc) entry.getValue();
287                 Integer JavaDoc occs = (Integer JavaDoc) productQuantities.get(prodId);
288                 double nqdbl = quantity.doubleValue() * quantityModifier + occs.doubleValue() * occurancesModifier;
289
290                 newMetric.put(prodId, new Double JavaDoc(nqdbl));
291             }
292             reorderProds = productOrderByMap(reorderProds, newMetric, true);
293
294             // remove extra products - only return 5
295
while (reorderProds.size() > 5) {
296                 reorderProds.remove(reorderProds.size() - 1);
297             }
298
299             results.put("products", reorderProds);
300             results.put("quantities", productQuantities);
301         } catch (GenericEntityException e) {
302             Debug.logWarning(e, module);
303         }
304         
305         return results;
306     }
307     
308     public static List JavaDoc productOrderByMap(Collection JavaDoc values, Map JavaDoc orderByMap, boolean descending) {
309         if (values == null) return null;
310         if (values.size() == 0) return UtilMisc.toList(values);
311
312         List JavaDoc result = new ArrayList JavaDoc(values);
313
314         Collections.sort(result, new ProductByMapComparator(orderByMap, descending));
315         return result;
316     }
317
318     static class ProductByMapComparator implements Comparator JavaDoc {
319         private Map JavaDoc orderByMap;
320         private boolean descending;
321
322         ProductByMapComparator(Map JavaDoc orderByMap, boolean descending) {
323             this.orderByMap = orderByMap;
324             this.descending = descending;
325         }
326
327         public int compare(java.lang.Object JavaDoc prod1, java.lang.Object JavaDoc prod2) {
328             int result = compareAsc((GenericEntity) prod1, (GenericEntity) prod2);
329
330             if (descending) {
331                 result = -result;
332             }
333             return result;
334         }
335
336         private int compareAsc(GenericEntity prod1, GenericEntity prod2) {
337             Object JavaDoc value = orderByMap.get(prod1.get("productId"));
338             Object JavaDoc value2 = orderByMap.get(prod2.get("productId"));
339
340             // null is defined as the smallest possible value
341
if (value == null) return value2 == null ? 0 : -1;
342             return ((Comparable JavaDoc) value).compareTo(value2);
343         }
344
345         public boolean equals(java.lang.Object JavaDoc obj) {
346             if ((obj != null) && (obj instanceof ProductByMapComparator)) {
347                 ProductByMapComparator that = (ProductByMapComparator) obj;
348
349                 return this.orderByMap.equals(that.orderByMap) && this.descending == that.descending;
350             } else {
351                 return false;
352             }
353         }
354     }
355 }
356
Popular Tags