KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > product > store > ProductStoreWorker


1 /*
2  * $Id: ProductStoreWorker.java 6448 2005-12-30 09:15:30Z 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.store;
25
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.LinkedList JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Random JavaDoc;
32 import javax.servlet.ServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletRequest JavaDoc;
34 import javax.servlet.http.HttpSession JavaDoc;
35
36 import javolution.util.FastMap;
37
38 import org.ofbiz.base.util.Debug;
39 import org.ofbiz.base.util.UtilHttp;
40 import org.ofbiz.base.util.UtilMisc;
41 import org.ofbiz.base.util.UtilValidate;
42 import org.ofbiz.common.geo.GeoWorker;
43 import org.ofbiz.entity.GenericDelegator;
44 import org.ofbiz.entity.GenericEntityException;
45 import org.ofbiz.entity.GenericValue;
46 import org.ofbiz.entity.util.EntityUtil;
47 import org.ofbiz.party.contact.ContactMechWorker;
48 import org.ofbiz.product.catalog.CatalogWorker;
49 import org.ofbiz.product.config.ProductConfigWrapper;
50 import org.ofbiz.product.product.ProductWorker;
51 import org.ofbiz.service.GenericServiceException;
52 import org.ofbiz.service.LocalDispatcher;
53 import org.ofbiz.service.ServiceUtil;
54
55 /**
56  * ProductStoreWorker - Worker class for store related functionality
57  *
58  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
59  * @version $Rev: 6448 $
60  * @since 2.0
61  */

