KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > pos > PosTransaction


1 /*
2  * $Id: PosTransaction.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2004 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  */

25 package org.ofbiz.pos;
26
27 import java.io.PrintWriter JavaDoc;
28 import java.io.Serializable JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Locale JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.HashMap JavaDoc;
34
35 import net.xoetrope.xui.data.XModel;
36 import net.xoetrope.xui.helper.SwingWorker;
37
38 import org.ofbiz.base.util.Debug;
39 import org.ofbiz.base.util.Log4jLoggerWriter;
40 import org.ofbiz.base.util.UtilFormatOut;
41 import org.ofbiz.base.util.UtilValidate;
42 import org.ofbiz.base.util.GeneralException;
43 import org.ofbiz.base.util.UtilMisc;
44 import org.ofbiz.base.util.UtilDateTime;
45 import org.ofbiz.base.util.collections.LifoSet;
46 import org.ofbiz.guiapp.xui.XuiSession;
47 import org.ofbiz.order.shoppingcart.CartItemModifyException;
48 import org.ofbiz.order.shoppingcart.ShoppingCart;
49 import org.ofbiz.order.shoppingcart.ShoppingCartItem;
50 import org.ofbiz.order.shoppingcart.CheckOutHelper;
51 import org.ofbiz.order.shoppingcart.ItemNotFoundException;
52 import org.ofbiz.pos.component.Journal;
53 import org.ofbiz.pos.component.Output;
54 import org.ofbiz.pos.device.DeviceLoader;
55 import org.ofbiz.entity.GenericValue;
56 import org.ofbiz.entity.GenericEntityException;
57 import org.ofbiz.entity.GenericDelegator;
58 import org.ofbiz.entity.util.EntityUtil;
59 import org.ofbiz.product.store.ProductStoreWorker;
60 import org.ofbiz.service.ServiceUtil;
61 import org.ofbiz.service.LocalDispatcher;
62 import org.ofbiz.service.GenericServiceException;
63 import org.ofbiz.accounting.payment.PaymentGatewayServices;
64 import org.ofbiz.base.util.UtilProperties;
65
66 /**
67  *
68  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
69  * @version $Rev: 5462 $
70  * @since 3.1
71  */

