KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > product > product > ProductEvents


1 /*
2  * $Id: ProductEvents.java 6367 2005-12-19 05:41:37Z 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.product.product;
25
26 import java.sql.Timestamp JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.HashSet JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedList JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set 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 javolution.util.FastMap;
40
41 import org.ofbiz.base.util.Debug;
42 import org.ofbiz.base.util.UtilDateTime;
43 import org.ofbiz.base.util.UtilHttp;
44 import org.ofbiz.base.util.UtilMisc;
45 import org.ofbiz.base.util.UtilParse;
46 import org.ofbiz.base.util.UtilProperties;
47 import org.ofbiz.base.util.UtilValidate;
48 import org.ofbiz.base.util.string.FlexibleStringExpander;
49 import org.ofbiz.entity.GenericDelegator;
50 import org.ofbiz.entity.GenericEntityException;
51 import org.ofbiz.entity.GenericPK;
52 import org.ofbiz.entity.GenericValue;
53 import org.ofbiz.entity.condition.EntityCondition;
54 import org.ofbiz.entity.condition.EntityConditionList;
55 import org.ofbiz.entity.condition.EntityExpr;
56 import org.ofbiz.entity.condition.EntityOperator;
57 import org.ofbiz.entity.transaction.GenericTransactionException;
58 import org.ofbiz.entity.transaction.TransactionUtil;
59 import org.ofbiz.entity.util.EntityListIterator;
60 import org.ofbiz.entity.util.EntityUtil;
61 import org.ofbiz.product.store.ProductStoreWorker;
62 import org.ofbiz.security.Security;
63 import org.ofbiz.service.GenericServiceException;
64 import org.ofbiz.service.LocalDispatcher;
65
66 /**
67  * Product Information Related Events
68  *
69  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
70  * @version $Rev: 6367 $
71  * @since 2.0
72  */

73 public class ProductEvents {
74
75     public static final String JavaDoc module = ProductEvents.class.getName();
76     public static final String JavaDoc resource = "ProductUiLabels";
77
78     /**
79      * Updates ProductKeyword information according to UPDATE_MODE parameter, only support CREATE and DELETE, no modify becuse all fields are PKs
80      *
81      * @param request
82      * The HTTPRequest object for the current request
83      * @param response
84      * The HTTPResponse object for the current request
85      * @return String specifying the exit status of this event
86      */

87     public static String JavaDoc updateProductKeyword(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
88         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
89         Security security = (Security) request.getAttribute("security");
90
91         String JavaDoc updateMode = request.getParameter("UPDATE_MODE");
92
93         if (updateMode == null || updateMode.length() <= 0) {
94             String JavaDoc errMsg = UtilProperties.getMessage(resource,"productevents.updatemode_not_specified", UtilHttp.getLocale(request));
95             request.setAttribute("_ERROR_MESSAGE_", errMsg);
96             Debug.logWarning("[ProductEvents.updateProductKeyword] Update Mode was not specified, but is required", module);
97             return "error";
98         }
99
100         // check permissions before moving on...
101
if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
102             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
103             String JavaDoc errMsg = UtilProperties.getMessage(resource,"productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
104             request.setAttribute("_ERROR_MESSAGE_", errMsg);
105             return "error";
106         }
107
108         String JavaDoc productId = request.getParameter("PRODUCT_ID");
109         String JavaDoc keyword = request.getParameter("KEYWORD");
110         String JavaDoc relevancyWeightString = request.getParameter("relevancyWeight");
111         Long JavaDoc relevancyWeight = null;
112         if (UtilValidate.isNotEmpty(relevancyWeightString)) {
113             try {
114                 relevancyWeight = Long.valueOf(relevancyWeightString);
115             } catch (NumberFormatException JavaDoc e) {
116                 String JavaDoc errMsg = "Bad format for relevancyWeight [" + relevancyWeightString + "]: " + e.toString();
117                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
118                 return "error";
119             }
120         }
121
122         String JavaDoc errMsgTemp = "";
123         if (!UtilValidate.isNotEmpty(productId)) {
124             errMsgTemp += ("<li>" + UtilProperties.getMessage(resource,"productevents.product_ID_missing", UtilHttp.getLocale(request)));
125         }
126         if (!UtilValidate.isNotEmpty(keyword)) {
127             errMsgTemp += ("<li>" + UtilProperties.getMessage(resource,"productevents.keyword_missing", UtilHttp.getLocale(request)));
128         }
129         if (errMsgTemp.length() > 0) {
130             errMsgTemp += ("<b>" + UtilProperties.getMessage(resource,"productevents.following_errors_occurred", UtilHttp.getLocale(request)));
131             errMsgTemp += ("</b><br/><ul>" + errMsgTemp + "</ul>");
132             request.setAttribute("_ERROR_MESSAGE_", errMsgTemp);
133             return "error";
134         }
135
136         if (updateMode.equals("CREATE")) {
137             keyword = keyword.toLowerCase();
138
139             GenericValue productKeyword = delegator.makeValue("ProductKeyword", UtilMisc.toMap("productId", productId, "keyword", keyword, "relevancyWeight", relevancyWeight));
140             GenericValue newValue = null;
141
142             try {
143                 newValue = delegator.findByPrimaryKey(productKeyword.getPrimaryKey());
144             } catch (GenericEntityException e) {
145                 Debug.logWarning(e.getMessage(), module);
146                 newValue = null;
147             }
148
149             if (newValue != null) {
150                 String JavaDoc errMsg = UtilProperties.getMessage(resource,"productevents.could_not_create_productkeyword_entry_exists", UtilHttp.getLocale(request));
151                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
152                 return "error";
153             }
154
155             try {
156                 productKeyword = productKeyword.create();
157             } catch (GenericEntityException e) {
158                 Debug.logWarning(e.getMessage(), module);
159                 productKeyword = null;
160             }
161             if (productKeyword == null) {
162                 String JavaDoc errMsg = UtilProperties.getMessage(resource,"productevents.could_not_create_productkeyword_entry_write", UtilHttp.getLocale(request));
163                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
164                 return "error";
165             }
166         } else if (updateMode.equals("DELETE")) {
167             GenericValue productKeyword = null;
168
169             try {
170                 productKeyword = delegator.findByPrimaryKey("ProductKeyword", UtilMisc.toMap("productId", productId, "keyword", keyword));
171             } catch (GenericEntityException e) {
172                 Debug.logWarning(e.getMessage(), module);
173                 productKeyword = null;
174             }
175             if (productKeyword == null) {
176                 String JavaDoc errMsg = UtilProperties.getMessage(resource,"productevents.could_not_remove_productkeyword_entry_notexists", UtilHttp.getLocale(request));
177                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
178                 return "error";
179             }
180             try {
181                 productKeyword.remove();
182             } catch (GenericEntityException e) {
183                 String JavaDoc errMsg = UtilProperties.getMessage(resource,"productevents.could_not_remove_productkeyword_entry_writeerror", UtilHttp.getLocale(request));
184                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
185                 Debug.logWarning("[ProductEvents.updateProductKeyword] Could not remove product-keyword (write error); message: " + e.getMessage(), module);
186                 return "error";
187             }
188         } else {
189             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
190             String JavaDoc errMsg = UtilProperties.getMessage(resource,"productevents.specified_update_mode_not_supported", messageMap, UtilHttp.getLocale(request));
191             request.setAttribute("_ERROR_MESSAGE_", errMsg);
192             return "error";
193         }
194
195         return "success";
196     }
197
198     /**
199      * Update (create/induce or delete) all keywords for a given Product
200      *
201      * @param request
202      * The HTTPRequest object for the current request
203      * @param response
204      * The HTTPResponse object for the current request
205      * @return String specifying the exit status of this event
206      */

207     public static String JavaDoc updateProductKeywords(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
208         String JavaDoc errMsg = "";
209         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
210         Security security = (Security) request.getAttribute("security");
211
212         String JavaDoc updateMode = request.getParameter("UPDATE_MODE");
213
214         if (updateMode == null || updateMode.length() <= 0) {
215             errMsg = UtilProperties.getMessage(resource,"productevents.updatemode_not_specified", UtilHttp.getLocale(request));
216             request.setAttribute("_ERROR_MESSAGE_", errMsg);
217             Debug.logWarning("[ProductEvents.updateProductKeywords] Update Mode was not specified, but is required", module);
218             return "error";
219         }
220
221         // check permissions before moving on...
222
if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
223             errMsg = UtilProperties.getMessage(resource,"productevents.not_sufficient_permissions", UtilHttp.getLocale(request));
224             request.setAttribute( "_ERROR_MESSAGE_", errMsg);
225             return "error";
226         }
227
228         String JavaDoc productId = request.getParameter("PRODUCT_ID");
229
230         if (!UtilValidate.isNotEmpty(productId)) {
231             errMsg = UtilProperties.getMessage(resource,"productevents.no_product_ID_specified_keywords", UtilHttp.getLocale(request));
232             request.setAttribute("_ERROR_MESSAGE_", errMsg);
233             return "error";
234         }
235
236         GenericValue product = null;
237
238         try {
239             product = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId));
240         } catch (GenericEntityException e) {
241             Debug.logWarning(e.getMessage(), module);
242             product = null;
243         }
244         if (product == null) {
245             Map JavaDoc messageMap = UtilMisc.toMap("productId", productId);
246             errMsg = UtilProperties.getMessage(resource,"productevents.product_with_productId_not_found_keywords", messageMap, UtilHttp.getLocale(request));
247             request.setAttribute("_ERROR_MESSAGE_", errMsg);
248             return "error";
249         }
250
251         if (updateMode.equals("CREATE")) {
252             try {
253                 KeywordSearch.induceKeywords(product, true);
254             } catch (GenericEntityException e) {
255                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_create_keywords_write", UtilHttp.getLocale(request));
256                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
257                 return "error";
258             }
259         } else if (updateMode.equals("DELETE")) {
260             try {
261                 product.removeRelated("ProductKeyword");
262             } catch (GenericEntityException e) {
263                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_remove_keywords_write", UtilHttp.getLocale(request));
264                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
265                 Debug.logWarning("[ProductEvents.updateProductKeywords] Could not remove product-keywords (write error); message: " + e.getMessage(), module);
266                 return "error";
267             }
268         } else {
269             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
270             errMsg = UtilProperties.getMessage(resource,"productevents.specified_update_mode_not_supported", messageMap, UtilHttp.getLocale(request));
271             request.setAttribute("_ERROR_MESSAGE_", errMsg);
272             return "error";
273         }
274
275         return "success";
276     }
277
278     /**
279      * Updates/adds keywords for all products
280      *
281      * @param request HTTPRequest object for the current request
282      * @param response HTTPResponse object for the current request
283      * @return String specifying the exit status of this event
284      */

