KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > cart > CartModule


1 /*
2  * Created on Mar 2, 2004
3  */

4 package com.openedit.modules.cart;
5
6 import java.util.Iterator JavaDoc;
7 import java.util.List JavaDoc;
8
9 import org.apache.commons.logging.Log;
10 import org.apache.commons.logging.LogFactory;
11 import org.openedit.money.Fraction;
12
13 import com.openedit.OpenEditException;
14 import com.openedit.WebPageRequest;
15 import com.openedit.modules.search.LuceneHitTracker;
16 import com.openedit.modules.store.BaseStoreModule;
17 import com.openedit.page.Page;
18 import com.openedit.store.Cart;
19 import com.openedit.store.CartItem;
20 import com.openedit.store.Category;
21 import com.openedit.store.CreditPaymentMethod;
22 import com.openedit.store.CustomerArchive;
23 import com.openedit.store.InventoryItem;
24 import com.openedit.store.Order;
25 import com.openedit.store.OrderArchive;
26 import com.openedit.store.OrderState;
27 import com.openedit.store.Product;
28 import com.openedit.store.ProductAdder;
29 import com.openedit.store.PurchaseOrderMethod;
30 import com.openedit.store.ShippingMethod;
31 import com.openedit.store.Store;
32 import com.openedit.store.customer.Address;
33 import com.openedit.store.customer.Customer;
34 import com.openedit.users.User;
35 import com.openedit.util.PathUtilities;
36 import com.openedit.util.URLUtilities;
37 import com.openedit.web.Crumb;
38
39 /**
40  * @author cburkey
41  *
42  */