62 public class ProductStoreWorker {
63
64     public static final String JavaDoc module = ProductStoreWorker.class.getName();
65
66     public static GenericValue getProductStore(String JavaDoc productStoreId, GenericDelegator delegator) {
67         if (productStoreId == null || delegator == null) {
68             return null;
69         }
70         GenericValue productStore = null;
71         try {
72             productStore = delegator.findByPrimaryKeyCache("ProductStore", UtilMisc.toMap("productStoreId", productStoreId));
73         } catch (GenericEntityException e) {
74             Debug.logError(e, "Problem getting ProductStore entity", module);
75         }
76         return productStore;
77     }
78
79     public static GenericValue getProductStore(ServletRequest JavaDoc request) {
80         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
81         String JavaDoc productStoreId = ProductStoreWorker.getProductStoreId(request);
82         return ProductStoreWorker.getProductStore(productStoreId, delegator);
83     }
84
85     public static String JavaDoc getProductStoreId(ServletRequest JavaDoc request) {
86         HttpServletRequest JavaDoc httpRequest = (HttpServletRequest JavaDoc) request;
87         HttpSession JavaDoc session = httpRequest.getSession();
88         if (session.getAttribute("productStoreId") != null) {
89             return (String JavaDoc) session.getAttribute("productStoreId");
90         } else {
91             GenericValue webSite = CatalogWorker.getWebSite(request);
92             if (webSite != null) {
93                 String JavaDoc productStoreId = webSite.getString("productStoreId");
94                 // might be nice to do this, but not needed and has a problem with dependencies: setSessionProductStore(productStoreId, httpRequest);
95
return productStoreId;
96             }
97         }
98         return null;
99     }
100
101     public static String JavaDoc determineSingleFacilityForStore(GenericDelegator delegator, String JavaDoc productStoreId) {
102         GenericValue productStore = null;
103         try {
104             productStore = delegator.findByPrimaryKey("ProductStore", UtilMisc.toMap("productStoreId", productStoreId));
105         } catch (GenericEntityException e) {
106             Debug.logError(e, module);
107         }
108         if (productStore != null) {
109             if ("Y".equalsIgnoreCase(productStore.getString("oneInventoryFacility"))) {
110                 return productStore.getString("inventoryFacilityId");
111             }
112         }
113         return null;
114     }
115
116     public static boolean autoSaveCart(GenericDelegator delegator, String JavaDoc productStoreId) {
117         return autoSaveCart(getProductStore(productStoreId, delegator));
118     }
119
120     public static boolean autoSaveCart(GenericValue productStore) {
121         return productStore == null ? false : "Y".equalsIgnoreCase(productStore.getString("autoSaveCart"));
122     }
123
124     public static String JavaDoc getProductStorePaymentProperties(ServletRequest JavaDoc request, String JavaDoc paymentMethodTypeId, String JavaDoc paymentServiceTypeEnumId, boolean anyServiceType) {
125         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
126         String JavaDoc productStoreId = ProductStoreWorker.getProductStoreId(request);
127         return ProductStoreWorker.getProductStorePaymentProperties(delegator, productStoreId, paymentMethodTypeId, paymentServiceTypeEnumId, anyServiceType);
128     }
129
130     public static String JavaDoc getProductStorePaymentProperties(GenericDelegator delegator, String JavaDoc productStoreId, String JavaDoc paymentMethodTypeId, String JavaDoc paymentServiceTypeEnumId, boolean anyServiceType) {
131         GenericValue setting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, paymentMethodTypeId, paymentServiceTypeEnumId, anyServiceType);
132
133         String JavaDoc payProps = "payment.properties";
134         if (setting != null && setting.get("paymentPropertiesPath") != null) {
135             payProps = setting.getString("paymentPropertiesPath");
136         }
137         return payProps;
138     }
139
140     public static GenericValue getProductStorePaymentSetting(GenericDelegator delegator, String JavaDoc productStoreId, String JavaDoc paymentMethodTypeId, String JavaDoc paymentServiceTypeEnumId, boolean anyServiceType) {
141         GenericValue storePayment = null;
142         try {
143             storePayment = delegator.findByPrimaryKeyCache("ProductStorePaymentSetting", UtilMisc.toMap("productStoreId", productStoreId, "paymentMethodTypeId", paymentMethodTypeId, "paymentServiceTypeEnumId", paymentServiceTypeEnumId));
144         } catch (GenericEntityException e) {
145             Debug.logError(e, "Problems looking up store payment settings", module);
146         }
147
148         if (anyServiceType) {
149             if (storePayment == null) {
150                 try {
151                     List JavaDoc storePayments = delegator.findByAnd("ProductStorePaymentSetting", UtilMisc.toMap("productStoreId", productStoreId, "paymentMethodTypeId", paymentMethodTypeId));
152                     storePayment = EntityUtil.getFirst(storePayments);
153                 } catch (GenericEntityException e) {
154                     Debug.logError(e, "Problems looking up store payment settings", module);
155                 }
156             }
157
158             if (storePayment == null) {
159                 try {
160                     List JavaDoc storePayments = delegator.findByAnd("ProductStorePaymentSetting", UtilMisc.toMap("productStoreId", productStoreId));
161                     storePayment = EntityUtil.getFirst(storePayments);
162                 } catch (GenericEntityException e) {
163                     Debug.logError(e, "Problems looking up store payment settings", module);
164                 }
165             }
166         }
167
168         return storePayment;
169     }
170
171     public static GenericValue getProductStoreShipmentMethod(GenericDelegator delegator, String JavaDoc productStoreId,
172                                                              String JavaDoc shipmentMethodTypeId, String JavaDoc carrierPartyId, String JavaDoc carrierRoleTypeId) {
173         // check for an external service call
174
Map JavaDoc storeFields = UtilMisc.toMap("productStoreId", productStoreId, "shipmentMethodTypeId", shipmentMethodTypeId,
175                 "partyId", carrierPartyId, "roleTypeId", carrierRoleTypeId);
176
177         GenericValue storeShipMeth = null;
178         try {
179             storeShipMeth = delegator.findByPrimaryKeyCache("ProductStoreShipmentMeth", storeFields);
180         } catch (GenericEntityException e) {
181             Debug.logError(e, module);
182         }
183
184         return storeShipMeth;
185     }
186
187     public static List JavaDoc getAvailableStoreShippingMethods(GenericDelegator delegator, String JavaDoc productStoreId, GenericValue shippingAddress, List JavaDoc itemSizes, Map JavaDoc featureIdMap, double weight, double orderTotal) {
188         if (featureIdMap == null) {
189             featureIdMap = new HashMap JavaDoc();
190         }
191         List JavaDoc shippingMethods = null;
192         try {
193             shippingMethods = delegator.findByAndCache("ProductStoreShipmentMethView", UtilMisc.toMap("productStoreId", productStoreId), UtilMisc.toList("sequenceNumber"));
194         } catch (GenericEntityException e) {
195             Debug.logError(e, "Unable to get ProductStore shipping methods", module);
196             return null;
197         }
198
199         // clone the list for concurrent modification
200
List JavaDoc returnShippingMethods = new LinkedList JavaDoc(shippingMethods);
201
202         if (shippingMethods != null) {
203             Iterator JavaDoc i = shippingMethods.iterator();
204             while (i.hasNext()) {
205                 GenericValue method = (GenericValue) i.next();
206                 //Debug.logInfo("Checking Shipping Method : " + method.getString("shipmentMethodTypeId"), module);
207

208                 // test min/max weight first
209
Double JavaDoc minWeight = method.getDouble("minWeight");
210                 Double JavaDoc maxWeight = method.getDouble("maxWeight");
211                 if (minWeight != null && minWeight.doubleValue() > 0 && minWeight.doubleValue() > weight) {
212                     returnShippingMethods.remove(method);
213                     //Debug.logInfo("Removed shipping method due to not enough weight", module);
214
continue;
215                 }
216                 if (maxWeight != null && maxWeight.doubleValue() > 0 && maxWeight.doubleValue() < weight) {
217                     returnShippingMethods.remove(method);
218                     //Debug.logInfo("Removed shipping method due to too much weight", module);
219
continue;
220                 }
221
222                 // test order total
223
Double JavaDoc minTotal = method.getDouble("minTotal");
224                 Double JavaDoc maxTotal = method.getDouble("maxTotal");
225                 if (minTotal != null && minTotal.doubleValue() > 0 && minTotal.doubleValue() > orderTotal) {
226                     returnShippingMethods.remove(method);
227                     //Debug.logInfo("Removed shipping method due to not enough order total", module);
228
continue;
229                 }
230                 if (maxTotal != null && maxTotal.doubleValue() > 0 && maxTotal.doubleValue() < orderTotal) {
231                     returnShippingMethods.remove(method);
232                     //Debug.logInfo("Removed shipping method due to too much shipping total", module);
233
continue;
234                 }
235
236                 // test product sizes
237
Double JavaDoc minSize = method.getDouble("minSize");
238                 Double JavaDoc maxSize = method.getDouble("maxSize");
239                 if (minSize != null && minSize.doubleValue() > 0) {
240                     boolean allMatch = false;
241                     if (itemSizes != null) {
242                         allMatch = true;
243                         Iterator JavaDoc isi = itemSizes.iterator();
244                         while (isi.hasNext()) {
245                             Double JavaDoc size = (Double JavaDoc) isi.next();
246                             if (size.doubleValue() < minSize.doubleValue()) {
247                                 allMatch = false;
248                             }
249                         }
250                     }
251                     if (!allMatch) {
252                         returnShippingMethods.remove(method);
253                         //Debug.logInfo("Removed shipping method because not all products are less then min size", module);
254
continue;
255                     }
256                 }
257                 if (maxSize != null && maxSize.doubleValue() > 0) {
258                     boolean allMatch = false;
259                     if (itemSizes != null) {
260                         allMatch = true;
261                         Iterator JavaDoc isi = itemSizes.iterator();
262                         while (isi.hasNext()) {
263                             Double JavaDoc size = (Double JavaDoc) isi.next();
264                             if (size.doubleValue() > maxSize.doubleValue()) {
265                                 allMatch = false;
266                             }
267                         }
268                     }
269                     if (!allMatch) {
270                         returnShippingMethods.remove(method);
271                         //Debug.logInfo("Removed shipping method because one or more products were more then max size", module);
272
continue;
273                     }
274                 }
275
276                 // check USPS address
277
String JavaDoc allowUspsAddr = method.getString("allowUspsAddr");
278                 String JavaDoc requireUspsAddr = method.getString("requireUspsAddr");
279                 boolean isUspsAddress = ContactMechWorker.isUspsAddress(shippingAddress);
280                 if ("N".equals(allowUspsAddr) && isUspsAddress) {
281                     returnShippingMethods.remove(method);
282                     //Debug.logInfo("Remove shipping method due to USPS address", module);
283
continue;
284                 }
285                 if ("Y".equals(requireUspsAddr) && !isUspsAddress) {
286                     returnShippingMethods.remove(method);
287                     //Debug.logInfo("Removed shipping method due to NON-USPS address", module);
288
continue;
289                 }
290
291                 // check company address
292
String JavaDoc companyPartyId = method.getString("companyPartyId");
293                 String JavaDoc allowCompanyAddr = method.getString("allowCompanyAddr");
294                 String JavaDoc requireCompanyAddr = method.getString("requireCompanyAddr");
295                 boolean isCompanyAddress = ContactMechWorker.isCompanyAddress(shippingAddress, companyPartyId);
296                 if ("N".equals(allowCompanyAddr) && isCompanyAddress) {
297                     returnShippingMethods.remove(method);
298                     //Debug.logInfo("Removed shipping method due to Company address", module);
299
continue;
300                 }
301                 if ("Y".equals(requireCompanyAddr) && !isCompanyAddress) {
302                     returnShippingMethods.remove(method);
303                     //Debug.logInfo("Removed shipping method due to NON-Company address", module);
304
continue;
305                 }
306
307                 // check the items excluded from shipping
308
String JavaDoc includeFreeShipping = method.getString("includeNoChargeItems");
309                 if (includeFreeShipping != null && "N".equalsIgnoreCase(includeFreeShipping)) {
310                     if ((itemSizes == null || itemSizes.size() == 0) && orderTotal == 0) {
311                         returnShippingMethods.remove(method);
312                         //Debug.logInfo("Removed shipping method due to all items being exempt from shipping", module);
313
continue;
314                     }
315                 }
316
317                 // check the geos
318
String JavaDoc includeGeoId = method.getString("includeGeoId");
319                 String JavaDoc excludeGeoId = method.getString("excludeGeoId");
320                 if ((includeGeoId != null && includeGeoId.length() > 0) || (excludeGeoId != null && excludeGeoId.length() > 0)) {
321                     if (shippingAddress == null) {
322                         returnShippingMethods.remove(method);
323                         //Debug.logInfo("Removed shipping method due to empty shipping adresss (may not have been selected yet)", module);
324
continue;
325                     }
326                 }
327                 if (includeGeoId != null && includeGeoId.length() > 0) {
328                     List JavaDoc includeGeoGroup = GeoWorker.expandGeoGroup(includeGeoId, delegator);
329                     if (!GeoWorker.containsGeo(includeGeoGroup, shippingAddress.getString("countryGeoId"), delegator) &&
330                             !GeoWorker.containsGeo(includeGeoGroup, shippingAddress.getString("stateProvinceGeoId"), delegator) &&
331                             !GeoWorker.containsGeo(includeGeoGroup, shippingAddress.getString("postalCodeGeoId"), delegator)) {
332                         // not in required included geos
333
returnShippingMethods.remove(method);
334                         //Debug.logInfo("Removed shipping method due to being outside the included GEO", module);
335
continue;
336                     }
337                 }
338                 if (excludeGeoId != null && excludeGeoId.length() > 0) {
339                     List JavaDoc excludeGeoGroup = GeoWorker.expandGeoGroup(excludeGeoId, delegator);
340                     if (GeoWorker.containsGeo(excludeGeoGroup, shippingAddress.getString("countryGeoId"), delegator) ||
341                             GeoWorker.containsGeo(excludeGeoGroup, shippingAddress.getString("stateProvinceGeoId"), delegator) ||
342                             GeoWorker.containsGeo(excludeGeoGroup, shippingAddress.getString("postalCodeGeoId"), delegator)) {
343                         // in excluded geos
344
returnShippingMethods.remove(method);
345                         //Debug.logInfo("Removed shipping method due to being inside the excluded GEO", module);
346
continue;
347                     }
348                 }
349
350                 // check the features
351
String JavaDoc includeFeatures = method.getString("includeFeatureGroup");
352                 String JavaDoc excludeFeatures = method.getString("excludeFeatureGroup");
353                 if (includeFeatures != null && includeFeatures.length() > 0) {
354                     List JavaDoc includedFeatures = null;
355                     try {
356                         includedFeatures = delegator.findByAndCache("ProductFeatureGroupAppl", UtilMisc.toMap("productFeatureGroupId", includeFeatures));
357                     } catch (GenericEntityException e) {
358                         Debug.logError(e, "Unable to lookup ProductFeatureGroupAppl records for group : " + includeFeatures, module);
359                     }
360                     if (includedFeatures != null) {
361                         boolean foundOne = false;
362                         Iterator JavaDoc ifet = includedFeatures.iterator();
363                         while (ifet.hasNext()) {
364                             GenericValue appl = (GenericValue) ifet.next();
365                             if (featureIdMap.containsKey(appl.getString("productFeatureId"))) {
366                                 foundOne = true;
367                                 break;
368                             }
369                         }
370                         if (!foundOne) {
371                             returnShippingMethods.remove(method);
372                             //Debug.logInfo("Removed shipping method due to no required features found", module);
373
continue;
374                         }
375                     }
376                 }
377                 if (excludeFeatures != null && excludeFeatures.length() > 0) {
378                     List JavaDoc excludedFeatures = null;
379                     try {
380                         excludedFeatures = delegator.findByAndCache("ProductFeatureGroupAppl", UtilMisc.toMap("productFeatureGroupId", excludeFeatures));
381                     } catch (GenericEntityException e) {
382                         Debug.logError(e, "Unable to lookup ProductFeatureGroupAppl records for group : " + excludeFeatures, module);
383                     }
384                     if (excludedFeatures != null) {
385                         Iterator JavaDoc ifet = excludedFeatures.iterator();
386                         while (ifet.hasNext()) {
387                             GenericValue appl = (GenericValue) ifet.next();
388                             if (featureIdMap.containsKey(appl.getString("productFeatureId"))) {
389                                 returnShippingMethods.remove(method);
390                                 //Debug.logInfo("Removed shipping method due to an exluded feature being found : " + appl.getString("productFeatureId"), module);
391
continue;
392                             }
393                         }
394                     }
395                 }
396             }
397         }
398
399         return returnShippingMethods;
400     }
401
402     public static ProductStoreSurveyWrapper getRandomSurveyWrapper(ServletRequest JavaDoc request, String JavaDoc groupName) {
403         GenericValue productStore = getProductStore(request);
404         HttpSession JavaDoc session = ((HttpServletRequest JavaDoc)request).getSession();
405         if (productStore == null) {
406             return null;
407         }
408
409         GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
410         if (userLogin == null) {
411             userLogin = (GenericValue) session.getAttribute("autoUserLogin");
412         }
413
414         String JavaDoc partyId = userLogin != null ? userLogin.getString("partyId") : null;
415         Map JavaDoc passThruFields = UtilHttp.getParameterMap(((HttpServletRequest JavaDoc)request));
416
417         return getRandomSurveyWrapper(productStore.getDelegator(), productStore.getString("productStoreId"), groupName, partyId, passThruFields);
418     }
419
420     public static ProductStoreSurveyWrapper getRandomSurveyWrapper(GenericDelegator delegator, String JavaDoc productStoreId, String JavaDoc groupName, String JavaDoc partyId, Map JavaDoc passThruFields) {
421         List JavaDoc randomSurveys = getSurveys(delegator, productStoreId, groupName, null, "RANDOM_POLL");
422         if (!UtilValidate.isEmpty(randomSurveys)) {
423             Random JavaDoc rand = new Random JavaDoc();
424             int index = rand.nextInt(randomSurveys.size());
425             GenericValue appl = (GenericValue) randomSurveys.get(index);
426             return new ProductStoreSurveyWrapper(appl, partyId, passThruFields);
427         } else {
428             return null;
429         }
430     }
431
432     public static List JavaDoc getProductSurveys(GenericDelegator delegator, String JavaDoc productStoreId, String JavaDoc productId, String JavaDoc surveyApplTypeId) {
433         return getSurveys(delegator, productStoreId, null, productId, surveyApplTypeId);
434     }
435
436     public static List JavaDoc getSurveys(GenericDelegator delegator, String JavaDoc productStoreId, String JavaDoc groupName, String JavaDoc productId, String JavaDoc surveyApplTypeId) {
437         List JavaDoc surveys = new LinkedList JavaDoc();
438         List JavaDoc storeSurveys = null;
439         try {
440             storeSurveys = delegator.findByAndCache("ProductStoreSurveyAppl", UtilMisc.toMap("productStoreId", productStoreId, "surveyApplTypeId", surveyApplTypeId), UtilMisc.toList("sequenceNum"));
441         } catch (GenericEntityException e) {
442             Debug.logError(e, "Unable to get ProductStoreSurveyAppl for store : " + productStoreId, module);
443             return surveys;
444         }
445
446         // limit by date
447
storeSurveys = EntityUtil.filterByDate(storeSurveys);
448
449         // limit based on group name
450
if (!UtilValidate.isEmpty(groupName)) {
451             storeSurveys = EntityUtil.filterByAnd(storeSurveys, UtilMisc.toMap("groupName", groupName));
452         }
453
454         // limit by product
455
if (!UtilValidate.isEmpty(productId) && !UtilValidate.isEmpty(storeSurveys)) {
456             Iterator JavaDoc ssi = storeSurveys.iterator();
457             while (ssi.hasNext()) {
458                 GenericValue surveyAppl = (GenericValue) ssi.next();
459                 GenericValue product = null;
460                 String JavaDoc virtualProductId = null;
461
462                 // if the item is a variant, get its virtual productId
463
try {
464                     product = delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", productId));
465                     if ((product != null) && ("Y".equals(product.get("isVariant")))) {
466                         virtualProductId = ProductWorker.getVariantVirtualId(product);
467                     }
468                 } catch (GenericEntityException e) {
469                     Debug.logError(e, "Problem finding product from productId " + productId, module);
470                 }
471
472                 // use survey if productId or virtualProductId of the variant product is in the ProductStoreSurveyAppl
473
if (surveyAppl.get("productId") != null) {
474                     if (surveyAppl.get("productId").equals(productId)) {
475                         surveys.add(surveyAppl);
476                     } else if ((virtualProductId != null) && (surveyAppl.getString("productId").equals(virtualProductId))) {
477                         surveys.add(surveyAppl);
478                     }
479                 } else if (surveyAppl.get("productCategoryId") != null) {
480                     List JavaDoc categoryMembers = null;
481                     try {
482                         categoryMembers = delegator.findByAnd("ProductCategoryMember", UtilMisc.toMap("productCategoryId", surveyAppl.get("productCategoryId")));
483                     } catch (GenericEntityException e) {
484                         Debug.logError(e, "Unable to get ProductCategoryMemebr records for survey application : " + surveyAppl, module);
485                     }
486                     if (categoryMembers != null) {
487                         Iterator JavaDoc cmi = categoryMembers.iterator();
488                         while (cmi.hasNext()) {
489                             GenericValue member = (GenericValue) cmi.next();
490                             if (productId != null && productId.equals(member.getString("productId"))) {
491                                 surveys.add(surveyAppl);
492                                 break;
493                             } else if ((virtualProductId != null) && (virtualProductId.equals(member.getString("productId")))) { // similarly, check if virtual productId is in category
494
surveys.add(surveyAppl);
495                                 break;
496                             }
497                         }
498                     }
499                 }
500             }
501         } else if (storeSurveys != null) {
502             surveys.addAll(storeSurveys);
503         }
504
505         return surveys;
506     }
507
508     /** Returns the number of responses for this survey by party */
509     public static int checkSurveyResponse(HttpServletRequest JavaDoc request, String JavaDoc surveyId) {
510         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
511         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
512         String JavaDoc productStoreId = getProductStoreId(request);
513         if (userLogin == null) {
514             return -1;
515         }
516
517         return checkSurveyResponse(delegator, userLogin.getString("partyId"), productStoreId, surveyId);
518     }
519
520     /** Returns the number of responses for this survey by party */
521     public static int checkSurveyResponse(GenericDelegator delegator, String JavaDoc partyId, String JavaDoc productStoreId, String JavaDoc surveyId) {
522         if (delegator == null || partyId == null || productStoreId == null) {
523             return -1;
524         }
525
526         List JavaDoc surveyResponse = null;
527         try {
528             surveyResponse = delegator.findByAnd("SurveyResponse", UtilMisc.toMap("surveyId", surveyId, "partyId", partyId));
529         } catch (GenericEntityException e) {
530             Debug.logError(e, module);
531             return -1;
532         }
533
534         if (surveyResponse == null || surveyResponse.size() == 0) {
535             return 0;
536         } else {
537             return surveyResponse.size();
538         }
539     }
540
541     public static boolean isStoreInventoryRequired(ServletRequest JavaDoc request, GenericValue product) {
542         return isStoreInventoryRequiredAndAvailable(request, product, null, Boolean.TRUE, null);
543     }
544
545     public static boolean isStoreInventoryAvailable(ServletRequest JavaDoc request, GenericValue product, Double JavaDoc quantity) {
546         return isStoreInventoryRequiredAndAvailable(request, product, quantity, null, Boolean.TRUE);
547     }
548
549     /**
550      * This method is used in the showcart pages to determine whether or not to show the inventory message and
551      * in the productdetail pages to determine whether or not to show the item as out of stock.
552      *
553      * @param request ServletRequest (or HttpServletRequest of course)
554      * @param product GenericValue representing the product in question
555      * @param quantity Quantity desired.
556      * @param wantRequired If true then inventory required must be true for the result to be true, if false must be false; if null don't care
557      * @param wantAvailable If true then inventory avilable must be true for the result to be true, if false must be false; if null don't care
558      */

