KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > order > shoppinglist > ShoppingListEvents


1 /*
2  * $Id: ShoppingListEvents.java 5847 2005-09-28 05:59:20Z jacopo $
3  *
4  * Copyright (c) 2003-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.shoppinglist;
25
26 import java.sql.Timestamp JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedList JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Locale JavaDoc;
33 import java.util.Map JavaDoc;
34
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37 import javax.servlet.http.HttpSession JavaDoc;
38
39 import org.ofbiz.base.util.Debug;
40 import org.ofbiz.base.util.GeneralException;
41 import org.ofbiz.base.util.UtilDateTime;
42 import org.ofbiz.base.util.UtilHttp;
43 import org.ofbiz.base.util.UtilMisc;
44 import org.ofbiz.base.util.UtilProperties;
45 import org.ofbiz.base.util.UtilValidate;
46 import org.ofbiz.entity.GenericDelegator;
47 import org.ofbiz.entity.GenericEntityException;
48 import org.ofbiz.entity.GenericValue;
49 import org.ofbiz.entity.util.EntityUtil;
50 import org.ofbiz.order.shoppingcart.CartItemModifyException;
51 import org.ofbiz.order.shoppingcart.ItemNotFoundException;
52 import org.ofbiz.order.shoppingcart.ShoppingCart;
53 import org.ofbiz.order.shoppingcart.ShoppingCartEvents;
54 import org.ofbiz.order.shoppingcart.ShoppingCartItem;
55 import org.ofbiz.product.catalog.CatalogWorker;
56 import org.ofbiz.product.store.ProductStoreWorker;
57 import org.ofbiz.service.GenericServiceException;
58 import org.ofbiz.service.LocalDispatcher;
59 import org.ofbiz.service.ModelService;
60 import org.ofbiz.service.ServiceUtil;
61
62 /**
63  * Shopping cart events.
64  *
65  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
66  * @version $Rev: 5847 $
67  * @since 2.2
68  */