72 public class PosTransaction implements Serializable JavaDoc {
73
74     public static final String JavaDoc module = PosTransaction.class.getName();
75     public static final int NO_PAYMENT = 0;
76     public static final int INTERNAL_PAYMENT = 1;
77     public static final int EXTERNAL_PAYMENT = 2;
78
79     private static PrintWriter JavaDoc defaultPrintWriter = new Log4jLoggerWriter(Debug.getLogger(module));
80     private static PosTransaction currentTx = null;
81     private static LifoSet savedTx = new LifoSet();
82     private Locale JavaDoc defaultLocale = Locale.getDefault();
83
84     protected XuiSession session = null;
85     protected ShoppingCart cart = null;
86     protected CheckOutHelper ch = null;
87     protected PrintWriter JavaDoc trace = null;
88     protected GenericValue txLog = null;
89
90     protected String JavaDoc productStoreId = null;
91     protected String JavaDoc transactionId = null;
92     protected String JavaDoc facilityId = null;
93     protected String JavaDoc terminalId = null;
94     protected String JavaDoc currency = null;
95     protected String JavaDoc orderId = null;
96     protected String JavaDoc partyId = null;
97     protected Locale JavaDoc locale = null;
98     protected boolean isOpen = false;
99     protected int drawerIdx = 0;
100
101     private GenericValue shipAddress = null;
102     private Map JavaDoc skuDiscounts = new HashMap JavaDoc();
103     private int cartDiscount = -1;
104
105
106     public PosTransaction(XuiSession session) {
107         this.session = session;
108         this.terminalId = session.getId();
109         this.partyId = "_NA_";
110         this.trace = defaultPrintWriter;
111
112         this.productStoreId = (String JavaDoc) session.getAttribute("productStoreId");
113         this.facilityId = (String JavaDoc) session.getAttribute("facilityId");
114         this.currency = (String JavaDoc) session.getAttribute("currency");
115         this.locale = (Locale JavaDoc) session.getAttribute("locale");
116
117         this.cart = new ShoppingCart(session.getDelegator(), productStoreId, locale, currency);
118         this.transactionId = session.getDelegator().getNextSeqId("PosTransaction");
119         this.ch = new CheckOutHelper(session.getDispatcher(), session.getDelegator(), cart);
120         cart.setChannelType("POS_SALES_CHANNEL");
121         cart.setTransactionId(transactionId);
122         cart.setFacilityId(facilityId);
123         cart.setTerminalId(terminalId);
124         if (session.getUserLogin() != null) {
125             cart.addAdditionalPartyRole(session.getUserLogin().getString("partyId"), "SALES_REP");
126         }
127
128         // setup the TX log
129
String JavaDoc txLogId = session.getDelegator().getNextSeqId("PosTerminalLog");
130         txLog = session.getDelegator().makeValue("PosTerminalLog", null);
131         txLog.set("posTerminalLogId", txLogId);
132         txLog.set("posTerminalId", terminalId);
133         txLog.set("transactionId", transactionId);
134         txLog.set("userLoginId", session.getUserId());
135         txLog.set("statusId", "POSTX_ACTIVE");
136         txLog.set("logStartDateTime", UtilDateTime.nowTimestamp());
137         try {
138             txLog.create();
139         } catch (GenericEntityException e) {
140             Debug.logError(e, "Unable to create TX log - not fatal", module);
141         }
142
143         currentTx = this;
144         trace("transaction created");
145     }
146
147     public String JavaDoc getUserId() {
148         return session.getUserId();
149     }
150
151     public int getDrawerNumber() {
152         return drawerIdx + 1;
153     }
154
155     public void popDrawer() {
156         DeviceLoader.drawer[drawerIdx].openDrawer();
157     }
158
159     public String JavaDoc getTransactionId() {
160         return this.transactionId;
161     }
162
163     public String JavaDoc getTerminalId() {
164         return this.terminalId;
165     }
166
167     public String JavaDoc getFacilityId() {
168         return this.facilityId;
169     }
170
171     public boolean isOpen() {
172         if (!this.isOpen) {
173             GenericValue terminalState = this.getTerminalState();
174             if (terminalState != null) {
175                 this.isOpen = true;
176             } else {
177                 this.isOpen = false;
178             }
179         }
180         return this.isOpen;
181     }
182
183     public boolean isEmpty() {
184         return (cart == null || cart.size() == 0);
185     }
186
187     public List JavaDoc lookupItem(String JavaDoc sku) throws GeneralException {
188         // first check for the product
189
GenericValue product = session.getDelegator().findByPrimaryKey("Product", UtilMisc.toMap("productId", sku));
190         if (product != null) {
191             return UtilMisc.toList(product);
192         } else {
193             // not found; so we move on to GoodIdentification
194
return session.getDelegator().findByAnd("GoodIdentificationAndProduct",
195                    UtilMisc.toMap("idValue", sku), UtilMisc.toList("productId"));
196         }
197     }
198
199     public String JavaDoc getOrderId() {
200         return this.orderId;
201     }
202
203     public double getTaxTotal() {
204         return cart.getTotalSalesTax();
205     }
206     
207     public double getGrandTotal() {
208         return UtilFormatOut.formatPriceNumber(cart.getGrandTotal()).doubleValue();
209     }
210
211     public int getNumberOfPayments() {
212         return cart.selectedPayments();
213     }
214
215     public double getPaymentTotal() {
216         return UtilFormatOut.formatPriceNumber(cart.getPaymentTotal()).doubleValue();
217     }
218
219     public double getTotalDue() {
220         double grandTotal = this.getGrandTotal();
221         double paymentAmt = this.getPaymentTotal();
222         return (grandTotal - paymentAmt);
223     }
224
225     public int size() {
226         return cart.size();
227     }
228
229     public Map JavaDoc getItemInfo(int index) {
230         ShoppingCartItem item = cart.findCartItem(index);
231         Map JavaDoc itemInfo = new HashMap JavaDoc();
232         itemInfo.put("productId", item.getProductId());
233         itemInfo.put("description", item.getDescription());
234         itemInfo.put("quantity", UtilFormatOut.formatQuantity(item.getQuantity()));
235         itemInfo.put("basePrice", UtilFormatOut.formatPrice(item.getBasePrice()));
236         itemInfo.put("subtotal", UtilFormatOut.formatPrice(item.getItemSubTotal()));
237         itemInfo.put("isTaxable", item.taxApplies() ? "T" : " ");
238         itemInfo.put("adjustments", item.getOtherAdjustments() > 0 ?
239                 UtilFormatOut.formatPrice(item.getOtherAdjustments()) : "");
240
241         return itemInfo;
242     }
243
244     public Map JavaDoc getPaymentInfo(int index) {
245         ShoppingCart.CartPaymentInfo inf = cart.getPaymentInfo(index);
246         GenericValue infValue = inf.getValueObject(session.getDelegator());
247         GenericValue paymentPref = null;
248         try {
249             Map JavaDoc fields = new HashMap JavaDoc();
250             fields.put("paymentMethodTypeId", inf.paymentMethodTypeId);
251             if (inf.paymentMethodId != null) {
252                 fields.put("paymentMethodId", inf.paymentMethodId);
253             }
254             fields.put("maxAmount", inf.amount);
255             fields.put("orderId", this.getOrderId());
256
257             List JavaDoc paymentPrefs = session.getDelegator().findByAnd("OrderPaymentPreference", fields);
258             if (paymentPrefs != null && paymentPrefs.size() > 0) {
259                 Debug.log("Found some prefs - " + paymentPrefs.size(), module);
260                 if (paymentPrefs.size() > 1) {
261                     Debug.logError("Multiple OrderPaymentPreferences found for the same payment method!", module);
262                 } else {
263                     paymentPref = EntityUtil.getFirst(paymentPrefs);
264                     Debug.log("Got the first pref - " + paymentPref, module);
265                 }
266             } else {
267                 Debug.logError("No OrderPaymentPreference found - " + fields, module);
268             }
269         } catch (GenericEntityException e) {
270             Debug.logError(e, module);
271         }
272         Debug.log("PaymentPref - " + paymentPref, module);
273
274         Map JavaDoc payInfo = new HashMap JavaDoc();
275
276         // locate the auth info
277
GenericValue authTrans = null;
278         if (paymentPref != null) {
279             authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
280             if (authTrans != null) {
281                 payInfo.putAll(authTrans);
282
283                 String JavaDoc authInfoString = "Ref: " + authTrans.getString("referenceNum") + " Auth: " + authTrans.getString("gatewayCode");
284                 payInfo.put("authInfoString", authInfoString);
285             } else {
286                 Debug.logError("No Authorization transaction found for payment preference - " + paymentPref, module);
287             }
288         } else {
289             Debug.logError("Payment preference is empty!", module);
290             return payInfo;
291         }
292         Debug.log("AuthTrans - " + authTrans, module);
293
294         if ("PaymentMethodType".equals(infValue.getEntityName())) {
295             payInfo.put("description", infValue.getString("description"));
296             payInfo.put("payInfo", infValue.getString("description"));
297             payInfo.put("amount", UtilFormatOut.formatPrice(inf.amount));
298         } else {
299             String JavaDoc paymentMethodTypeId = infValue.getString("paymentMethodTypeId");
300             GenericValue pmt = null;
301             try {
302                  pmt = infValue.getRelatedOne("PaymentMethodType");
303             } catch (GenericEntityException e) {
304                 Debug.logError(e, module);
305             }
306             if (pmt != null) {
307                 payInfo.put("description", pmt.getString("description"));
308                 payInfo.put("amount", UtilFormatOut.formatPrice(inf.amount));
309             }
310
311             if ("CREDIT_CARD".equals(paymentMethodTypeId)) {
312                 GenericValue cc = null;
313                 try {
314                     cc = infValue.getRelatedOne("CreditCard");
315                 } catch (GenericEntityException e) {
316                     Debug.logError(e, module);
317                 }
318                 String JavaDoc nameOnCard = cc.getString("firstNameOnCard") + " " + cc.getString("lastNameOnCard");
319                 nameOnCard.trim();
320                 payInfo.put("nameOnCard", nameOnCard);
321
322                 String JavaDoc cardNum = cc.getString("cardNumber");
323                 String JavaDoc cardStr = cardNum.substring(0, 2);
324                 cardStr = cardStr + "****";
325                 cardStr = cardStr + cardNum.substring(cardNum.length() - 4);
326
327                 String JavaDoc expDate = cc.getString("expireDate");
328                 String JavaDoc infoString = cardStr + " " + expDate;
329                 payInfo.put("payInfo", infoString);
330                 payInfo.putAll(cc);
331
332
333             } else if ("GIFT_CARD".equals(paymentMethodTypeId)) {
334                 GenericValue gc = null;
335                 try {
336                     gc = infValue.getRelatedOne("GiftCard");
337                 } catch (GenericEntityException e) {
338                     Debug.logError(e, module);
339                 }
340             }
341         }
342
343         return payInfo;
344     }
345
346     public double getItemQuantity(String JavaDoc productId) {
347         trace("request item quantity", productId);
348         ShoppingCartItem item = cart.findCartItem(productId, null, null, null, 0.00);
349         if (item != null) {
350             return item.getQuantity();
351         } else {
352             trace("item not found", productId);
353             return 0;
354         }
355     }
356         
357     public void addItem(String JavaDoc productId, double quantity) throws CartItemModifyException, ItemNotFoundException {
358         trace("add item", productId + "/" + quantity);
359         try {
360             cart.addOrIncreaseItem(productId, quantity, session.getDispatcher());
361         } catch (ItemNotFoundException e) {
362             trace("item not found", e);
363             throw e;
364         } catch (CartItemModifyException e) {
365             trace("add item error", e);
366             throw e;
367         }
368     }
369
370     public void modifyQty(String JavaDoc productId, double quantity) throws CartItemModifyException {
371         trace("modify item quantity", productId + "/" + quantity);
372         ShoppingCartItem item = cart.findCartItem(productId, null, null, null, 0.00);
373         if (item != null) {
374             try {
375                 item.setQuantity(quantity, session.getDispatcher(), cart, true);
376             } catch (CartItemModifyException e) {
377                 Debug.logError(e, module);
378                 trace("modify item error", e);
379                 throw e;
380             }
381         } else {
382             trace("item not found", productId);
383         }
384     }
385
386     public void modifyPrice(String JavaDoc productId, double price) {
387         trace("modify item price", productId + "/" + price);
388         ShoppingCartItem item = cart.findCartItem(productId, null, null, null, 0.00);
389         if (item != null) {
390             item.setBasePrice(price);
391         } else {
392             trace("item not found", productId);
393         }
394     }
395
396     public void addDiscount(String JavaDoc productId, double discount, boolean percent) {
397         GenericValue adjustment = session.getDelegator().makeValue("OrderAdjustment", null);
398         adjustment.set("orderAdjustmentTypeId", "DISCOUNT_ADJUSTMENT");
399         if (percent) {
400             adjustment.set("percentage", new Double JavaDoc(discount));
401         } else {
402             adjustment.set("amount", new Double JavaDoc(discount));
403         }
404
405         if (productId != null) {
406             trace("add item adjustment");
407             ShoppingCartItem item = cart.findCartItem(productId, null, null, null, 0.00);
408             Integer JavaDoc itemAdj = (Integer JavaDoc) skuDiscounts.get(productId);
409             if (itemAdj != null) {
410                 item.removeAdjustment(itemAdj.intValue());
411             }
412             int idx = item.addAdjustment(adjustment);
413             skuDiscounts.put(productId, new Integer JavaDoc(idx));
414         } else {
415             trace("add sale adjustment");
416             if (cartDiscount > -1) {
417                 cart.removeAdjustment(cartDiscount);
418             }
419             cartDiscount = cart.addAdjustment(adjustment);
420         }
421     }
422
423     public void clearDiscounts() {
424         if (cartDiscount > -1) {
425             cart.removeAdjustment(cartDiscount);
426             cartDiscount = -1;
427         }
428         if (skuDiscounts.size() > 0) {
429             Iterator JavaDoc i = skuDiscounts.keySet().iterator();
430             while (i.hasNext()) {
431                 String JavaDoc productId = (String JavaDoc) i.next();
432                 ShoppingCartItem item = cart.findCartItem(productId, null, null, null, 0.00);
433                 Integer JavaDoc itemAdj = (Integer JavaDoc) skuDiscounts.remove(productId);
434                 if (itemAdj != null) {
435                     item.removeAdjustment(itemAdj.intValue());
436                 }
437             }
438         }
439     }
440
441     public void voidItem(String JavaDoc productId) throws CartItemModifyException {
442         trace("void item", productId);
443         ShoppingCartItem item = cart.findCartItem(productId, null, null, null, 0.00);
444         if (item != null) {
445             try {
446                 int itemIdx = cart.getItemIndex(item);
447                 cart.removeCartItem(itemIdx, session.getDispatcher());
448             } catch (CartItemModifyException e) {
449                 Debug.logError(e, module);
450                 trace("void item error", productId, e);
451                 throw e;
452             }
453         } else {
454             trace("item not found", productId);
455         }
456     }
457
458     public void voidSale() {
459         trace("void sale");
460         txLog.set("statusId", "POSTX_VOIDED");
461         txLog.set("itemCount", new Long JavaDoc(cart.size()));
462         txLog.set("logEndDateTime", UtilDateTime.nowTimestamp());
463         try {
464             txLog.store();
465         } catch (GenericEntityException e) {
466             Debug.logError(e, "Unable to store TX log - not fatal", module);
467         }
468         cart.clear();
469         currentTx = null;
470     }
471         
472     public void closeTx() {
473         trace("transaction closed");
474         txLog.set("statusId", "POSTX_CLOSED");
475         txLog.set("itemCount", new Long JavaDoc(cart.size()));
476         txLog.set("logEndDateTime", UtilDateTime.nowTimestamp());
477         try {
478             txLog.store();
479         } catch (GenericEntityException e) {
480             Debug.logError(e, "Unable to store TX log - not fatal", module);
481         }
482         cart.clear();
483         currentTx = null;
484     }
485
486     public void calcTax() {
487         try {
488             ch.calcAndAddTax(this.getStoreOrgAddress());
489         } catch (GeneralException e) {
490             Debug.logError(e, module);
491         }
492     }
493
494     public void clearTax() {
495         cart.removeAdjustmentByType("SALES_TAX");
496     }
497
498     public int checkPaymentMethodType(String JavaDoc paymentMethodTypeId) {
499         Map JavaDoc fields = UtilMisc.toMap("paymentMethodTypeId", paymentMethodTypeId, "productStoreId", productStoreId);
500         List JavaDoc values = null;
501         try {
502             values = session.getDelegator().findByAndCache("ProductStorePaymentSetting", fields);
503         } catch (GenericEntityException e) {
504             Debug.logError(e, module);
505         }
506
507         final String JavaDoc externalCode = "PRDS_PAY_EXTERNAL";
508         if (values == null || values.size() == 0) {
509             return NO_PAYMENT;
510         } else {
511             boolean isExternal = true;
512             Iterator JavaDoc i = values.iterator();
513             while (i.hasNext() && isExternal) {
514                 GenericValue v = (GenericValue) i.next();
515                 Debug.log("Testing [" + paymentMethodTypeId + "] - " + v, module);
516                 if (!externalCode.equals(v.getString("paymentServiceTypeEnumId"))) {
517                     isExternal = false;
518                 }
519             }
520
521             if (isExternal) {
522                 return EXTERNAL_PAYMENT;
523             } else {
524                 return INTERNAL_PAYMENT;
525             }
526         }
527     }
528
529     public double addPayment(String JavaDoc id, double amount) {
530         return this.addPayment(id, amount, null, null);
531     }
532
533     public double addPayment(String JavaDoc id, double amount, String JavaDoc refNum, String JavaDoc authCode) {
534         trace("added payment", id + "/" + amount);
535         if ("CASH".equals(id)) {
536             // clear cash payments first; so there is only one
537
cart.clearPayment(id);
538         }
539         cart.addPaymentAmount(id, new Double JavaDoc(amount), refNum, authCode, true, true, false);
540         return this.getTotalDue();
541     }
542
543     public void setPaymentRefNum(int paymentIndex, String JavaDoc refNum, String JavaDoc authCode) {
544         trace("setting payment index reference number", paymentIndex + " / " + refNum + " / " + authCode);
545         ShoppingCart.CartPaymentInfo inf = cart.getPaymentInfo(paymentIndex);
546         inf.refNum[0] = refNum;
547         inf.refNum[1] = authCode;
548     }
549
550     public void clearPayments() {
551         trace("all payments cleared from sale");
552         cart.clearPayments();
553     }
554
555     public void clearPayment(int index) {
556         trace("removing payment", "" + index);
557         cart.clearPayment(index);
558     }
559
560     public void clearPayment(String JavaDoc id) {
561         trace("removing payment", id);
562         cart.clearPayment(id);
563     }
564
565     public int selectedPayments() {
566         return cart.selectedPayments();
567     }
568
569     public void setTxAsReturn(String JavaDoc returnId) {
570         trace("returned sale");
571         txLog.set("statusId", "POSTX_RETURNED");
572         txLog.set("returnId", returnId);
573         txLog.set("logEndDateTime", UtilDateTime.nowTimestamp());
574         try {
575             txLog.store();
576         } catch (GenericEntityException e) {
577             Debug.logError(e, "Unable to store TX log - not fatal", module);
578         }
579         cart.clear();
580         currentTx = null;
581     }
582
583     public double processSale(Output output) throws GeneralException {
584         trace("process sale");
585         double grandTotal = this.getGrandTotal();
586         double paymentAmt = this.getPaymentTotal();
587         if (grandTotal > paymentAmt) {
588             throw new IllegalStateException JavaDoc();
589         }
590
591         // attach the party ID to the cart
592
cart.setOrderPartyId(partyId);
593
594         // validate payment methods
595
output.print(UtilProperties.getMessage("pos","Validating",defaultLocale));
596         Map JavaDoc valRes = ch.validatePaymentMethods();
597         if (valRes != null && ServiceUtil.isError(valRes)) {
598             throw new GeneralException(ServiceUtil.getErrorMessage(valRes));
599         }
600
601         // store the "order"
602
output.print(UtilProperties.getMessage("pos","Saving",defaultLocale));
603         Map JavaDoc orderRes = ch.createOrder(session.getUserLogin());
604         Debug.log("Create Order Resp : " + orderRes, module);
605
606         if (orderRes != null && ServiceUtil.isError(orderRes)) {
607             throw new GeneralException(ServiceUtil.getErrorMessage(orderRes));
608         } else if (orderRes != null) {
609             this.orderId = (String JavaDoc) orderRes.get("orderId");
610         }
611
612         // process the payment(s)
613
output.print(UtilProperties.getMessage("pos","Processing",defaultLocale));
614         Map JavaDoc payRes = null;
615         try {
616             payRes = ch.processPayment(ProductStoreWorker.getProductStore(productStoreId, session.getDelegator()), session.getUserLogin(), true);
617         } catch (GeneralException e) {
618             Debug.logError(e, module);
619             throw e;
620         }
621
622         if (payRes != null && ServiceUtil.isError(payRes)) {
623             throw new GeneralException(ServiceUtil.getErrorMessage(payRes));
624         }
625
626         // get the change due
627
double change = (grandTotal - paymentAmt);
628
629         // notify the change due
630
output.print(UtilProperties.getMessage("pos","CHANGE",defaultLocale) + " " + UtilFormatOut.formatPrice(this.getTotalDue() * -1));
631
632         // threaded drawer/receipt printing
633
final PosTransaction currentTrans = this;
634         final SwingWorker worker = new SwingWorker() {
635             public Object JavaDoc construct() {
636                 // open the drawer
637
currentTrans.popDrawer();
638
639                 // print the receipt
640
DeviceLoader.receipt.printReceipt(currentTrans, true);
641
642                 return null;
643             }
644         };
645         worker.start();
646
647         // save the TX Log
648
txLog.set("statusId", "POSTX_SOLD");
649         txLog.set("orderId", orderId);
650         txLog.set("itemCount", new Long JavaDoc(cart.size()));
651         txLog.set("logEndDateTime", UtilDateTime.nowTimestamp());
652         try {
653             txLog.store();
654         } catch (GenericEntityException e) {
655             Debug.logError(e, "Unable to store TX log - not fatal", module);
656         }
657
658         // clear the tx
659
currentTx = null;
660
661         return change;
662     }
663
664     private synchronized GenericValue getStoreOrgAddress() {
665         if (this.shipAddress == null) {
666             // locate the store's physical address - use this for tax
667
GenericValue facility = (GenericValue) session.getAttribute("facility");
668             if (facility == null) {
669                 return null;
670             }
671
672             List JavaDoc fcp = null;
673             try {
674                 fcp = facility.getRelatedByAnd("FacilityContactMechPurpose", UtilMisc.toMap("contactMechPurposeTypeId", "SHIP_ORIG_LOCATION"));
675             } catch (GenericEntityException e) {
676                 Debug.logError(e, module);
677             }
678             fcp = EntityUtil.filterByDate(fcp);
679             GenericValue purp = EntityUtil.getFirst(fcp);
680             if (purp != null) {
681                 try {
682                     this.shipAddress = session.getDelegator().findByPrimaryKey("PostalAddress",
683                             UtilMisc.toMap("contactMechId", purp.getString("contactMechId")));
684                 } catch (GenericEntityException e) {
685                     Debug.logError(e, module);
686                 }
687             }
688         }
689         return this.shipAddress;
690     }
691
692     public void saveTx() {
693         savedTx.push(this);
694         currentTx = null;
695         trace("transaction saved");
696     }
697
698     public void appendItemDataModel(XModel model) {
699         if (cart != null) {
700             Iterator JavaDoc i = cart.iterator();
701             while (i.hasNext()) {
702                 ShoppingCartItem item = (ShoppingCartItem) i.next();
703                 double quantity = item.getQuantity();
704                 double unitPrice = item.getBasePrice();
705                 double subTotal = unitPrice * quantity;
706                 double adjustment = item.getOtherAdjustments();
707
708                 XModel line = Journal.appendNode(model, "tr", "", "");
709                 Journal.appendNode(line, "td", "sku", item.getProductId());
710                 Journal.appendNode(line, "td", "desc", item.getName());
711                 Journal.appendNode(line, "td", "qty", UtilFormatOut.formatQuantity(quantity));
712                 Journal.appendNode(line, "td", "price", UtilFormatOut.formatPrice(subTotal));
713                 Journal.appendNode(line, "td", "index", new Integer JavaDoc(cart.getItemIndex(item)).toString());
714                 if (adjustment != 0) {
715                     // append the promo info
716
XModel promo = Journal.appendNode(model, "tr", "", "");
717                     Journal.appendNode(promo, "td", "sku", "");
718                     Journal.appendNode(promo, "td", "desc", "(adjustment)");
719                     Journal.appendNode(promo, "td", "qty", "-");
720                     Journal.appendNode(promo, "td", "price", UtilFormatOut.formatPrice(adjustment));
721                 }
722             }
723         }
724     }
725
726     public void appendTotalDataModel(XModel model) {
727         if (cart != null) {
728             double taxAmount = cart.getTotalSalesTax();
729             double total = cart.getGrandTotal();
730
731             XModel taxLine = Journal.appendNode(model, "tr", "", "");
732             Journal.appendNode(taxLine, "td", "sku", "");
733             
734             Journal.appendNode(taxLine, "td", "desc", UtilProperties.getMessage("pos","Sales_Tax",defaultLocale));
735             Journal.appendNode(taxLine, "td", "qty", "-");
736             Journal.appendNode(taxLine, "td", "price", UtilFormatOut.formatPrice(taxAmount));
737
738             XModel totalLine = Journal.appendNode(model, "tr", "", "");
739             Journal.appendNode(totalLine, "td", "sku", "");
740             Journal.appendNode(totalLine, "td", "desc", UtilProperties.getMessage("pos","Grand_Total",defaultLocale));
741             Journal.appendNode(totalLine, "td", "qty", "-");
742             Journal.appendNode(totalLine, "td", "price", UtilFormatOut.formatPrice(total));
743         }
744     }
745
746     public void appendPaymentDataModel(XModel model) {
747         if (cart != null) {
748             int paymentInfoSize = cart.selectedPayments();
749             for (int i = 0; i < paymentInfoSize; i++) {
750                 ShoppingCart.CartPaymentInfo inf = (ShoppingCart.CartPaymentInfo) cart.getPaymentInfo(i);
751                 GenericValue paymentInfoObj = inf.getValueObject(session.getDelegator());
752
753                 GenericValue paymentMethodType = null;
754                 GenericValue paymentMethod = null;
755                 if ("PaymentMethod".equals(paymentInfoObj.getEntityName())) {
756                     paymentMethod = paymentInfoObj;
757                     try {
758                         paymentMethodType = paymentMethod.getRelatedOne("PaymentMethodType");
759                     } catch (GenericEntityException e) {
760                         Debug.logError(e, module);
761                     }
762                 } else {
763                     paymentMethodType = paymentInfoObj;
764                 }
765
766                 Object JavaDoc desc = paymentMethodType != null ? paymentMethodType.get("description",defaultLocale) : "??";
767                 String JavaDoc descString = desc.toString();
768                 double amount = 0;
769                 if (inf.amount == null) {
770                     amount = cart.getGrandTotal() - cart.getPaymentTotal();
771                 } else {
772                     amount = inf.amount.doubleValue();
773                 }
774
775                 XModel paymentLine = Journal.appendNode(model, "tr", "", "");
776                 Journal.appendNode(paymentLine, "td", "sku", "");
777                 Journal.appendNode(paymentLine, "td", "desc", descString);
778                 Journal.appendNode(paymentLine, "td", "qty", "-");
779                 Journal.appendNode(paymentLine, "td", "price", UtilFormatOut.formatPrice(-1 * amount));
780                 Journal.appendNode(paymentLine, "td", "index", new Integer JavaDoc(i).toString());
781             }
782         }
783     }
784
785     public void appendChangeDataModel(XModel model) {
786         if (cart != null) {
787             double changeDue = (-1 * this.getTotalDue());
788             if (changeDue >= 0) {
789                 XModel changeLine = Journal.appendNode(model, "tr", "", "");
790                 Journal.appendNode(changeLine, "td", "sku", "");
791                 Journal.appendNode(changeLine, "td", "desc", "Change");
792                 Journal.appendNode(changeLine, "td", "qty", "-");
793                 Journal.appendNode(changeLine, "td", "price", UtilFormatOut.formatPrice(changeDue));
794             }
795         }
796     }
797
798     public String JavaDoc makeCreditCardVo(String JavaDoc cardNumber, String JavaDoc expDate, String JavaDoc firstName, String JavaDoc lastName) {
799         LocalDispatcher dispatcher = session.getDispatcher();
800         String JavaDoc expMonth = expDate.substring(0, 2);
801         String JavaDoc expYear = expDate.substring(2);
802         // two digit year check -- may want to re-think this
803
if (expYear.length() == 2) {
804             expYear = "20" + expYear;
805         }
806
807         Map JavaDoc svcCtx = new HashMap JavaDoc();
808         svcCtx.put("userLogin", session.getUserLogin());
809         svcCtx.put("partyId", partyId);
810         svcCtx.put("cardNumber", cardNumber);
811         svcCtx.put("firstNameOnCard", firstName == null ? "" : firstName);
812         svcCtx.put("lastNameOnCard", lastName == null ? "" : lastName);
813         svcCtx.put("expMonth", expMonth);
814         svcCtx.put("expYear", expYear);
815         svcCtx.put("cardType", UtilValidate.getCardType(cardNumber));
816
817         Debug.log("Create CC : " + svcCtx, module);
818         Map JavaDoc svcRes = null;
819         try {
820             svcRes = dispatcher.runSync("createCreditCard", svcCtx);
821         } catch (GenericServiceException e) {
822             Debug.logError(e, module);
823             return null;
824         }
825         if (ServiceUtil.isError(svcRes)) {
826             Debug.logError(ServiceUtil.getErrorMessage(svcRes) + " - " + svcRes, module);
827             return null;
828         } else {
829             return (String JavaDoc) svcRes.get("paymentMethodId");
830         }
831     }
832
833     public GenericValue getTerminalState() {
834         GenericDelegator delegator = session.getDelegator();
835         List JavaDoc states = null;
836         try {
837             states = delegator.findByAnd("PosTerminalState", UtilMisc.toMap("posTerminalId", this.getTerminalId()));
838         } catch (GenericEntityException e) {
839             Debug.logError(e, module);
840         }
841         states = EntityUtil.filterByDate(states, UtilDateTime.nowTimestamp(), "openedDate", "closedDate", true);
842         return EntityUtil.getFirst(states);
843     }
844
845     public void setPrintWriter(PrintWriter JavaDoc writer) {
846         this.trace = writer;
847     }
848
849     private void trace(String JavaDoc s) {
850         trace(s, null, null);
851     }
852
853     private void trace(String JavaDoc s, Throwable JavaDoc t) {
854         trace(s, null, t);
855     }
856
857     private void trace(String JavaDoc s1, String JavaDoc s2) {
858         trace(s1, s2, null);
859     }
860
861     private void trace(String JavaDoc s1, String JavaDoc s2, Throwable JavaDoc t) {
862         if (trace != null) {
863             String JavaDoc msg = s1;
864             if (UtilValidate.isNotEmpty(s2)) {
865                 msg = msg + "(" + s2 + ")";
866             }
867             if (t != null) {
868                 msg = msg + " : " + t.getMessage();
869             }
870
871             // print the trace line
872
trace.println("[POS @ " + terminalId + " TX:" + transactionId + "] - " + msg);
873             trace.flush();
874         }
875     }
876
877     public static synchronized PosTransaction getCurrentTx(XuiSession session) {
878         if (currentTx == null) {
879             if (session.getUserLogin() != null) {
880                 currentTx = new PosTransaction(session);
881             }
882         }
883         return currentTx;
884     }
885 }
Popular Tags