285     public static String JavaDoc updateAllKeywords(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
286         //String errMsg = "";
287
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
288         Security security = (Security) request.getAttribute("security");
289         Timestamp JavaDoc nowTimestamp = UtilDateTime.nowTimestamp();
290
291         String JavaDoc updateMode = "CREATE";
292         String JavaDoc errMsg=null;
293
294         String JavaDoc doAll = request.getParameter("doAll");
295
296         // check permissions before moving on...
297
if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
298             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
299             errMsg = UtilProperties.getMessage(resource,"productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
300             request.setAttribute("_ERROR_MESSAGE_", errMsg);
301             return "error";
302         }
303
304         EntityCondition condition = null;
305         if (!"Y".equals(doAll)) {
306             List JavaDoc condList = new LinkedList JavaDoc();
307             condList.add(new EntityExpr(new EntityExpr("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, new EntityExpr("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N")));
308             if ("true".equals(UtilProperties.getPropertyValue("prodsearch", "index.ignore.variants"))) {
309                 condList.add(new EntityExpr(new EntityExpr("isVariant", EntityOperator.EQUALS, null), EntityOperator.OR, new EntityExpr("isVariant", EntityOperator.NOT_EQUAL, "Y")));
310             }
311             if ("true".equals(UtilProperties.getPropertyValue("prodsearch", "index.ignore.discontinued.sales"))) {
312                 condList.add(new EntityExpr(new EntityExpr("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, new EntityExpr("salesDiscontinuationDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp)));
313             }
314             condition = new EntityConditionList(condList, EntityOperator.AND);
315         } else {
316             condition = new EntityExpr(new EntityExpr("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, new EntityExpr("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N"));
317         }
318
319
320         EntityListIterator entityListIterator = null;
321         try {
322             if (Debug.infoOn()) {
323                 long count = delegator.findCountByCondition("Product", condition, null);
324                 Debug.logInfo("========== Found " + count + " products to index ==========", module);
325             }
326             entityListIterator = delegator.findListIteratorByCondition("Product", condition, null, null);
327         } catch (GenericEntityException gee) {
328             Debug.logWarning(gee, gee.getMessage(), module);
329             Map JavaDoc messageMap = UtilMisc.toMap("gee", gee.toString());
330             errMsg = UtilProperties.getMessage(resource,"productevents.error_getting_product_list", messageMap, UtilHttp.getLocale(request));
331             request.setAttribute("_ERROR_MESSAGE_", errMsg);
332             return "error";
333         }
334
335         int numProds = 0;
336         int errProds = 0;
337
338         GenericValue product = null;
339         while ((product = (GenericValue) entityListIterator.next()) != null) {
340             try {
341                 KeywordSearch.induceKeywords(product, "Y".equals(doAll));
342             } catch (GenericEntityException e) {
343                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_create_keywords_write", UtilHttp.getLocale(request));
344                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
345                 Debug.logWarning("[ProductEvents.updateAllKeywords] Could not create product-keyword (write error); message: " + e.getMessage(), module);
346                 try {
347                     entityListIterator.close();
348                 } catch (GenericEntityException gee) {
349                     Debug.logError(gee, "Error closing EntityListIterator when indexing product keywords.", module);
350                 }
351                 errProds++;
352             }
353             numProds++;
354             if (numProds % 500 == 0) {
355                 Debug.logInfo("Keywords indexed for " + numProds + " so far", module);
356             }
357         }
358
359         if (entityListIterator != null) {
360             try {
361                 entityListIterator.close();
362             } catch (GenericEntityException gee) {
363                 Debug.logError(gee, "Error closing EntityListIterator when indexing product keywords.", module);
364             }
365         }
366
367         if (errProds == 0) {
368             Map JavaDoc messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
369             errMsg = UtilProperties.getMessage(resource,"productevents.keyword_creation_complete_for_products", messageMap, UtilHttp.getLocale(request));
370             request.setAttribute("_EVENT_MESSAGE_", errMsg);
371             return "success";
372         } else {
373             Map JavaDoc messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
374             messageMap.put("errProds", Integer.toString(errProds));
375             errMsg = UtilProperties.getMessage(resource,"productevents.keyword_creation_complete_for_products_with_errors", messageMap, UtilHttp.getLocale(request));
376             request.setAttribute( "_ERROR_MESSAGE_", errMsg);
377             return "error";
378         }
379     }
380
381     /**
382      * Updates ProductAssoc information according to UPDATE_MODE parameter
383      *
384      * @param request The HTTPRequest object for the current request
385      * @param response The HTTPResponse object for the current request
386      * @return String specifying the exit status of this event
387      */

388     public static String JavaDoc updateProductAssoc(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
389         String JavaDoc errMsg = "";
390         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
391         Security security = (Security) request.getAttribute("security");
392
393         String JavaDoc updateMode = request.getParameter("UPDATE_MODE");
394
395         if (updateMode == null || updateMode.length() <= 0) {
396             errMsg = UtilProperties.getMessage(resource,"productevents.updatemode_not_specified", UtilHttp.getLocale(request));
397             request.setAttribute("_ERROR_MESSAGE_", errMsg);
398             Debug.logWarning("[ProductEvents.updateProductAssoc] Update Mode was not specified, but is required", module);
399             return "error";
400         }
401
402         // check permissions before moving on...
403
if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
404             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
405             errMsg = UtilProperties.getMessage(resource,"productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
406             request.setAttribute("_ERROR_MESSAGE_", errMsg);
407             return "error";
408         }
409
410         String JavaDoc productId = request.getParameter("PRODUCT_ID");
411         String JavaDoc productIdTo = request.getParameter("PRODUCT_ID_TO");
412         String JavaDoc productAssocTypeId = request.getParameter("PRODUCT_ASSOC_TYPE_ID");
413         String JavaDoc fromDateStr = request.getParameter("FROM_DATE");
414         Timestamp JavaDoc fromDate = null;
415
416         try {
417             if (delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId)) == null) {
418                 Map JavaDoc messageMap = UtilMisc.toMap("productId", productId);
419                 errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.product_with_id_not_found", messageMap, UtilHttp.getLocale(request)));
420             }
421             if (delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productIdTo)) == null) {
422                 Map JavaDoc messageMap = UtilMisc.toMap("productIdTo", productIdTo);
423                 errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.product_To_with_id_not_found", messageMap, UtilHttp.getLocale(request)));
424             }
425         } catch (GenericEntityException e) {
426             // if there is an exception for either, the other probably wont work
427
Debug.logWarning(e, module);
428         }
429
430         if (UtilValidate.isNotEmpty(fromDateStr)) {
431             try {
432                 fromDate = Timestamp.valueOf(fromDateStr);
433             } catch (Exception JavaDoc e) {
434                 errMsg += "<li>From Date not formatted correctly.";
435             }
436         }
437         if (!UtilValidate.isNotEmpty(productId))
438             errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.product_ID_missing", UtilHttp.getLocale(request)));
439         if (!UtilValidate.isNotEmpty(productIdTo))
440             errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.product_ID_To_missing", UtilHttp.getLocale(request)));
441         if (!UtilValidate.isNotEmpty(productAssocTypeId))
442             errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.association_type_ID_missing", UtilHttp.getLocale(request)));
443         // from date is only required if update mode is not CREATE
444
if (!updateMode.equals("CREATE") && !UtilValidate.isNotEmpty(fromDateStr))
445             errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.from_date_missing", UtilHttp.getLocale(request)));
446         if (errMsg.length() > 0) {
447             errMsg += ("<b>" + UtilProperties.getMessage(resource,"productevents.following_errors_occurred", UtilHttp.getLocale(request)));
448             errMsg += ("</b><br/><ul>" + errMsg + "</ul>");
449             request.setAttribute("_ERROR_MESSAGE_", errMsg);
450             return "error";
451         }
452
453         // clear some cache entries
454
delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productId", productId));
455         delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productId", productId, "productAssocTypeId", productAssocTypeId));
456
457         delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productIdTo", productIdTo));
458         delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productIdTo", productIdTo, "productAssocTypeId", productAssocTypeId));
459
460         delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productAssocTypeId", productAssocTypeId));
461         delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productId", productId, "productIdTo", productIdTo, "productAssocTypeId", productAssocTypeId, "fromDate", fromDate));
462
463         GenericValue tempProductAssoc = delegator.makeValue("ProductAssoc", UtilMisc.toMap("productId", productId, "productIdTo", productIdTo, "productAssocTypeId", productAssocTypeId, "fromDate", fromDate));
464
465         if (updateMode.equals("DELETE")) {
466             GenericValue productAssoc = null;
467
468             try {
469                 productAssoc = delegator.findByPrimaryKey(tempProductAssoc.getPrimaryKey());
470             } catch (GenericEntityException e) {
471                 Debug.logWarning(e.getMessage(), module);
472                 productAssoc = null;
473             }
474             if (productAssoc == null) {
475                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_remove_product_association_exist", UtilHttp.getLocale(request));
476                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
477                 return "error";
478             }
479             try {
480                 productAssoc.remove();
481             } catch (GenericEntityException e) {
482                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_remove_product_association_write", UtilHttp.getLocale(request));
483                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
484                 Debug.logWarning("[ProductEvents.updateProductAssoc] Could not remove product association (write error); message: " + e.getMessage(), module);
485                 return "error";
486             }
487             return "success";
488         }
489
490         String JavaDoc thruDateStr = request.getParameter("THRU_DATE");
491         String JavaDoc reason = request.getParameter("REASON");
492         String JavaDoc instruction = request.getParameter("INSTRUCTION");
493         String JavaDoc quantityStr = request.getParameter("QUANTITY");
494         String JavaDoc sequenceNumStr = request.getParameter("SEQUENCE_NUM");
495         Timestamp JavaDoc thruDate = null;
496         Double JavaDoc quantity = null;
497         Long JavaDoc sequenceNum = null;
498
499         if (UtilValidate.isNotEmpty(thruDateStr)) {
500             try {
501                 thruDate = Timestamp.valueOf(thruDateStr);
502             } catch (Exception JavaDoc e) {
503                 errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.thru_date_not_formatted_correctly", UtilHttp.getLocale(request)));
504             }
505         }
506         if (UtilValidate.isNotEmpty(quantityStr)) {
507             try {
508                 quantity = Double.valueOf(quantityStr);
509             } catch (Exception JavaDoc e) {
510                 errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.quantity_not_formatted_correctly", UtilHttp.getLocale(request)));
511             }
512         }
513         if (UtilValidate.isNotEmpty(sequenceNumStr)) {
514             try {
515                 sequenceNum = Long.valueOf(sequenceNumStr);
516             } catch (Exception JavaDoc e) {
517                 errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.sequenceNum_not_formatted_correctly", UtilHttp.getLocale(request)));
518             }
519         }
520         if (errMsg.length() > 0) {
521             errMsg += ("<b>" + UtilProperties.getMessage(resource,"productevents.following_errors_occurred", UtilHttp.getLocale(request)));
522             errMsg += ("</b><br/><ul>" + errMsg + "</ul>");
523             request.setAttribute("_ERROR_MESSAGE_", errMsg);
524             return "error";
525         }
526
527         tempProductAssoc.set("thruDate", thruDate);
528         tempProductAssoc.set("reason", reason);
529         tempProductAssoc.set("instruction", instruction);
530         tempProductAssoc.set("quantity", quantity);
531         tempProductAssoc.set("sequenceNum", sequenceNum);
532
533         if (updateMode.equals("CREATE")) {
534             // if no from date specified, set to now
535
if (fromDate == null) {
536                 fromDate = new Timestamp JavaDoc(new java.util.Date JavaDoc().getTime());
537                 tempProductAssoc.set("fromDate", fromDate);
538                 request.setAttribute("ProductAssocCreateFromDate", fromDate);
539             }
540
541             GenericValue productAssoc = null;
542
543             try {
544                 productAssoc = delegator.findByPrimaryKey(tempProductAssoc.getPrimaryKey());
545             } catch (GenericEntityException e) {
546                 Debug.logWarning(e.getMessage(), module);
547                 productAssoc = null;
548             }
549             if (productAssoc != null) {
550                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_create_product_association_exists", UtilHttp.getLocale(request));
551                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
552                 return "error";
553             }
554             try {
555                 productAssoc = tempProductAssoc.create();
556             } catch (GenericEntityException e) {
557                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_create_product_association_write", UtilHttp.getLocale(request));
558                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
559                 Debug.logWarning("[ProductEvents.updateProductAssoc] Could not create product association (write error); message: " + e.getMessage(), module);
560                 return "error";
561             }
562         } else if (updateMode.equals("UPDATE")) {
563             try {
564                 tempProductAssoc.store();
565             } catch (GenericEntityException e) {
566                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_update_product_association_write", UtilHttp.getLocale(request));
567                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
568                 Debug.logWarning("[ProductEvents.updateProductAssoc] Could not update product association (write error); message: " + e.getMessage(), module);
569                 return "error";
570             }
571         } else {
572             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
573             errMsg = UtilProperties.getMessage(resource,"productevents.specified_update_mode_not_supported", messageMap, UtilHttp.getLocale(request));
574             request.setAttribute("_ERROR_MESSAGE_", errMsg);
575             return "error";
576         }
577
578         return "success";
579     }
580
581     public static String JavaDoc updateAttribute(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
582         String JavaDoc errMsg = "";
583         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
584         Security security = (Security) request.getAttribute("security");
585
586         String JavaDoc updateMode = request.getParameter("UPDATE_MODE");
587
588         if (updateMode == null || updateMode.length() <= 0) {
589             errMsg = UtilProperties.getMessage(resource,"productevents.updatemode_not_specified", UtilHttp.getLocale(request));
590             request.setAttribute("_ERROR_MESSAGE_", errMsg);
591             Debug.logWarning("[CategoryEvents.updateCategory] Update Mode was not specified, but is required", module);
592             return "error";
593         }
594
595         // check permissions before moving on...
596
if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
597             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
598             errMsg = UtilProperties.getMessage(resource,"productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
599             request.setAttribute("_ERROR_MESSAGE_", errMsg);
600             return "error";
601         }
602
603         String JavaDoc productId = request.getParameter("PRODUCT_ID");
604         String JavaDoc attrName = request.getParameter("ATTRIBUTE_NAME");
605         String JavaDoc attrValue = request.getParameter("ATTRIBUTE_VALUE");
606         String JavaDoc attrType = request.getParameter("ATTRIBUTE_TYPE");
607
608         if (!UtilValidate.isNotEmpty(productId))
609             errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.product_ID_missing", UtilHttp.getLocale(request)));
610         if (!UtilValidate.isNotEmpty(attrName))
611             errMsg += ("<li>" + UtilProperties.getMessage(resource,"productevents.attribute_name_missing", UtilHttp.getLocale(request)));
612         if (errMsg.length() > 0) {
613             errMsg += ("<b>" + UtilProperties.getMessage(resource,"productevents.following_errors_occurred", UtilHttp.getLocale(request)));
614             errMsg += ("</b><br/><ul>" + errMsg + "</ul>");
615             request.setAttribute("_ERROR_MESSAGE_", errMsg);
616             return "error";
617         }
618
619         List JavaDoc toBeStored = new LinkedList JavaDoc();
620         GenericValue attribute = delegator.makeValue("ProductAttribute", null);
621
622         toBeStored.add(attribute);
623         attribute.set("productId", productId);
624         attribute.set("attrName", attrName);
625         attribute.set("attrValue", attrValue);
626         attribute.set("attrType", attrType);
627
628         if (updateMode.equals("CREATE")) {
629             try {
630                 delegator.storeAll(toBeStored);
631             } catch (GenericEntityException e) {
632                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_create_attribute_write", UtilHttp.getLocale(request));
633                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
634                 return "error";
635             }
636         } else if (updateMode.equals("UPDATE")) {
637             try {
638                 delegator.storeAll(toBeStored);
639             } catch (GenericEntityException e) {
640                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_update_attribute_write", UtilHttp.getLocale(request));
641                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
642                 Debug.logWarning("[ProductEvents.updateAttribute] Could not update attribute (write error); message: " + e.getMessage(), module);
643                 return "error";
644             }
645         } else if (updateMode.equals("DELETE")) {
646             try {
647                 delegator.removeByAnd("ProductAttribute", UtilMisc.toMap("productId", productId, "attrName", attrName));
648             } catch (GenericEntityException e) {
649                 errMsg = UtilProperties.getMessage(resource,"productevents.could_not_delete_attribute_write", UtilHttp.getLocale(request));
650                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
651                 Debug.logWarning("[ProductEvents.updateAttribute] Could not delete attribute (write error); message: " + e.getMessage(), module);
652                 return "error";
653             }
654         } else {
655             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
656             errMsg = UtilProperties.getMessage(resource,"productevents.specified_update_mode_not_supported", messageMap, UtilHttp.getLocale(request));
657             request.setAttribute("_ERROR_MESSAGE_", errMsg);
658             return "error";
659         }
660
661         return "success";
662     }
663
664     /** Event to clear the last viewed categories */
665     public static String JavaDoc clearLastViewedCategories(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
666         // just store a new empty list in the session
667
HttpSession JavaDoc session = request.getSession();
668         if (session != null) {
669             session.setAttribute("lastViewedCategories", new LinkedList JavaDoc());
670         }
671         return "success";
672     }
673
674     /** Event to clear the last vieweed products */
675     public static String JavaDoc clearLastViewedProducts(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
676         // just store a new empty list in the session
677
HttpSession JavaDoc session = request.getSession();
678         if (session != null) {
679             session.setAttribute("lastViewedProducts", new LinkedList JavaDoc());
680         }
681         return "success";
682     }
683
684     /** Event to clear the last viewed history (products/categories/searchs) */
685     public static String JavaDoc clearAllLastViewed(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
686         ProductEvents.clearLastViewedCategories(request, response);
687         ProductEvents.clearLastViewedProducts(request, response);
688         ProductSearchSession.clearSearchOptionsHistoryList(request, response);
689         return "success";
690     }
691
692     public static String JavaDoc updateProductQuickAdminShipping(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
693         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
694         Timestamp JavaDoc nowTimestamp = UtilDateTime.nowTimestamp();
695         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
696         String JavaDoc variantProductId = request.getParameter("productId0");
697
698         boolean applyToAll = (request.getParameter("applyToAll") != null);
699
700         try {
701             boolean beganTransaction = TransactionUtil.begin();
702             try {
703                 // check for variantProductId - this will mean that we have multiple ship info to update
704
if (variantProductId == null) {
705                     // only single product to update
706
String JavaDoc productId = request.getParameter("productId");
707                     GenericValue product = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId));
708                     product.set("lastModifiedDate", nowTimestamp);
709                     product.setString("lastModifiedByUserLogin", userLogin.getString("userLoginId"));
710                     try {
711                         product.set("productHeight", UtilParse.parseDoubleForEntity(request.getParameter("productHeight")));
712                         product.set("productWidth", UtilParse.parseDoubleForEntity(request.getParameter("productWidth")));
713                         product.set("productDepth", UtilParse.parseDoubleForEntity(request.getParameter("productDepth")));
714                         product.set("weight", UtilParse.parseDoubleForEntity(request.getParameter("weight")));
715     
716                         // default unit settings for shipping parameters
717
product.set("heightUomId", "LEN_in");
718                         product.set("widthUomId", "LEN_in");
719                         product.set("depthUomId", "LEN_in");
720                         product.set("weightUomId", "WT_oz");
721     
722                         Double JavaDoc floz = UtilParse.parseDoubleForEntity(request.getParameter("~floz"));
723                         Double JavaDoc ml = UtilParse.parseDoubleForEntity(request.getParameter("~ml"));
724                         Double JavaDoc ntwt = UtilParse.parseDoubleForEntity(request.getParameter("~ntwt"));
725                         Double JavaDoc grams = UtilParse.parseDoubleForEntity(request.getParameter("~grams"));
726     
727                         List JavaDoc currentProductFeatureAndAppls = EntityUtil.filterByDate(delegator.findByAnd("ProductFeatureAndAppl", UtilMisc.toMap("productId", productId, "productFeatureApplTypeId", "STANDARD_FEATURE")), true);
728                         setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ozUS", "AMOUNT", floz);
729                         setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ml", "AMOUNT", ml);
730                         setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_g", "AMOUNT", grams);
731                         setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_oz", "AMOUNT", ntwt);
732                         product.store();
733     
734                     } catch (NumberFormatException JavaDoc nfe) {
735                         String JavaDoc errMsg = "Shipping Dimensions and Weights must be numbers.";
736                         request.setAttribute("_ERROR_MESSAGE_", errMsg);
737                         Debug.logError(nfe, errMsg, module);
738                         return "error";
739                     }
740                 } else {
741                     // multiple products, so use a numeric suffix to get them all
742
int prodIdx = 0;
743                     int attribIdx = 0;
744                     String JavaDoc productId = variantProductId;
745                     do {
746                         GenericValue product = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId));
747                         try {
748                             product.set("productHeight", UtilParse.parseDoubleForEntity(request.getParameter("productHeight" + attribIdx)));
749                             product.set("productWidth", UtilParse.parseDoubleForEntity(request.getParameter("productWidth" + attribIdx)));
750                             product.set("productDepth", UtilParse.parseDoubleForEntity(request.getParameter("productDepth" + attribIdx)));
751                             product.set("weight", UtilParse.parseDoubleForEntity(request.getParameter("weight" + attribIdx)));
752                             Double JavaDoc floz = UtilParse.parseDoubleForEntity(request.getParameter("~floz" + attribIdx));
753                             Double JavaDoc ml = UtilParse.parseDoubleForEntity(request.getParameter("~ml" + attribIdx));
754                             Double JavaDoc ntwt = UtilParse.parseDoubleForEntity(request.getParameter("~ntwt" + attribIdx));
755                             Double JavaDoc grams = UtilParse.parseDoubleForEntity(request.getParameter("~grams" + attribIdx));
756     
757                                 List JavaDoc currentProductFeatureAndAppls = EntityUtil.filterByDate(delegator.findByAnd("ProductFeatureAndAppl", UtilMisc.toMap("productId", productId, "productFeatureApplTypeId", "STANDARD_FEATURE")), true);
758                                 setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ozUS", "AMOUNT", floz);
759                                 setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ml", "AMOUNT", ml);
760                                 setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_g", "AMOUNT", grams);
761                                 setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_oz", "AMOUNT", ntwt);
762                             product.store();
763                         } catch (NumberFormatException JavaDoc nfe) {
764                             String JavaDoc errMsg = "Shipping Dimensions and Weights must be numbers.";
765                             request.setAttribute("_ERROR_MESSAGE_", errMsg);
766                             Debug.logError(nfe, errMsg, module);
767                             return "error";
768                         }
769                         prodIdx++;
770                         if (!applyToAll) {
771                             attribIdx = prodIdx;
772                         }
773                         productId = request.getParameter("productId" + prodIdx);
774                     } while (productId != null);
775                 }
776                 TransactionUtil.commit(beganTransaction);
777             } catch (GenericEntityException e) {
778                 String JavaDoc errMsg = "Error updating quick admin shipping settings: " + e.toString();
779                 Debug.logError(e, errMsg, module);
780                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
781                 TransactionUtil.rollback(beganTransaction, errMsg, e);
782                 return "error";
783             }
784         } catch (GenericTransactionException gte) {
785             String JavaDoc errMsg = "Error updating quick admin shipping settings: " + gte.toString();
786             Debug.logError(gte, errMsg, module);
787             request.setAttribute("_ERROR_MESSAGE_", errMsg);
788             return "error";
789         }
790         return "success";
791     }
792
793     /**
794      * find a specific feature in a given list, then update it or create it if it doesn't exist.
795      * @param delegator
796      * @param productId
797      * @param existingFeatures
798      * @param uomId
799      * @param productFeatureTypeId
800      * @param numberSpecified
801      * @return
802      * @throws GenericEntityException
803      */