559     public static boolean isStoreInventoryRequiredAndAvailable(ServletRequest JavaDoc request, GenericValue product, Double JavaDoc quantity, Boolean JavaDoc wantRequired, Boolean JavaDoc wantAvailable) {
560         GenericValue productStore = getProductStore(request);
561         if (productStore == null) {
562             Debug.logWarning("No ProductStore found, return false for inventory check", module);
563             return false;
564         }
565         if (product == null) {
566             Debug.logWarning("No Product passed, return false for inventory check", module);
567             return false;
568         }
569
570         if (quantity == null) quantity = new Double JavaDoc(1);
571
572         String JavaDoc productStoreId = productStore.getString("productStoreId");
573         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
574
575         try {
576             Boolean JavaDoc requiredOkay = null;
577             if (wantRequired != null) {
578                 Map JavaDoc invReqResult = dispatcher.runSync("isStoreInventoryRequired", UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"), "product", product, "productStore", productStore));
579                 if (ServiceUtil.isError(invReqResult)) {
580                     Debug.logError("Error calling isStoreInventoryRequired service, result is: " + invReqResult, module);
581                     return false;
582                 }
583                 requiredOkay = new Boolean JavaDoc(wantRequired.booleanValue() == "Y".equals((String JavaDoc) invReqResult.get("requireInventory")));
584             }
585
586             Boolean JavaDoc availableOkay = null;
587             if (wantAvailable != null) {
588                 Map JavaDoc invAvailResult = dispatcher.runSync("isStoreInventoryAvailable", UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"), "product", product, "productStore", productStore, "quantity", quantity));
589                 if (ServiceUtil.isError(invAvailResult)) {
590                     Debug.logError("Error calling isStoreInventoryAvailable service, result is: " + invAvailResult, module);
591                     return false;
592                 }
593                 availableOkay = new Boolean JavaDoc(wantAvailable.booleanValue() == "Y".equals((String JavaDoc) invAvailResult.get("available")));
594             }
595
596             if ((requiredOkay == null || requiredOkay.booleanValue()) && (availableOkay == null || availableOkay.booleanValue())) {
597                 return true;
598             } else {
599                 return false;
600             }
601         } catch (GenericServiceException e) {
602             String JavaDoc errMsg = "Fatal error calling inventory checking services: " + e.toString();
603             Debug.logError(e, errMsg, module);
604             return false;
605         }
606     }
607
608     public static boolean isStoreInventoryAvailable(ServletRequest JavaDoc request, ProductConfigWrapper productConfig, double quantity) {
609         GenericValue productStore = getProductStore(request);
610
611         if (productStore == null) {
612             Debug.logWarning("No ProductStore found, return false for inventory check", module);
613             return false;
614         }
615
616         String JavaDoc productStoreId = productStore.getString("productStoreId");
617         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
618         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
619         return isStoreInventoryAvailable(productStoreId, productConfig, quantity, delegator, dispatcher);
620     }
621
622     /** check inventory availability for the given catalog, product, quantity, etc */
623     public static boolean isStoreInventoryAvailable(String JavaDoc productStoreId, ProductConfigWrapper productConfig, double quantity, GenericDelegator delegator, LocalDispatcher dispatcher) {
624         GenericValue productStore = getProductStore(productStoreId, delegator);
625
626         if (productStore == null) {
627             Debug.logWarning("No ProductStore found with id " + productStoreId + ", returning false for inventory available check", module);
628             return false;
629         }
630
631         // if prodCatalog is set to not check inventory break here
632
if ("N".equals(productStore.getString("checkInventory"))) {
633             // note: if not set, defaults to yes, check inventory
634
if (Debug.verboseOn()) Debug.logVerbose("ProductStore with id " + productStoreId + ", is set to NOT check inventory, returning true for inventory available check", module);
635             return true;
636         }
637         boolean isInventoryAvailable = false;
638
639         if ("Y".equals(productStore.getString("oneInventoryFacility"))) {
640             String JavaDoc inventoryFacilityId = productStore.getString("inventoryFacilityId");
641
642             if (UtilValidate.isEmpty(inventoryFacilityId)) {
643                 Debug.logWarning("ProductStore with id " + productStoreId + " has Y for oneInventoryFacility but inventoryFacilityId is empty, returning false for inventory check", module);
644                 return false;
645             }
646
647             try {
648                 isInventoryAvailable = ProductWorker.isProductInventoryAvailableByFacility(productConfig, inventoryFacilityId, quantity, dispatcher);
649             } catch (GenericServiceException e) {
650                 Debug.logWarning(e, "Error invoking isProductInventoryAvailableByFacility in isCatalogInventoryAvailable", module);
651                 return false;
652             }
653             return isInventoryAvailable;
654
655         } else {
656             GenericValue product = productConfig.getProduct();;
657             List JavaDoc productFacilities = null;
658
659             try {
660                 productFacilities = delegator.getRelatedCache("ProductFacility", product);
661             } catch (GenericEntityException e) {
662                 Debug.logWarning(e, "Error invoking getRelatedCache in isCatalogInventoryAvailable", module);
663                 return false;
664             }
665
666             if (productFacilities != null && productFacilities.size() > 0) {
667                 Iterator JavaDoc pfIter = productFacilities.iterator();
668
669                 while (pfIter.hasNext()) {
670                     try {
671                         GenericValue pfValue = (GenericValue) pfIter.next();
672
673                         isInventoryAvailable = ProductWorker.isProductInventoryAvailableByFacility(productConfig, pfValue.getString("facilityId"), quantity, dispatcher);
674                         if (isInventoryAvailable == true) {
675                             return isInventoryAvailable;
676                         }
677                     } catch (GenericServiceException e) {
678                         Debug.logWarning(e, "Error invoking isProductInventoryAvailableByFacility in isCatalogInventoryAvailable", module);
679                         return false;
680                     }
681                 }
682             }
683             return false;
684         }
685     }
686
687     protected static Map JavaDoc defaultProductStoreEmailScreenLocation = FastMap.newInstance();
688
689     static {
690         defaultProductStoreEmailScreenLocation.put("PRDS_ODR_CONFIRM", "component://ecommerce/widget/EmailOrderScreens.xml#OrderConfirmNotice");
691         defaultProductStoreEmailScreenLocation.put("PRDS_ODR_COMPLETE", "component://ecommerce/widget/EmailOrderScreens.xml#OrderCompleteNotice");
692         defaultProductStoreEmailScreenLocation.put("PRDS_ODR_BACKORDER", "component://ecommerce/widget/EmailOrderScreens.xml#BackorderNotice");
693         defaultProductStoreEmailScreenLocation.put("PRDS_ODR_CHANGE", "component://ecommerce/widget/EmailOrderScreens.xml#OrderChangeNotice");
694
695         defaultProductStoreEmailScreenLocation.put("PRDS_ODR_PAYRETRY", "component://ecommerce/widget/EmailOrderScreens.xml#PaymentRetryNotice");
696
697         defaultProductStoreEmailScreenLocation.put("PRDS_RTN_ACCEPT", "component://ecommerce/widget/EmailReturnScreens.xml#ReturnAccept");
698         defaultProductStoreEmailScreenLocation.put("PRDS_RTN_COMPLETE", "component://ecommerce/widget/EmailReturnScreens.xml#ReturnComplete");
699         defaultProductStoreEmailScreenLocation.put("PRDS_RTN_CANCEL", "component://ecommerce/widget/EmailReturnScreens.xml#ReturnCancel");
700
701         defaultProductStoreEmailScreenLocation.put("PRDS_GC_PURCHASE", "component://ecommerce/widget/EmailGiftCardScreens.xml#GiftCardPurchase");
702         defaultProductStoreEmailScreenLocation.put("PRDS_GC_RELOAD", "component://ecommerce/widget/EmailGiftCardScreens.xml#GiftCardReload");
703     }
704
705     public static String JavaDoc getDefaultProductStoreEmailScreenLocation(String JavaDoc emailType) {
706         return (String JavaDoc) defaultProductStoreEmailScreenLocation.get(emailType);
707     }
708 }
709
Popular Tags