43 public class CartModule extends BaseStoreModule
44 {
45     protected List JavaDoc fieldListConverters;
46
47     private static final Log log = LogFactory.getLog(CartModule.class);
48
49     public CartModule()
50     {
51
52     }
53
54     public void findCustomer(WebPageRequest inPageRequest) throws Exception JavaDoc
55     {
56         //get what is filled in
57
//Are they creating a user or searching for one?
58
//String firstName = inPageRequest.getRequestParameter("firstName");
59
String JavaDoc lastname = inPageRequest.getRequestParameter("lastName");
60         String JavaDoc phone = inPageRequest.getRequestParameter("phone1");
61         if (lastname != null && lastname.length() > 0)
62         {
63             CustomerArchive archive = getStore(inPageRequest).getCustomerArchive();
64             List JavaDoc hits = archive.findCustomer(User.LAST_NAME_PROPERTY, lastname, Customer.PHONE1,
65                 phone);
66             inPageRequest.putPageValue("users", hits);
67         }
68     }
69
70     public void loadCatalog(WebPageRequest inPageRequest) throws OpenEditException
71     {
72         String JavaDoc id = inPageRequest.getRequestParameter(CATEGORYID);
73         if (id == null)
74         {
75             id = inPageRequest.getCurrentAction().getChildValue("catalogid");
76         }
77         if (id == null)
78         {
79             Page page = inPageRequest.getPage();
80             id = page.get(CATEGORYID);
81         }
82         if (id == null)
83         {
84             Page page = inPageRequest.getContentPage();
85             id = page.get(CATEGORYID);
86         }
87
88         if (id == null)
89         {
90             //get it from the path name
91
String JavaDoc path = inPageRequest.getPath();
92             id = PathUtilities.extractPageName(path);
93         }
94         Store store = getStore(inPageRequest);
95         Category cat = store.getCatalog(id);
96         if (cat == null)
97         {
98             log.error("No Such catalog: " + id);
99             inPageRequest.putPageValue("catalog", "No such catalog");
100         }
101         else
102         {
103             Crumb crumb = store.buildCrumb(cat);
104             inPageRequest.putPageValue("crumb", crumb);
105             inPageRequest.putPageValue("catalog", cat); //@deprecated
106
inPageRequest.putPageValue("category", cat);
107             getCart(inPageRequest).setLastVisitedCatalog(cat);
108         }
109     }
110
111     public void loadProductDetails(WebPageRequest inPageRequest) throws OpenEditException
112     {
113         Page page = inPageRequest.getContentPage();
114         if (page.isBinary()) //this action is called for every image. Yuck.
115
{
116             return;
117         }
118         Store store = getStore(inPageRequest);
119         String JavaDoc id = inPageRequest.getRequestParameter("productid");
120         if (id == null)
121         {
122             //get it from the path?
123
String JavaDoc path = page.getPath();
124             id = PathUtilities.extractPageName(path);
125         }
126         Product item = store.getProduct(id);
127
128         if (item == null)
129         {
130             log.info("Product:" + id + " is null, cannot put page value");
131             return;
132         }
133
134         inPageRequest.putPageValue("product", item);
135         Category cat = item.getDefaultCatalog();
136         if (cat != null)
137         {
138             Crumb crumb = store.buildCrumb(cat);
139             inPageRequest.putPageValue("crumb", crumb);
140         }
141     }
142
143     public void clearCart(WebPageRequest inPageRequest) throws Exception JavaDoc
144     {
145         Cart cart = (Cart) inPageRequest.getSessionValue("cart");
146         if (cart != null)
147         {
148             cart.removeAllItems();
149         }
150     }
151
152     /**
153      * @deprecated used on aniara
154      * TODO: Replace with cart properties
155      * @param inReq
156      * @throws Exception
157      */

158     public void setRegion(WebPageRequest inReq) throws Exception JavaDoc
159     {
160         Cart cart = getCart(inReq);
161         String JavaDoc region = inReq.getRequestParameter("region");
162         cart.setRegion(region);
163     }
164
165     public void updateCart(WebPageRequest inPageRequest) throws Exception JavaDoc
166     {
167         Cart cart = getCart(inPageRequest);
168         getProductAdder().updateCart(inPageRequest, cart);
169     }
170
171     /**
172      * @param inPageRequest
173      */

174
175     // Is this used anywhere?
176
public void removeProduct(WebPageRequest inPageRequest) throws Exception JavaDoc
177     {
178         String JavaDoc productId = inPageRequest.getRequestParameter("productid");
179         if (productId != null)
180         {
181             Store store = getStore(inPageRequest);
182             Product product = store.getProduct(productId);
183             Cart cart = getCart(inPageRequest);
184             cart.removeProduct(product);
185         }
186     }
187
188     protected ProductAdder getProductAdder()
189     {
190         ProductAdder adder = (ProductAdder) getBeanFactory().getBean("ProductAdder");
191         return adder;
192     }
193
194 /* public void addItem(WebPageRequest inPageRequest) throws Exception
195     {
196         Cart cart = getCart(inPageRequest);
197         getProductAdder().addItem(inPageRequest, cart);
198     }
199 */

200
201     public void addCoupon(WebPageRequest inReq) throws Exception JavaDoc
202     {
203         Cart cart = getCart(inReq);
204         getProductAdder().addCoupon(inReq, cart);
205     }
206     public Cart getCart(WebPageRequest inPageRequest) throws OpenEditException
207     {
208         Cart cart = (Cart) inPageRequest.getSessionValue("cart");
209         if (cart == null)
210         {
211             cart = new Cart(getStore(inPageRequest));
212             inPageRequest.putSessionValue("cart", cart);
213         }
214         return cart;
215     }
216
217     public void createCustomer(WebPageRequest inPageRequest) throws Exception JavaDoc
218     {
219         Store store = getStore(inPageRequest);
220         Cart cart = getCart(inPageRequest);
221         String JavaDoc userName = inPageRequest.getRequestParameter("userName");
222         String JavaDoc passWord = inPageRequest.getRequestParameter("password");
223         if( cart.getCustomer() != null)
224         {
225             if( userName == null)
226             {
227                 return;
228             }
229             if( cart.getCustomer().getUserName().equals(userName))
230             {
231                 log.info("Already created " + userName);
232                 return;
233             }
234         }
235         
236         Customer customer = null;
237         if (userName != null && passWord != null)
238         {
239             User user = getUserManager().getUser(userName);
240             if (getUserManager().authenticate(user, passWord))
241             {
242                 customer = store.getCustomerArchive().getCustomer(userName);
243             }
244         }
245         if( customer == null)
246         {
247             if( !store.getAllowDuplicateAccounts() )
248             {
249                 //create a new customer
250
String JavaDoc email = inPageRequest.getRequestParameter("email");
251                 email = email.toLowerCase().trim();
252                 User user = getUserManager().getUserByEmail(email);
253                 if (user != null )
254                 {
255                     //TODO: Replace with a stream API
256
inPageRequest.forward( store.getStoreHome() + "/customers/duplicate.html");
257                     return;
258                 }
259             }
260             customer = store.getCustomerArchive().createNewCustomer(null, null);
261             log.info("Created new Customer");
262         }
263         cart.setCustomer(customer);
264
265         inPageRequest.putPageValue("customer", customer);
266     }
267     public void updateCustomer(WebPageRequest inPageRequest) throws Exception JavaDoc
268     {
269         Cart cart = getCart(inPageRequest);
270         Customer customer = cart.getCustomer();
271
272         //Page one stuff
273
String JavaDoc email = inPageRequest.getRequestParameter("email");
274         if( email != null)
275         {
276             customer.setEmail(email);
277             String JavaDoc firstName = inPageRequest.getRequestParameter("firstName");
278             customer.setFirstName(firstName);
279             String JavaDoc lastName = inPageRequest.getRequestParameter("lastName");
280             customer.setLastName(lastName);
281             String JavaDoc company = inPageRequest.getRequestParameter("company");
282             if (company != null)
283             {
284                 customer.setCompany(company);
285             }
286             else
287             {
288                 customer.setCompany(customer.getFirstName() + " " + customer.getLastName());
289             }
290             customer.setAllowEmail(Boolean.valueOf(inPageRequest.getRequestParameter("allowEmail"))
291                 .booleanValue());
292             customer.setPhone1(inPageRequest.getRequestParameter("phone1"));
293             customer.setFax(inPageRequest.getRequestParameter("fax"));
294             //TODO: Remove these, replace with list that the usermanager uses to display data
295
customer.setUserField1(inPageRequest.getRequestParameter("userfield1"));
296             customer.setUserField2(inPageRequest.getRequestParameter("userfield2"));
297             if (customer.getReferenceNumber() == null)
298             {
299                 customer.setReferenceNumber(inPageRequest.getRequestParameter("referenceNumber"));
300             }
301         }
302         
303         if (inPageRequest.getRequestParameter("billingaddress1") != null)
304         {
305             populateCustomerAddress(inPageRequest, "billing", customer.getBillingAddress());
306         }
307         if (inPageRequest.getRequestParameter("shippingaddress1") != null)
308         {
309             populateCustomerAddress(inPageRequest, "shipping", customer.getShippingAddress());
310         }
311
312         Fraction taxrate = cart.getStore().getTaxRateFor(customer.getShippingAddress().getState());
313         customer.setTaxRate(taxrate);
314         if (inPageRequest.getRequestParameter("taxExemptId") != null)
315         {
316             customer.setTaxExemptId(inPageRequest.getRequestParameter("taxExemptId"));
317         }
318
319         log.debug("Setting cart customer to " + customer);
320         cart.setCustomer(customer);
321         cart.getStore().getCustomerArchive().saveCustomer(customer);
322         inPageRequest.putPageValue("customer", customer);
323     }
324
325     protected void populateCustomerAddress(WebPageRequest inPageRequest, String JavaDoc inPrefix,
326         Address inAddress)
327     {
328         inAddress.setAddress1(inPageRequest.getRequestParameter(inPrefix + "address1"));
329         inAddress.setAddress2(inPageRequest.getRequestParameter(inPrefix + "address2"));
330         inAddress.setCity(inPageRequest.getRequestParameter(inPrefix + "city"));
331         String JavaDoc state = inPageRequest.getRequestParameter(inPrefix + "state");
332         if (state != null)
333         {
334             state = state.toUpperCase();
335         }
336         inAddress.setState(state);
337         inAddress.setCountry(inPageRequest.getRequestParameter(inPrefix + "country"));
338         inAddress.setZipCode(inPageRequest.getRequestParameter(inPrefix + "zipCode"));
339     }
340
341     public void loadCustomer(WebPageRequest inPageRequest) throws Exception JavaDoc
342     {
343         Cart cart = getCart(inPageRequest);
344         String JavaDoc customerId = inPageRequest.getRequestParameter("customerId");
345         if (customerId == null)
346         {
347             User user = (User) inPageRequest.getPageValue("user");
348             if (user != null)
349             {
350                 customerId = user.getUserName();
351             }
352         }
353
354         if (customerId != null)
355         {
356             Store store = getStore(inPageRequest);
357
358             Customer customer = store.getCustomerArchive().getCustomer(customerId);
359             if (customer == null)
360             {
361                 //set error
362
inPageRequest.putPageValue("errorMessage", "No such customer");
363             }
364             else
365             {
366                 cart.setCustomer(customer);
367             }
368         }
369         if (cart.getCustomer() != null)
370         {
371             inPageRequest.putPageValue("customer", cart.getCustomer());
372         }
373     }
374
375     public void saveCreditPaymentMethodData(WebPageRequest inPageRequest) throws OpenEditException
376     {
377         Cart cart = getCart(inPageRequest);
378
379         //check for billing info
380
if (inPageRequest.getRequestParameter("billingaddress1") != null)
381         {
382             populateCustomerAddress(inPageRequest, "billing", cart.getCustomer()
383                 .getBillingAddress());
384         }
385
386         CreditPaymentMethod method = null;
387         // PO
388
String JavaDoc purchaseorder = inPageRequest.getRequestParameter("purchaseorder");
389         if (purchaseorder != null && purchaseorder.trim().length() > 0)
390         {
391             PurchaseOrderMethod po = new PurchaseOrderMethod();
392             po.setPoNumber(purchaseorder);
393             method = po;
394         }
395         else
396         {
397             method = new CreditPaymentMethod();
398         }
399         // Card type
400
String JavaDoc cardType = inPageRequest.getRequestParameter("cardType");
401         if (cardType != null)
402         {
403             method.setCreditCardType(getStore(inPageRequest).getCreditCardType(cardType));
404         }
405         // Card number
406
String JavaDoc cardNumber = inPageRequest.getRequestParameter("cardNumber");
407         method.setCardNumber(cardNumber);
408         // Expiration month
409
String JavaDoc expirationMonth = inPageRequest.getRequestParameter("expirationMonth");
410         if (expirationMonth != null && !expirationMonth.trim().equals(""))
411         {
412             method.setExpirationMonth(Integer.valueOf(expirationMonth).intValue());
413         }
414         // Experation year
415
String JavaDoc expirationYear = inPageRequest.getRequestParameter("expirationYear");
416         if (expirationYear != null && !expirationYear.trim().equals(""))
417         {
418             method.setExpirationYear(Integer.valueOf(expirationYear).intValue());
419         }
420
421         String JavaDoc note = inPageRequest.getRequestParameter("ordernote");
422         if (note != null)
423         {
424             method.setNote(note);
425         }
426
427         String JavaDoc bill = inPageRequest.getRequestParameter("billmelater");
428         boolean billMeLater = (bill != null && bill.equalsIgnoreCase("true"));
429         method.setBillMeLater(billMeLater);
430
431         // Save payment method
432
cart.getCustomer().setPaymentMethod(method);
433     }
434
435     public void autoSelectShipping(WebPageRequest inPageRequest) throws OpenEditException
436     {
437         Cart cart = getCart(inPageRequest);
438         if (!cart.hasZeroSubTotal())
439         {
440             List JavaDoc availableMethods = cart.getAvailableShippingMethods();
441             Store store = getStore(inPageRequest);
442             if (availableMethods.size() == 1)
443             {
444                 cart.setShippingMethod((ShippingMethod) availableMethods.get(0));
445                 inPageRequest.redirect( cart.getStore().getStoreHome() + "/checkout2.html");
446             }
447             else if (availableMethods.size() > 1 && store.isAssignShippingMethod())
448             {
449                 cart.setShippingMethod((ShippingMethod) availableMethods.get(0));
450                 inPageRequest.redirect(cart.getStore().getStoreHome() + "/checkout2.html");
451             }
452         }
453     }
454
455     public void saveShippingMethod(WebPageRequest inPageRequest) throws OpenEditException
456     {
457         String JavaDoc method = inPageRequest.getRequestParameter("shippingmethod");
458         Cart cart = getCart(inPageRequest);
459         Store store = getStore(inPageRequest);
460         if (method != null)
461         {
462             ShippingMethod smethod = store.findShippingMethod(method);
463             cart.setShippingMethod(smethod);
464         }
465         else if (cart.getShippingMethod() == null && store.isAssignShippingMethod())
466         {
467             List JavaDoc availableMethods = cart.getAvailableShippingMethods();
468             if (availableMethods.size() > 0)
469             {
470                 cart.setShippingMethod((ShippingMethod) availableMethods.get(0));
471             }
472         }
473     }
474
475     public void saveProduct(WebPageRequest inPageRequest) throws Exception JavaDoc
476     {
477         //TODO: map back to the item in question, add security
478
loadProductDetails(inPageRequest);
479         Product product = (Product) inPageRequest.getPageValue("product");
480         String JavaDoc newname = inPageRequest.getRequestParameter("product.name");
481         product.setName(newname);
482
483         //Reset catalogs
484
product.clearUserCatalogs();
485         Store store = getStore(inPageRequest);
486         //add back any new user selected projects that are now selected
487
for (Iterator JavaDoc iter = store.listUserSelectedCatalogs().iterator(); iter.hasNext();)
488         {
489             Category cat = (Category) iter.next();
490             String JavaDoc value = inPageRequest.getRequestParameter("catalog." + cat.getId());
491             if (value != null && !value.equals("false")) //might have an X in it
492
{
493                 product.addCatalog(cat);
494             }
495         }
496         store.saveProduct(product);
497     }
498
499     public Order processOrder(WebPageRequest inPageRequest) throws Exception JavaDoc
500     {
501         Store store = getStore(inPageRequest);
502         Cart cart = getCart(inPageRequest);
503         Order order = store.getOrderGenerator().createNewOrder(store, cart);
504         OrderState orderState = order.getOrderState();
505         cart.setCurrentOrder(order);
506
507         if (cart.isEmpty())
508         {
509             orderState.setOk(false);
510             orderState.setDescription("Error: Cart is empty.<br><br>");
511             return order;
512         }
513
514         // Assign default shipping method if one has not been assigned
515
if (cart.getShippingMethod() == null)
516         {
517             List JavaDoc shippingMethods = cart.getAvailableShippingMethods();
518             if (shippingMethods.size() > 0)
519             {
520                 cart.setShippingMethod((ShippingMethod) shippingMethods.get(0));
521             }
522         }
523         // Export order
524
store.exportNewOrder(inPageRequest, order);
525
526         if (order.getOrderState().isOk())
527         {
528             // Remove items from stock
529
for (Iterator JavaDoc iter = cart.getItemIterator(); iter.hasNext();)
530             {
531                 CartItem cartItem = (CartItem) iter.next();
532                 InventoryItem inventoryItem = cartItem.getInventoryItem();
533                 if (inventoryItem != null)
534                 {
535                     inventoryItem.decreaseQuantityInStock(cartItem.getQuantity());
536                 }
537             }
538             
539             // Save updated product inventory values to disk
540
for (Iterator JavaDoc iter = cart.getItemIterator(); iter.hasNext();)
541             {
542                 CartItem cartItem = (CartItem) iter.next();
543                 Product product = cartItem.getProduct();
544                 store.getProductArchive().saveProduct(product);
545             }
546
547             // Order succeeded - remove cart
548
cart.removeAllItems();
549         }
550
551         inPageRequest.putPageValue("order", order);
552         inPageRequest.putPageValue("cart", cart);
553         inPageRequest.putPageValue("store", store);
554         return order;
555     }
556
557     public void archiveOrders(WebPageRequest inPageRequest) throws Exception JavaDoc
558     {
559         Store store = getStore(inPageRequest);
560         OrderArchive orderArchive = store.getOrderArchive();
561         orderArchive.archiveOrderData(store);
562     }
563
564     public void convertData(WebPageRequest inPageRequest) throws Exception JavaDoc
565     {
566
567         //loop over all the converters and let them convert what they find
568
//clear out the reader so its all reloaded
569
Store store = getStore(inPageRequest);
570
571         List JavaDoc errorlog = store.convertCatalog();
572         if (inPageRequest != null)
573         {
574             inPageRequest.removeSessionValue("store");
575             inPageRequest.putPageValue("exception-report", errorlog);
576         }
577     }
578
579     /**
580      *
581      */

582     public void reIndexStore(WebPageRequest inPageRequest) throws Exception JavaDoc
583     {
584         Store store = getStore(inPageRequest);
585
586         store.reindexAll();
587         store.getCatalogArchive().reloadCatalogs();
588     }
589
590     /**
591      * Only searches if the query does not match the page they want
592      * @param inPageRequest
593      * @throws Exception
594      */

595     public void loadPageOfSearch(WebPageRequest inPageRequest) throws Exception JavaDoc
596     {
597         String JavaDoc page = inPageRequest.getRequestParameter("page");
598     
599         if (page != null)
600         {
601             //String q = inPageRequest.getRequestParameter( "query" );
602
LuceneHitTracker tracker = (LuceneHitTracker) inPageRequest.getSessionValue("hits");
603             if (tracker != null)
604             {
605                 int jumpToPage = Integer.parseInt(page);
606                 if (jumpToPage <= tracker.getTotalPages() && jumpToPage > 0)
607                 {
608                     tracker.setPage(jumpToPage);
609                 }
610                 else
611                 {
612                     tracker.setPage(1);
613                 }
614 // Store store = getStore(inPageRequest);
615
// Crumb crumb = new Crumb();
616
// crumb.setText("search " + URLUtilities.xmlEscape(tracker.getUserQuery()));
617
// crumb.setLink(store.getStoreHome() + "/search/results.html?page=1");
618
// inPageRequest.putPageValue("crumb", crumb);
619

620             }
621             else
622             {
623                 log.error("No search found to turn page on " + inPageRequest.getPathUrl());
624             }
625         }
626     
627     }
628
629 }
Popular Tags