804     private static void setOrCreateProdFeature(GenericDelegator delegator, String JavaDoc productId, List JavaDoc currentProductFeatureAndAppls,
805                                           String JavaDoc uomId, String JavaDoc productFeatureTypeId, Double JavaDoc numberSpecified) throws GenericEntityException {
806         
807         GenericValue productFeatureType = delegator.findByPrimaryKey("ProductFeatureType", UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId));
808         GenericValue uom = delegator.findByPrimaryKey("Uom", UtilMisc.toMap("uomId", uomId));
809         
810         Timestamp JavaDoc nowTimestamp = UtilDateTime.nowTimestamp();
811
812         // filter list of features to the one we'll be editing
813
List JavaDoc typeUomProductFeatureAndApplList = EntityUtil.filterByAnd(currentProductFeatureAndAppls, UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId, "uomId", uomId));
814
815         // go through each; need to remove? do it now
816
Iterator JavaDoc typeUomProductFeatureAndApplIter = typeUomProductFeatureAndApplList.iterator();
817         boolean foundOneEqual = false;
818         while (typeUomProductFeatureAndApplIter.hasNext()) {
819             GenericValue typeUomProductFeatureAndAppl = (GenericValue) typeUomProductFeatureAndApplIter.next();
820             if ((numberSpecified != null) && (numberSpecified.equals(typeUomProductFeatureAndAppl.getDouble("numberSpecified")))) {
821                 foundOneEqual = true;
822             } else {
823                 // remove the PFA...
824
GenericValue productFeatureAppl = delegator.makeValidValue("ProductFeatureAppl", typeUomProductFeatureAndAppl);
825                 productFeatureAppl.remove();
826             }
827         }
828
829         // NOTE: if numberSpecified is null then foundOneEqual will always be false, so need to check both
830
if (numberSpecified != null && !foundOneEqual) {
831             String JavaDoc productFeatureId = null;
832             List JavaDoc existingProductFeatureList = delegator.findByAnd("ProductFeature", UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId, "numberSpecified", numberSpecified, "uomId", uomId));
833             if (existingProductFeatureList.size() > 0) {
834                 GenericValue existingProductFeature = (GenericValue) existingProductFeatureList.get(0);
835                 productFeatureId = existingProductFeature.getString("productFeatureId");
836             } else {
837                 // doesn't exist, so create it
838
productFeatureId = delegator.getNextSeqId("ProductFeature").toString();
839                 GenericValue prodFeature = delegator.makeValue("ProductFeature", UtilMisc.toMap("productFeatureId", productFeatureId, "productFeatureTypeId", productFeatureTypeId));
840                 if (uomId != null) {
841                     prodFeature.set("uomId", uomId);
842                 }
843                 prodFeature.set("numberSpecified", numberSpecified);
844                 prodFeature.set("description", numberSpecified.toString() + (uom == null ? "" : (" " + uom.getString("description"))));
845                 
846                 // if there is a productFeatureCategory with the same id as the productFeatureType, use that category.
847
// otherwise, use a default category from the configuration
848
if (delegator.findByPrimaryKey("ProductFeatureCategory", UtilMisc.toMap("productFeatureCategoryId", productFeatureTypeId)) == null) {
849                     GenericValue productFeatureCategory = delegator.makeValue("ProductFeatureCategory", null);
850                     productFeatureCategory.set("productFeatureCategoryId", productFeatureTypeId);
851                     productFeatureCategory.set("description", productFeatureType.get("description"));
852                     productFeatureCategory.create();
853                 }
854                 prodFeature.set("productFeatureCategoryId", productFeatureTypeId);
855                 prodFeature.create();
856             }
857
858             delegator.create("ProductFeatureAppl", UtilMisc.toMap("productId", productId, "productFeatureId", productFeatureId,
859                     "productFeatureApplTypeId", "STANDARD_FEATURE", "fromDate", nowTimestamp));
860         }
861     }
862
863     public static String JavaDoc updateProductQuickAdminSelFeat(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
864         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
865         Timestamp JavaDoc nowTimestamp = UtilDateTime.nowTimestamp();
866         //GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
867
String JavaDoc productId = request.getParameter("productId");
868         String JavaDoc variantProductId = request.getParameter("productId0");
869         String JavaDoc useImagesProdId = request.getParameter("useImages");
870         String JavaDoc productFeatureTypeId = request.getParameter("productFeatureTypeId");
871         
872         if (UtilValidate.isEmpty(productFeatureTypeId)) {
873             String JavaDoc errMsg = "Error: please select a ProductFeature Type to add or update variant features.";
874             request.setAttribute("_ERROR_MESSAGE_", errMsg);
875             return "error";
876         }
877
878         try {
879             boolean beganTransaction = TransactionUtil.begin();
880             try {
881                 GenericValue productFeatureType = delegator.findByPrimaryKey("ProductFeatureType", UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId));
882                 if (productFeatureType == null) {
883                     String JavaDoc errMsg = "Error: the ProductFeature Type specified was not valid and one is require to add or update variant features.";
884                     request.setAttribute("_ERROR_MESSAGE_", errMsg);
885                     return "error";
886                 }
887                 
888                 // check for variantProductId - this will mean that we have multiple variants to update
889
if (variantProductId != null) {
890                     // multiple products, so use a numeric suffix to get them all
891
int attribIdx = 0;
892                     GenericValue product = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId));
893                     do {
894                         GenericValue variantProduct = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", variantProductId));
895                         String JavaDoc description = request.getParameter("description" + attribIdx);
896                         // blank means null, which means delete the feature application
897
if ((description != null) && (description.trim().length() < 1)) {
898                             description = null;
899                         }
900     
901                         Set JavaDoc variantDescRemoveToRemoveOnVirtual = new HashSet JavaDoc();
902                         checkUpdateFeatureApplByDescription(variantProductId, variantProduct, description, productFeatureTypeId, productFeatureType, "STANDARD_FEATURE", nowTimestamp, delegator, null, variantDescRemoveToRemoveOnVirtual);
903                         checkUpdateFeatureApplByDescription(productId, product, description, productFeatureTypeId, productFeatureType, "SELECTABLE_FEATURE", nowTimestamp, delegator, variantDescRemoveToRemoveOnVirtual, null);
904
905                         // update image urls
906
if ((useImagesProdId != null) && (useImagesProdId.equals(variantProductId))) {
907                             product.set("smallImageUrl", variantProduct.getString("smallImageUrl"));
908                             product.set("mediumImageUrl", variantProduct.getString("mediumImageUrl"));
909                             product.set("largeImageUrl", null);
910                             product.set("detailImageUrl", null);
911                             product.store();
912                         }
913                         attribIdx++;
914                         variantProductId = request.getParameter("productId" + attribIdx);
915                     } while (variantProductId != null);
916                 }
917     
918                 TransactionUtil.commit(beganTransaction);
919             } catch (GenericEntityException e) {
920                 String JavaDoc errMsg = "Error updating quick admin selectable feature settings: " + e.toString();
921                 Debug.logError(e, errMsg, module);
922                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
923                 TransactionUtil.rollback(beganTransaction, errMsg, e);
924                 return "error";
925             }
926         } catch (GenericTransactionException gte) {
927             String JavaDoc errMsg = "Error updating quick admin selectable feature settings: " + gte.toString();
928             Debug.logError(gte, errMsg, module);
929             request.setAttribute("_ERROR_MESSAGE_", errMsg);
930             return "error";
931         }
932         return "success";
933     }
934     
935     protected static void checkUpdateFeatureApplByDescription(String JavaDoc productId, GenericValue product, String JavaDoc description,
936             String JavaDoc productFeatureTypeId, GenericValue productFeatureType, String JavaDoc productFeatureApplTypeId,
937             Timestamp JavaDoc nowTimestamp, GenericDelegator delegator, Set JavaDoc descriptionsToRemove, Set JavaDoc descriptionsRemoved) throws GenericEntityException {
938         if (productFeatureType == null) {
939             return;
940         }
941
942         GenericValue productFeatureAndAppl = null;
943
944         Set JavaDoc descriptionsForThisType = new HashSet JavaDoc();
945         List JavaDoc productFeatureAndApplList = EntityUtil.filterByDate(delegator.findByAnd("ProductFeatureAndAppl", UtilMisc.toMap("productId", productId,
946                 "productFeatureApplTypeId", productFeatureApplTypeId, "productFeatureTypeId", productFeatureTypeId)), true);
947         if (productFeatureAndApplList.size() > 0) {
948             Iterator JavaDoc productFeatureAndApplIter = productFeatureAndApplList.iterator();
949             while (productFeatureAndApplIter.hasNext()) {
950                 productFeatureAndAppl = (GenericValue) productFeatureAndApplIter.next();
951                 GenericValue productFeatureAppl = delegator.makeValidValue("ProductFeatureAppl", productFeatureAndAppl);
952
953                 // remove productFeatureAppl IFF: productFeatureAppl != null && (description is empty/null || description is different than existing)
954
if (productFeatureAppl != null && (description == null || !description.equals(productFeatureAndAppl.getString("description")))) {
955                     // if descriptionsToRemove is not null, only remove if description is in that set
956
if (descriptionsToRemove == null || (descriptionsToRemove != null && descriptionsToRemove.contains(productFeatureAndAppl.get("description")))) {
957                         // okay, almost there: before removing it if this is a virtual product check to make SURE this feature's description doesn't exist on any of the variants; wouldn't want to remove something we should have kept around...
958
if ("Y".equals(product.getString("isVirtual"))) {
959                             boolean foundFeatureOnVariant = false;
960                             // get/check all the variants
961
List JavaDoc variantAssocs = product.getRelatedByAnd("MainProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_VARIANT"));
962                             List JavaDoc variants = EntityUtil.getRelated("AssocProduct", variantAssocs);
963                             Iterator JavaDoc variantIter = variants.iterator();
964                             while (!foundFeatureOnVariant && variantIter.hasNext()) {
965                                 GenericValue variant = (GenericValue) variantIter.next();
966                                 // get the selectable features for the variant
967
List JavaDoc variantProductFeatureAndAppls = variant.getRelated("ProductFeatureAndAppl",
968                                         UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId,
969                                                 "productFeatureApplTypeId", "STANDARD_FEATURE", "description", description), null);
970                                 if (variantProductFeatureAndAppls.size() > 0) {
971                                     foundFeatureOnVariant = true;
972                                 }
973                             }
974                             
975                             if (foundFeatureOnVariant) {
976                                 // don't remove this one!
977
continue;
978                             }
979                         }
980                         
981                         if (descriptionsRemoved != null) {
982                             descriptionsRemoved.add(productFeatureAndAppl.get("description"));
983                         }
984                         productFeatureAppl.remove();
985                         continue;
986                     }
987                 }
988                 
989                 // we got here, is still a valid description associated with this product
990
descriptionsForThisType.add(productFeatureAndAppl.get("description"));
991             }
992         }
993         
994         if (description != null && (productFeatureAndAppl == null || (productFeatureAndAppl != null && !descriptionsForThisType.contains(description)))) {
995             // need to add an appl, and possibly the feature
996

997             // see if a feature exists with the type and description specified (if doesn't exist will create later)
998
String JavaDoc productFeatureId = null;
999             List JavaDoc existingProductFeatureList = delegator.findByAnd("ProductFeature", UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId, "description", description));
1000            if (existingProductFeatureList.size() > 0) {
1001                GenericValue existingProductFeature = (GenericValue) existingProductFeatureList.get(0);
1002                productFeatureId = existingProductFeature.getString("productFeatureId");
1003            } else {
1004                // doesn't exist, so create it
1005
productFeatureId = delegator.getNextSeqId("ProductFeature").toString();
1006                GenericValue newProductFeature = delegator.makeValue("ProductFeature",
1007                        UtilMisc.toMap("productFeatureId", productFeatureId,
1008                                "productFeatureTypeId", productFeatureTypeId,
1009                                "description", description));
1010    
1011                // if there is a productFeatureCategory with the same id as the productFeatureType, use that category.
1012
// otherwise, create a category for the feature type
1013
if (delegator.findByPrimaryKey("ProductFeatureCategory", UtilMisc.toMap("productFeatureCategoryId", productFeatureTypeId)) == null) {
1014                    GenericValue productFeatureCategory = delegator.makeValue("ProductFeatureCategory", null);
1015                    productFeatureCategory.set("productFeatureCategoryId", productFeatureTypeId);
1016                    productFeatureCategory.set("description", productFeatureType.get("description"));
1017                    productFeatureCategory.create();
1018                }
1019                newProductFeature.set("productFeatureCategoryId", productFeatureTypeId);
1020                newProductFeature.create();
1021            }
1022    
1023            // check to see if the productFeatureId is already attached to the virtual or variant, if not attach them...
1024
List JavaDoc specificProductFeatureApplList = EntityUtil.filterByDate(delegator.findByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", productId,
1025                    "productFeatureApplTypeId", productFeatureApplTypeId, "productFeatureId", productFeatureId)), true);
1026            
1027            if (specificProductFeatureApplList.size() == 0) {
1028                delegator.create("ProductFeatureAppl",
1029                        UtilMisc.toMap("productId", productId,
1030                                "productFeatureId", productFeatureId,
1031                                "productFeatureApplTypeId", productFeatureApplTypeId,
1032                                "fromDate", nowTimestamp));
1033            }
1034        }
1035    }
1036
1037    public static String JavaDoc removeFeatureApplsByFeatureTypeId(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1038        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
1039        //Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
1040
//GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
1041
String JavaDoc productId = request.getParameter("productId");
1042        String JavaDoc productFeatureTypeId = request.getParameter("productFeatureTypeId");
1043
1044        try {
1045            GenericValue product = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId));
1046            // get all the variants
1047
List JavaDoc variantAssocs = product.getRelatedByAnd("MainProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_VARIANT"));
1048            List JavaDoc variants = EntityUtil.getRelated("AssocProduct", variantAssocs);
1049            Iterator JavaDoc variantIter = variants.iterator();
1050            while (variantIter.hasNext()) {
1051                GenericValue variant = (GenericValue) variantIter.next();
1052                // get the selectable features for the variant
1053
List JavaDoc productFeatureAndAppls = variant.getRelated("ProductFeatureAndAppl", UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId, "productFeatureApplTypeId", "STANDARD_FEATURE"), null);
1054                Iterator JavaDoc productFeatureAndApplIter = productFeatureAndAppls.iterator();
1055                while (productFeatureAndApplIter.hasNext()) {
1056                    GenericValue productFeatureAndAppl = (GenericValue) productFeatureAndApplIter.next();
1057                    GenericPK productFeatureApplPK = delegator.makePK("ProductFeatureAppl", null);
1058                    productFeatureApplPK.setPKFields(productFeatureAndAppl);
1059                    delegator.removeByPrimaryKey(productFeatureApplPK);
1060                }
1061            }
1062            List JavaDoc productFeatureAndAppls = product.getRelated("ProductFeatureAndAppl", UtilMisc.toMap("productFeatureTypeId", productFeatureTypeId, "productFeatureApplTypeId", "SELECTABLE_FEATURE"), null);
1063            Iterator JavaDoc productFeatureAndApplIter = productFeatureAndAppls.iterator();
1064            while (productFeatureAndApplIter.hasNext()) {
1065                GenericValue productFeatureAndAppl = (GenericValue) productFeatureAndApplIter.next();
1066                GenericPK productFeatureApplPK = delegator.makePK("ProductFeatureAppl", null);
1067                productFeatureApplPK.setPKFields(productFeatureAndAppl);
1068                delegator.removeByPrimaryKey(productFeatureApplPK);
1069            }
1070        } catch (GenericEntityException e) {
1071            String JavaDoc errMsg = "Error creating new virtual product from variant products: " + e.toString();
1072            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1073            return "error";
1074        }
1075        return "success";
1076    }
1077
1078    public static String JavaDoc removeProductFeatureAppl(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1079        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
1080        //Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
1081
//GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
1082
String JavaDoc productId = request.getParameter("productId");
1083        String JavaDoc productFeatureId = request.getParameter("productFeatureId");
1084        
1085        if (UtilValidate.isEmpty(productId) || UtilValidate.isEmpty(productFeatureId)) {
1086            String JavaDoc errMsg = "Must specify both a productId [was:" + productId + "] and a productFeatureId [was:" + productFeatureId + "] to remove the feature from the product.";
1087            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1088            return "error";
1089        }
1090
1091        try {
1092            delegator.removeByAnd("ProductFeatureAppl", UtilMisc.toMap("productFeatureId", productFeatureId, "productId", productId));
1093        } catch (GenericEntityException e) {
1094            String JavaDoc errMsg = "Error removing product feature: " + e.toString();
1095            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1096            return "error";
1097        }
1098        return "success";
1099    }
1100
1101    public static String JavaDoc addProductToCategories(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1102        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
1103        String JavaDoc productId = request.getParameter("productId");
1104        String JavaDoc fromDate = request.getParameter("fromDate");
1105        if ((fromDate == null) || (fromDate.trim().length() == 0)) {
1106            fromDate = UtilDateTime.nowTimestamp().toString();
1107        }
1108        String JavaDoc[] categoryId = request.getParameterValues("categoryId");
1109        if (categoryId != null) {
1110            for (int i = 0; i < categoryId.length; i++) {
1111                try {
1112                    List JavaDoc catMembs = delegator.findByAnd("ProductCategoryMember", UtilMisc.toMap(
1113                            "productCategoryId", categoryId[i],
1114                            "productId", productId));
1115                    catMembs = EntityUtil.filterByDate(catMembs);
1116                    if (catMembs.size() == 0) {
1117                        delegator.create("ProductCategoryMember",
1118                                UtilMisc.toMap("productCategoryId", categoryId[i], "productId", productId, "fromDate", fromDate));
1119                    }
1120                } catch (GenericEntityException e) {
1121                    String JavaDoc errMsg = "Error adding to category: " + e.toString();
1122                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
1123                    return "error";
1124                }
1125
1126            }
1127        }
1128        return "success";
1129    }
1130
1131    public static String JavaDoc updateProductCategoryMember(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1132        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
1133        String JavaDoc productId = request.getParameter("productId");
1134        String JavaDoc productCategoryId = request.getParameter("productCategoryId");
1135        String JavaDoc thruDate = request.getParameter("thruDate");
1136        if ((thruDate == null) || (thruDate.trim().length() == 0)) {
1137            thruDate = UtilDateTime.nowTimestamp().toString();
1138        }
1139        try {
1140            List JavaDoc prodCatMembs = delegator.findByAnd("ProductCategoryMember",
1141                    UtilMisc.toMap("productCategoryId", productCategoryId, "productId", productId));
1142            prodCatMembs = EntityUtil.filterByDate(prodCatMembs);
1143            if (prodCatMembs.size() > 0) {
1144                // there is one to modify
1145
GenericValue prodCatMemb = (GenericValue)prodCatMembs.get(0);
1146                prodCatMemb.setString("thruDate", thruDate);
1147                prodCatMemb.store();
1148            }
1149
1150        } catch (GenericEntityException e) {
1151            String JavaDoc errMsg = "Error adding to category: " + e.toString();
1152            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1153            return "error";
1154        }
1155        return "success";
1156    }
1157
1158    public static String JavaDoc addProductFeatures(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1159        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
1160        String JavaDoc productId = request.getParameter("productId");
1161        String JavaDoc productFeatureApplTypeId = request.getParameter("productFeatureApplTypeId");
1162        String JavaDoc fromDate = request.getParameter("fromDate");
1163        if ((fromDate == null) || (fromDate.trim().length() == 0)) {
1164            fromDate = UtilDateTime.nowTimestamp().toString();
1165        }
1166        String JavaDoc[] productFeatureIdArray = request.getParameterValues("productFeatureId");
1167        if (productFeatureIdArray != null && productFeatureIdArray.length > 0) {
1168            try {
1169                for (int i = 0; i < productFeatureIdArray.length; i++) {
1170                    if (!productFeatureIdArray[i].equals("~~any~~")) {
1171                        List JavaDoc featureAppls = delegator.findByAnd("ProductFeatureAppl",
1172                                UtilMisc.toMap("productId", productId,
1173                                        "productFeatureId", productFeatureIdArray[i],
1174                                        "productFeatureApplTypeId", productFeatureApplTypeId));
1175                        if (featureAppls.size() == 0) {
1176                            // no existing application for this
1177
delegator.create("ProductFeatureAppl",
1178                                    UtilMisc.toMap("productId", productId,
1179                                        "productFeatureId", productFeatureIdArray[i],
1180                                        "productFeatureApplTypeId", productFeatureApplTypeId,
1181                                        "fromDate", fromDate));
1182                        }
1183                    }
1184                }
1185            } catch (GenericEntityException e) {
1186                String JavaDoc errMsg = "Error adding feature: " + e.toString();
1187                request.setAttribute("_ERROR_MESSAGE_", errMsg);
1188                return "error";
1189            }
1190        }
1191        return "success";
1192    }
1193
1194    /** Simple event to set the users initial locale and currency Uom based on website product store */
1195    public static String JavaDoc setDefaultStoreSettings(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1196        GenericValue productStore = ProductStoreWorker.getProductStore(request);
1197        if (productStore != null) {
1198            String JavaDoc currencyStr = null;
1199            String JavaDoc localeStr = null;
1200
1201            HttpSession JavaDoc session = request.getSession();
1202            GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
1203            if (userLogin != null) {
1204                // user login currency
1205
currencyStr = userLogin.getString("lastCurrencyUom");
1206                // user login locale
1207
localeStr = userLogin.getString("lastLocale");
1208            }
1209
1210            // if currency is not set, the store's default currency is used
1211
if (currencyStr == null && productStore.get("defaultCurrencyUomId") != null) {
1212                currencyStr = productStore.getString("defaultCurrencyUomId");
1213            }
1214
1215            // if locale is not set, the store's default locale is used
1216
if (localeStr == null && productStore.get("defaultLocaleString") != null) {
1217                localeStr = productStore.getString("defaultLocaleString");
1218            }
1219            
1220            UtilHttp.setCurrencyUom(session, currencyStr);
1221            UtilHttp.setLocale(request, localeStr);
1222
1223        }
1224        return "success";
1225    }
1226
1227    /**
1228     * If ProductStore.requireCustomerRole == Y then the loggedin user must be associated with the store in the customer role.
1229     * This event method is called from the ProductEvents.storeCheckLogin and ProductEvents.storeLogin
1230     *
1231     * @param request
1232     * @param response
1233     * @return String with response, maybe "success" or "error" if logged in user is not associated with the ProductStore in the CUSTOMER role.
1234     */