69 public class ShoppingListEvents {
70     
71     public static final String JavaDoc module = ShoppingListEvents.class.getName();
72     public static final String JavaDoc resource = "OrderUiLabels";
73     public static final String JavaDoc err_resource = "OrderErrorUiLabel";
74     public static final String JavaDoc resource_error = "OrderErrorUiLabels";
75     public static final String JavaDoc PERSISTANT_LIST_NAME = "auto-save";
76
77     public static String JavaDoc addBulkFromCart(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
78         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
79         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
80         ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
81         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
82         Locale JavaDoc locale = UtilHttp.getLocale(request);
83
84         String JavaDoc shoppingListId = request.getParameter("shoppingListId");
85         String JavaDoc selectedCartItems[] = request.getParameterValues("selectedItem");
86
87         try {
88             shoppingListId = addBulkFromCart(delegator, dispatcher, cart, userLogin, shoppingListId, selectedCartItems, true, true);
89         } catch (IllegalArgumentException JavaDoc e) {
90             request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
91             return "error";
92         }
93
94         request.setAttribute("shoppingListId", shoppingListId);
95         return "success";
96     }
97
98     public static String JavaDoc addBulkFromCart(GenericDelegator delegator, LocalDispatcher dispatcher, ShoppingCart cart, GenericValue userLogin, String JavaDoc shoppingListId, String JavaDoc[] items, boolean allowPromo, boolean append) throws IllegalArgumentException JavaDoc {
99         String JavaDoc errMsg = null;
100
101         if (items == null || items.length == 0) {
102             errMsg = UtilProperties.getMessage(resource, "shoppinglistevents.select_items_to_add_to_list", cart.getLocale());
103             throw new IllegalArgumentException JavaDoc(errMsg);
104         }
105                 
106         if (UtilValidate.isEmpty(shoppingListId)) {
107             // create a new shopping list
108
Map JavaDoc newListResult = null;
109             try {
110                 newListResult = dispatcher.runSync("createShoppingList", UtilMisc.toMap("userLogin", userLogin, "productStoreId", cart.getProductStoreId(), "partyId", cart.getOrderPartyId(), "currencyUom", cart.getCurrency()));
111             } catch (GenericServiceException e) {
112                 Debug.logError(e, "Problems creating new ShoppingList", module);
113                 errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.cannot_create_new_shopping_list", cart.getLocale());
114                 throw new IllegalArgumentException JavaDoc(errMsg);
115             }
116
117             // check for errors
118
if (ServiceUtil.isError(newListResult)) {
119                 throw new IllegalArgumentException JavaDoc(ServiceUtil.getErrorMessage(newListResult));
120             }
121
122             // get the new list id
123
if (newListResult != null) {
124                 shoppingListId = (String JavaDoc) newListResult.get("shoppingListId");
125             }
126             
127             // if no list was created throw an error
128
if (shoppingListId == null || shoppingListId.equals("")) {
129                 errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.shoppingListId_is_required_parameter", cart.getLocale());
130                 throw new IllegalArgumentException JavaDoc(errMsg);
131             }
132         } else if (!append) {
133             try {
134                 clearListInfo(delegator, shoppingListId);
135             } catch (GenericEntityException e) {
136                 Debug.logError(e, module);
137                 throw new IllegalArgumentException JavaDoc("Could not clear current shopping list: " + e.toString());
138             }
139         }
140                 
141         for (int i = 0; i < items.length; i++) {
142             Integer JavaDoc cartIdInt = null;
143             try {
144                 cartIdInt = new Integer JavaDoc(items[i]);
145             } catch (Exception JavaDoc e) {
146                 Debug.logWarning(e, UtilProperties.getMessage(resource_error,"OrderIllegalCharacterInSelectedItemField", cart.getLocale()), module);
147             }
148             if (cartIdInt != null) {
149                 ShoppingCartItem item = cart.findCartItem(cartIdInt.intValue());
150                 if (allowPromo || !item.getIsPromo()) {
151                     Debug.logInfo("Adding cart item to shopping list [" + shoppingListId + "], allowPromo=" + allowPromo + ", item.getIsPromo()=" + item.getIsPromo() + ", item.getProductId()=" + item.getProductId() + ", item.getQuantity()=" + item.getQuantity(), module);
152                     Map JavaDoc serviceResult = null;
153                     try {
154                         Map JavaDoc ctx = UtilMisc.toMap("userLogin", userLogin, "shoppingListId", shoppingListId, "productId", item.getProductId(), "quantity", new Double JavaDoc(item.getQuantity()));
155                         ctx.put("reservStart", item.getReservStart());
156                         ctx.put("reservLength", new Double JavaDoc(item.getReservLength()));
157                         ctx.put("reservPersons", new Double JavaDoc(item.getReservPersons()));
158                         serviceResult = dispatcher.runSync("createShoppingListItem", ctx);
159                     } catch (GenericServiceException e) {
160                         Debug.logError(e, "Problems creating ShoppingList item entity", module);
161                         errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.error_adding_item_to_shopping_list", cart.getLocale());
162                         throw new IllegalArgumentException JavaDoc(errMsg);
163                     }
164
165                     // check for errors
166
if (ServiceUtil.isError(serviceResult)) {
167                         throw new IllegalArgumentException JavaDoc(ServiceUtil.getErrorMessage(serviceResult));
168                     }
169                 }
170             }
171         }
172         
173         // return the shoppinglist id
174
return shoppingListId;
175     }
176     
177     public static String JavaDoc addListToCart(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
178         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
179         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
180         ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
181         Locale JavaDoc locale = UtilHttp.getLocale(request);
182
183         String JavaDoc shoppingListId = request.getParameter("shoppingListId");
184         String JavaDoc includeChild = request.getParameter("includeChild");
185         String JavaDoc prodCatalogId = CatalogWorker.getCurrentCatalogId(request);
186
187         String JavaDoc eventMessage = null;
188         try {
189             addListToCart(delegator, dispatcher, cart, prodCatalogId, shoppingListId, (includeChild != null), true, true);
190         } catch (IllegalArgumentException JavaDoc e) {
191             request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
192             return "error";
193         }
194
195         if (eventMessage != null && eventMessage.length() > 0) {
196             request.setAttribute("_EVENT_MESSAGE_", eventMessage);
197         }
198
199         return "success";
200     }
201
202     public static String JavaDoc addListToCart(GenericDelegator delegator, LocalDispatcher dispatcher, ShoppingCart cart, String JavaDoc prodCatalogId, String JavaDoc shoppingListId, boolean includeChild, boolean setAsListItem, boolean append) throws java.lang.IllegalArgumentException JavaDoc {
203         String JavaDoc errMsg = null;
204
205         // no list; no add
206
if (shoppingListId == null) {
207             errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.choose_shopping_list", cart.getLocale());
208             throw new IllegalArgumentException JavaDoc(errMsg);
209         }
210         
211         // get the shopping list
212
GenericValue shoppingList = null;
213         List JavaDoc shoppingListItems = null;
214         try {
215             shoppingList = delegator.findByPrimaryKey("ShoppingList", UtilMisc.toMap("shoppingListId", shoppingListId));
216             if (shoppingList == null) {
217                 errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.error_getting_shopping_list_and_items", cart.getLocale());
218                 throw new IllegalArgumentException JavaDoc(errMsg);
219             }
220
221             shoppingListItems = shoppingList.getRelated("ShoppingListItem");
222             if (shoppingListItems == null) {
223                 shoppingListItems = new LinkedList JavaDoc();
224             }
225
226             // include all items of child lists if flagged to do so
227
if (includeChild) {
228                 List JavaDoc childShoppingLists = shoppingList.getRelated("ChildShoppingList");
229                 Iterator JavaDoc ci = childShoppingLists.iterator();
230                 while (ci.hasNext()) {
231                     GenericValue v = (GenericValue) ci.next();
232                     List JavaDoc items = v.getRelated("ShoppingListItem");
233                     shoppingListItems.addAll(items);
234                 }
235             }
236
237         } catch (GenericEntityException e) {
238             Debug.logError(e, "Problems getting ShoppingList and ShoppingListItem records", module);
239             errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.error_getting_shopping_list_and_items", cart.getLocale());
240             throw new IllegalArgumentException JavaDoc(errMsg);
241         }
242         
243         // no items; not an error; just mention that nothing was added
244
if (shoppingListItems == null || shoppingListItems.size() == 0) {
245             errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.no_items_added", cart.getLocale());
246             return errMsg;
247         }
248
249         // check if we are to clear the cart first
250
if (!append) {
251             cart.clear();
252         }
253
254         // get the survey info for all the items
255
Map JavaDoc shoppingListSurveyInfo = getItemSurveyInfos(shoppingListItems);
256
257         // add the items
258
StringBuffer JavaDoc eventMessage = new StringBuffer JavaDoc();
259         Iterator JavaDoc i = shoppingListItems.iterator();
260         while (i.hasNext()) {
261             GenericValue shoppingListItem = (GenericValue) i.next();
262             String JavaDoc productId = shoppingListItem.getString("productId");
263             Double JavaDoc quantity = shoppingListItem.getDouble("quantity");
264             Timestamp JavaDoc reservStart = shoppingListItem.getTimestamp("reservStart");
265             Double JavaDoc reservLength = shoppingListItem.getDouble("reservLength");
266             Double JavaDoc reservPersons = shoppingListItem.getDouble("reservPersons");
267             try {
268                 String JavaDoc listId = shoppingListItem.getString("shoppingListId");
269                 String JavaDoc itemId = shoppingListItem.getString("shoppingListItemSeqId");
270
271                 Map JavaDoc attributes = new HashMap JavaDoc();
272                 // list items are noted in the shopping cart
273
if (setAsListItem) {
274                     attributes.put("shoppingListId", listId);
275                     attributes.put("shoppingListItemSeqId", itemId);
276                 }
277
278                 // check if we have existing survey responses to append
279
if (shoppingListSurveyInfo.containsKey(listId + "." + itemId)) {
280                     attributes.put("surveyResponses", shoppingListSurveyInfo.get(listId + "." + itemId));
281                 }
282
283                 // TODO: add code to check for survey response requirement
284

285                 // i cannot get the addOrDecrease function to accept a null reservStart field: i get a null pointer exception a null constant works....
286
if (reservStart == null)
287                     cart.addOrIncreaseItem(productId, quantity.doubleValue(), null,0,0, null, attributes, prodCatalogId, dispatcher);
288                 else
289                     cart.addOrIncreaseItem(productId, quantity.doubleValue(), reservStart, reservLength.doubleValue(), reservPersons.doubleValue(), null, attributes, prodCatalogId, dispatcher);
290                 Map JavaDoc messageMap = UtilMisc.toMap("productId", productId);
291                 errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.added_product_to_cart", messageMap, cart.getLocale());
292                 eventMessage.append(errMsg + "\n");
293             } catch (CartItemModifyException e) {
294                 Debug.logWarning(e, UtilProperties.getMessage(resource_error,"OrderProblemsAddingItemFromListToCart", cart.getLocale()));
295                 Map JavaDoc messageMap = UtilMisc.toMap("productId", productId);
296                 errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.problem_adding_product_to_cart", messageMap, cart.getLocale());
297                 eventMessage.append(errMsg + "\n");
298             } catch (ItemNotFoundException e) {
299                 Debug.logWarning(e, UtilProperties.getMessage(resource_error,"OrderProductNotFound", cart.getLocale()));
300                 Map JavaDoc messageMap = UtilMisc.toMap("productId", productId);
301                 errMsg = UtilProperties.getMessage(resource,"shoppinglistevents.problem_adding_product_to_cart", messageMap, cart.getLocale());
302                 eventMessage.append(errMsg + "\n");
303             }
304         }
305         
306         if (eventMessage.length() > 0) {
307             return eventMessage.toString();
308         }
309         
310         // all done
311
return ""; // no message to return; will simply reply as success
312
}
313
314     public static String JavaDoc replaceShoppingListItem(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
315         String JavaDoc quantityStr = request.getParameter("quantity");
316
317         // just call the updateShoppingListItem service
318
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
319         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
320         Locale JavaDoc locale = UtilHttp.getLocale(request);
321                 
322         Double JavaDoc quantity = null;
323         try {
324             quantity = Double.valueOf(quantityStr);
325         } catch (Exception JavaDoc e) {
326             // do nothing, just won't pass to service if it is null
327
}
328         
329         Map JavaDoc serviceInMap = new HashMap JavaDoc();
330         serviceInMap.put("shoppingListId", request.getParameter("shoppingListId"));
331         serviceInMap.put("shoppingListItemSeqId", request.getParameter("shoppingListItemSeqId"));
332         serviceInMap.put("productId", request.getParameter("add_product_id"));
333         serviceInMap.put("userLogin", userLogin);
334         if (quantity != null) serviceInMap.put("quantity", quantity);
335         Map JavaDoc result = null;
336         try {
337             result = dispatcher.runSync("updateShoppingListItem", serviceInMap);
338         } catch (GenericServiceException e) {
339             String JavaDoc errMsg = UtilProperties.getMessage(ShoppingListEvents.err_resource,"shoppingListEvents.error_calling_update", locale) + ": " + e.toString();
340             request.setAttribute("_ERROR_MESSAGE_", errMsg);
341             String JavaDoc errorMsg = "Error calling the updateShoppingListItem in handleShoppingListItemVariant: " + e.toString();
342             Debug.logError(e, errorMsg, module);
343             return "error";
344         }
345         
346         ServiceUtil.getMessages(request, result, "", "", "", "", "", "", "");
347         if ("error".equals(result.get(ModelService.RESPONSE_MESSAGE))) {
348             return "error";
349         } else {
350             return "success";
351         }
352     }
353     
354     /**
355      * Finds or creates a specialized (auto-save) shopping list used to record shopping bag contents between user visits.
356      */

357     public static String JavaDoc getAutoSaveListId(GenericDelegator delegator, LocalDispatcher dispatcher, String JavaDoc partyId, GenericValue userLogin, String JavaDoc productStoreId) throws GenericEntityException, GenericServiceException {
358         if (partyId == null && userLogin != null) {
359             partyId = userLogin.getString("partyId");
360         }
361
362         String JavaDoc autoSaveListId = null;
363         // TODO: add sorting, just in case there are multiple...
364
Map JavaDoc findMap = UtilMisc.toMap("partyId", partyId, "productStoreId", productStoreId, "shoppingListTypeId", "SLT_SPEC_PURP", "listName", PERSISTANT_LIST_NAME);
365         List JavaDoc existingLists = delegator.findByAnd("ShoppingList", findMap);
366         Debug.logInfo("Finding existing auto-save shopping list with: \nfindMap: " + findMap + "\nlists: " + existingLists, module);
367
368         GenericValue list = null;
369         if (existingLists != null && !existingLists.isEmpty()) {
370             list = EntityUtil.getFirst(existingLists);
371             autoSaveListId = list.getString("shoppingListId");
372         }
373
374         if (list == null && dispatcher != null && userLogin != null) {
375             Map JavaDoc listFields = UtilMisc.toMap("userLogin", userLogin, "productStoreId", productStoreId, "shoppingListTypeId", "SLT_SPEC_PURP", "listName", PERSISTANT_LIST_NAME);
376             Map JavaDoc newListResult = dispatcher.runSync("createShoppingList", listFields);
377
378             if (newListResult != null) {
379                 autoSaveListId = (String JavaDoc) newListResult.get("shoppingListId");
380             }
381         }
382
383         return autoSaveListId;
384     }
385
386     /**
387      * Fills the specialized shopping list with the current shopping cart if one exists (if not leaves it alone)
388      */

389     public static void fillAutoSaveList(ShoppingCart cart, LocalDispatcher dispatcher) throws GeneralException {
390         if (cart != null && dispatcher != null) {
391             GenericValue userLogin = ShoppingListEvents.getCartUserLogin(cart);
392             if (userLogin == null) return; //only save carts when a user is logged in....
393
GenericDelegator delegator = cart.getDelegator();
394             String JavaDoc autoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
395
396             try {
397                 String JavaDoc[] itemsArray = makeCartItemsArray(cart);
398                 if (itemsArray != null && itemsArray.length != 0) {
399                     addBulkFromCart(delegator, dispatcher, cart, userLogin, autoSaveListId, itemsArray, false, false);
400                 }
401             } catch (IllegalArgumentException JavaDoc e) {
402                 throw new GeneralException(e.getMessage(), e);
403             }
404         }
405     }
406
407     /**
408      * Saves the shopping cart to the specialized (auto-save) shopping list
409      */

410     public static String JavaDoc saveCartToAutoSaveList(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
411         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
412         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
413         ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
414         
415         try {
416             fillAutoSaveList(cart, dispatcher);
417         } catch (GeneralException e) {
418             Debug.logError(e, "Error saving the cart to the auto-save list: " + e.toString(), module);
419         }
420         
421         return "success";
422     }
423     
424     /**
425      * Restores the specialized (auto-save) shopping list back into the shopping cart
426      */

427     public static String JavaDoc restoreAutoSaveList(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
428         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
429         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
430         GenericValue productStore = ProductStoreWorker.getProductStore(request);
431
432         if (!ProductStoreWorker.autoSaveCart(productStore)) {
433             // if auto-save is disabled just return here
434
return "success";
435         }
436
437         HttpSession JavaDoc session = request.getSession();
438         ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
439
440         // safety check for missing required parameter.
441
if (cart.getWebSiteId() == null) {
442             cart.setWebSiteId(CatalogWorker.getWebSiteId(request));
443         }
444
445         // locate the user's identity
446
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
447         if (userLogin == null) {
448             userLogin = (GenericValue) session.getAttribute("autoUserLogin");
449         }
450
451         if (userLogin == null) {
452             // not logged in; cannot identify the user
453
return "success";
454         }
455
456         // find the list ID
457
String JavaDoc autoSaveListId = cart.getAutoSaveListId();
458         if (autoSaveListId == null) {
459             try {
460                 autoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
461             } catch (GeneralException e) {
462                 Debug.logError(e, module);
463             }
464             cart.setAutoSaveListId(autoSaveListId);
465         }
466
467         // check to see if we are okay to load this list
468
java.sql.Timestamp JavaDoc lastLoad = cart.getLastListRestore();
469         boolean okayToLoad = autoSaveListId == null ? false : (lastLoad == null ? true : false);
470         if (!okayToLoad && lastLoad != null) {
471             GenericValue shoppingList = null;
472             try {
473                 shoppingList = delegator.findByPrimaryKey("ShoppingList", UtilMisc.toMap("shoppingListId", autoSaveListId));
474             } catch (GenericEntityException e) {
475                 Debug.logError(e, module);
476             }
477             if (shoppingList != null) {
478                 java.sql.Timestamp JavaDoc lastModified = shoppingList.getTimestamp("lastAdminModified");
479                 if (lastModified != null) {
480                     if (lastModified.after(lastLoad)) {
481                         okayToLoad = true;
482                     }
483                     if (cart.size() == 0 && lastModified.after(cart.getCartCreatedTime())) {
484                         okayToLoad = true;
485                     }
486                 }
487             }
488         }
489
490         // load (restore) the list of we have determined it is okay to load
491
if (okayToLoad) {
492             String JavaDoc prodCatalogId = CatalogWorker.getCurrentCatalogId(request);
493             try {
494                 addListToCart(delegator, dispatcher, cart, prodCatalogId, autoSaveListId, false, false, false);
495                 cart.setLastListRestore(UtilDateTime.nowTimestamp());
496             } catch (IllegalArgumentException JavaDoc e) {
497                 Debug.logError(e, module);
498             }
499         }
500
501         return "success";
502     }
503
504     /**
505      * Remove all items from the given list.
506      */

507     public static int clearListInfo(GenericDelegator delegator, String JavaDoc shoppingListId) throws GenericEntityException {
508         // remove the survey responses first
509
delegator.removeByAnd("ShoppingListItemSurvey", UtilMisc.toMap("shoppingListId", shoppingListId));
510
511         // next remove the items
512
return delegator.removeByAnd("ShoppingListItem", UtilMisc.toMap("shoppingListId", shoppingListId));
513     }
514
515     /**
516      * Creates records for survey responses on survey items
517      */

518     public static int makeListItemSurveyResp(GenericDelegator delegator, GenericValue item, List JavaDoc surveyResps) throws GenericEntityException {
519         if (surveyResps != null && surveyResps.size() > 0) {
520             Iterator JavaDoc i = surveyResps.iterator();
521             int count = 0;
522             while (i.hasNext()) {
523                 String JavaDoc responseId = (String JavaDoc) i.next();
524                 GenericValue listResp = delegator.makeValue("ShoppingListItemSurvey", null);
525                 listResp.set("shoppingListId", item.getString("shoppingListId"));
526                 listResp.set("shoppingListItemSeqId", item.getString("shoppingListItemSeqId"));
527                 listResp.set("surveyResponseId", responseId);
528                 delegator.create(listResp);
529                 count++;
530             }
531             return count;
532         }
533         return -1;
534     }
535
536     /**
537      * Returns Map keyed on item sequence ID containing a list of survey response IDs
538      */

539     public static Map JavaDoc getItemSurveyInfos(List JavaDoc items) {
540         Map JavaDoc surveyInfos = new HashMap JavaDoc();
541         if (items != null && items.size() > 0) {
542             Iterator JavaDoc itemIt = items.iterator();
543             while (itemIt.hasNext()) {
544                 GenericValue item = (GenericValue) itemIt.next();
545                 String JavaDoc listId = item.getString("shoppingListId");
546                 String JavaDoc itemId = item.getString("shoppingListItemSeqId");
547                 surveyInfos.put(listId + "." + itemId, getItemSurveyInfo(item));
548             }
549         }
550
551         return surveyInfos;
552     }
553
554     /**
555      * Returns a list of survey response IDs for a shopping list item
556      */

557     public static List JavaDoc getItemSurveyInfo(GenericValue item) {
558         List JavaDoc responseIds = new ArrayList JavaDoc();
559         List JavaDoc surveyResp = null;
560         try {
561             surveyResp = item.getRelated("ShoppingListItemSurvey");
562         } catch (GenericEntityException e) {
563             Debug.logError(e, module);
564         }
565
566         if (surveyResp != null || surveyResp.size() > 0) {
567             Iterator JavaDoc respIt = surveyResp.iterator();
568             while (respIt.hasNext()) {
569                 GenericValue resp = (GenericValue) respIt.next();
570                 responseIds.add(resp.getString("surveyResponseId"));
571             }
572         }
573
574         return responseIds;
575     }
576
577     private static GenericValue getCartUserLogin(ShoppingCart cart) {
578         GenericValue ul = cart.getUserLogin();
579         if (ul == null) {
580             ul = cart.getAutoUserLogin();
581         }
582         return ul;
583     }
584
585     private static String JavaDoc[] makeCartItemsArray(ShoppingCart cart) {
586         int len = cart.size();
587         String JavaDoc[] arr = new String JavaDoc[len];
588         for (int i = 0; i < len; i++) {
589             arr[i] = new Integer JavaDoc(i).toString();
590         }
591         return arr;
592     }
593 }
594
Popular Tags