1235    public static String JavaDoc checkStoreCustomerRole(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1236        HttpSession JavaDoc session = request.getSession();
1237        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
1238        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
1239        GenericValue productStore = ProductStoreWorker.getProductStore(request);
1240        if (productStore != null && userLogin != null) {
1241            if ("Y".equals(productStore.getString("requireCustomerRole"))) {
1242                List JavaDoc productStoreRoleList = null;
1243                try {
1244                    productStoreRoleList = delegator.findByAnd("ProductStoreRole", UtilMisc.toMap("productStoreId", productStore.get("productStoreId"),
1245                            "partyId", userLogin.get("partyId"), "roleTypeId", "CUSTOMER"));
1246                    productStoreRoleList = EntityUtil.filterByDate(productStoreRoleList, true);
1247                } catch (GenericEntityException e) {
1248                    Debug.logError(e, "Database error finding CUSTOMER ProductStoreRole records, required by the ProductStore with ID [" + productStore.getString("productStoreId") + "]", module);
1249                }
1250                if (productStoreRoleList == null || productStoreRoleList.size() == 0) {
1251                    // uh-oh, this user isn't associated...
1252
String JavaDoc errorMsg = "The " + productStore.getString("storeName") + " [" + productStore.getString("productStoreId") + "] ProductStore requires that customers be associated with it, and the logged in user is NOT associated with it in the CUSTOMER role; userLoginId=[" + userLogin.getString("userLoginId") + "], partyId=[" + userLogin.getString("partyId") + "]";
1253                    Debug.logWarning(errorMsg, module);
1254                    request.setAttribute("_ERROR_MESSAGE_", errorMsg);
1255                    session.removeAttribute("userLogin");
1256                    session.removeAttribute("autoUserLogin");
1257                    return "error";
1258                }
1259            }
1260        }
1261        return "success";
1262    }
1263
1264    public static String JavaDoc tellAFriend(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1265        HttpSession JavaDoc session = request.getSession();
1266        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
1267        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
1268        String JavaDoc emailType = "PRDS_TELL_FRIEND";
1269        String JavaDoc defaultScreenLocation = "component://ecommerce/widget/EmailProductScreens.xml#TellFriend";
1270
1271        GenericValue productStore = ProductStoreWorker.getProductStore(request);
1272        if (productStore == null) {
1273            String JavaDoc errMsg = "Could not send tell a friend email, no ProductStore found";
1274            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1275            return "error";
1276        }
1277        String JavaDoc productStoreId = productStore.getString("productStoreId");
1278        
1279        GenericValue productStoreEmail = null;
1280        try {
1281            productStoreEmail = delegator.findByPrimaryKey("ProductStoreEmailSetting",
1282                    UtilMisc.toMap("productStoreId", productStoreId, "emailType", emailType));
1283        } catch (GenericEntityException e) {
1284            String JavaDoc errMsg = "Unable to get product store email setting for tell-a-friend: " + e.toString();
1285            Debug.logError(e, errMsg, module);
1286            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1287            return "error";
1288        }
1289        if (productStoreEmail == null) {
1290            String JavaDoc errMsg = "Could not find tell a friend [" + emailType + "] email settings for the store [" + productStoreId + "]";
1291            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1292            return "error";
1293        }
1294
1295        String JavaDoc bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
1296        if (UtilValidate.isEmpty(bodyScreenLocation)) {
1297            bodyScreenLocation = defaultScreenLocation;
1298        }
1299        
1300        Map JavaDoc paramMap = UtilHttp.getParameterMap(request);
1301        paramMap.put("locale", UtilHttp.getLocale(request));
1302        paramMap.put("userLogin", session.getAttribute("userLogin"));
1303
1304        Map JavaDoc context = FastMap.newInstance();
1305        context.put("bodyScreenUri", bodyScreenLocation);
1306        context.put("bodyParameters", paramMap);
1307        context.put("sendTo", paramMap.get("sendTo"));
1308        context.put("contentType", productStoreEmail.get("contentType"));
1309        context.put("sendFrom", productStoreEmail.get("fromAddress"));
1310        context.put("sendCc", productStoreEmail.get("ccAddress"));
1311        context.put("sendBcc", productStoreEmail.get("bccAddress"));
1312        context.put("subject", productStoreEmail.getString("subject"));
1313
1314        try {
1315            dispatcher.runAsync("sendMailFromScreen", context);
1316        } catch (GenericServiceException e) {
1317            String JavaDoc errMsg = "Problem sending mail: " + e.toString();
1318            Debug.logError(e, errMsg, module);
1319            request.setAttribute("_ERROR_MESSAGE_", errMsg);
1320            return "error";
1321        }
1322        return "success";
1323    }
1324}
1325
Popular Tags