KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > order > OrderManagerEvents


1 /*
2  * $Id: OrderManagerEvents.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.order;
25
26 import java.text.NumberFormat JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.LinkedList JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Locale JavaDoc;
31 import java.util.Map JavaDoc;
32
33 import javax.servlet.ServletContext JavaDoc;
34 import javax.servlet.http.HttpServletRequest JavaDoc;
35 import javax.servlet.http.HttpServletResponse JavaDoc;
36 import javax.servlet.http.HttpSession JavaDoc;
37
38 import org.ofbiz.base.util.Debug;
39 import org.ofbiz.base.util.UtilDateTime;
40 import org.ofbiz.base.util.UtilHttp;
41 import org.ofbiz.base.util.UtilMisc;
42 import org.ofbiz.base.util.UtilProperties;
43 import org.ofbiz.base.util.UtilValidate;
44 import org.ofbiz.entity.GenericDelegator;
45 import org.ofbiz.entity.GenericEntityException;
46 import org.ofbiz.entity.GenericValue;
47 import org.ofbiz.entity.condition.EntityExpr;
48 import org.ofbiz.entity.condition.EntityOperator;
49 import org.ofbiz.entity.util.EntityUtil;
50 import org.ofbiz.order.order.OrderChangeHelper;
51 import org.ofbiz.service.ModelService;
52 import org.ofbiz.service.LocalDispatcher;
53 import org.ofbiz.service.GenericServiceException;
54
55 /**
56  * Order Manager Events
57  *
58  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
59  * @version $Rev: 6642 $
60  * @since 2.0
61  */

62 public class OrderManagerEvents {
63
64     public static final String JavaDoc module = OrderManagerEvents.class.getName();
65     public static final String JavaDoc resource_error = "OrderErrorUiLabels";
66
67     public static String JavaDoc processOfflinePayments(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
68         HttpSession JavaDoc session = request.getSession();
69         ServletContext JavaDoc application = ((ServletContext JavaDoc) request.getAttribute("servletContext"));
70         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
71         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
72         GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
73         Locale JavaDoc locale = UtilHttp.getLocale(request);
74
75         if (session.getAttribute("OFFLINE_PAYMENTS") != null) {
76             String JavaDoc orderId = (String JavaDoc) request.getAttribute("orderId");
77             List JavaDoc toBeStored = new LinkedList JavaDoc();
78             List JavaDoc paymentPrefs = null;
79             GenericValue placingCustomer = null;
80             try {
81                 paymentPrefs = delegator.findByAnd("OrderPaymentPreference", UtilMisc.toMap("orderId", orderId));
82                 List JavaDoc pRoles = delegator.findByAnd("OrderRole", UtilMisc.toMap("orderId", orderId, "roleTypeId", "PLACING_CUSTOMER"));
83                 if (pRoles != null && pRoles.size() > 0)
84                     placingCustomer = EntityUtil.getFirst(pRoles);
85             } catch (GenericEntityException e) {
86                 Debug.logError(e, "Problems looking up order payment preferences", module);
87                 request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderErrorProcessingOfflinePayments", locale));
88                 return "error";
89             }
90             if (paymentPrefs != null) {
91                 Iterator JavaDoc i = paymentPrefs.iterator();
92                 while (i.hasNext()) {
93                     // update the preference to received
94
// TODO: updating payment preferences should be done as a service
95
GenericValue ppref = (GenericValue) i.next();
96                     ppref.set("statusId", "PAYMENT_RECEIVED");
97                     ppref.set("authDate", UtilDateTime.nowTimestamp());
98                     toBeStored.add(ppref);
99
100                     // create a payment record
101
Map JavaDoc results = null;
102                     try {
103                         results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("orderPaymentPreferenceId", ppref.get("orderPaymentPreferenceId"),
104                                 "paymentFromId", placingCustomer.getString("partyId"), "comments", "Payment received offline and manually entered."));
105                     } catch (GenericServiceException e) {
106                         Debug.logError(e, "Failed to execute service createPaymentFromPreference", module);
107                         request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
108                         return "error";
109                     }
110  
111                     if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) {
112                         Debug.logError((String JavaDoc) results.get(ModelService.ERROR_MESSAGE), module);
113                         request.setAttribute("_ERROR_MESSAGE_", (String JavaDoc) results.get(ModelService.ERROR_MESSAGE));
114                         return "error";
115                     }
116                 }
117
118                 // store the updated preferences
119
try {
120                     delegator.storeAll(toBeStored);
121                 } catch (GenericEntityException e) {
122                     Debug.logError(e, "Problems storing payment information", module);
123                     request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderProblemStoringReceivedPaymentInformation", locale));
124                     return "error";
125                 }
126
127                 // set the status of the order to approved
128
OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
129             }
130         }
131         return "success";
132     }
133
134     public static String JavaDoc receiveOfflinePayment(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
135         HttpSession JavaDoc session = request.getSession();
136         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
137         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
138         GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
139         Locale JavaDoc locale = UtilHttp.getLocale(request);
140
141         String JavaDoc orderId = request.getParameter("orderId");
142
143         // get the order header & payment preferences
144
GenericValue orderHeader = null;
145         try {
146             orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
147         } catch (GenericEntityException e) {
148             Debug.logError(e, "Problems reading order header from datasource.", module);
149             request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderProblemsReadingOrderHeaderInformation", locale));
150             return "error";
151         }
152
153         Double JavaDoc grandTotal = new Double JavaDoc(0.00);
154         if (orderHeader != null) {
155             grandTotal = orderHeader.getDouble("grandTotal");
156         }
157
158         // get the payment types to receive
159
List JavaDoc paymentMethodTypes = null;
160
161         try {
162             List JavaDoc pmtFields = UtilMisc.toList(new EntityExpr("paymentMethodTypeId", EntityOperator.NOT_EQUAL, "EXT_OFFLINE"));
163             paymentMethodTypes = delegator.findByAnd("PaymentMethodType", pmtFields);
164         } catch (GenericEntityException e) {
165             Debug.logError(e, "Problems getting payment types", module);
166             request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderProblemsWithPaymentTypeLookup", locale));
167             return "error";
168         }
169
170         if (paymentMethodTypes == null) {
171             request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderProblemsWithPaymentTypeLookup", locale));
172             return "error";
173         }
174
175         List JavaDoc toBeStored = new LinkedList JavaDoc();
176         GenericValue placingCustomer = null;
177         try {
178             List JavaDoc pRoles = delegator.findByAnd("OrderRole", UtilMisc.toMap("orderId", orderId, "roleTypeId", "PLACING_CUSTOMER"));
179             if (pRoles != null && pRoles.size() > 0)
180                 placingCustomer = EntityUtil.getFirst(pRoles);
181         } catch (GenericEntityException e) {
182             Debug.logError(e, "Problems looking up order payment preferences", module);
183             request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderErrorProcessingOfflinePayments", locale));
184             return "error";
185         }
186
187         Iterator JavaDoc pmti = paymentMethodTypes.iterator();
188         double paymentTally = 0.00;
189         while (pmti.hasNext()) {
190             GenericValue paymentMethodType = (GenericValue) pmti.next();
191             String JavaDoc paymentMethodTypeId = paymentMethodType.getString("paymentMethodTypeId");
192             String JavaDoc amountStr = request.getParameter(paymentMethodTypeId + "_amount");
193             String JavaDoc paymentReference = request.getParameter(paymentMethodTypeId + "_reference");
194             if (!UtilValidate.isEmpty(amountStr)) {
195                 double paymentTypeAmount = 0.00;
196                 try {
197                     paymentTypeAmount = NumberFormat.getNumberInstance(locale).parse(amountStr).doubleValue();
198                 } catch (java.text.ParseException JavaDoc pe) {
199                     request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderProblemsPaymentParsingAmount", locale));
200                     return "error";
201                 }
202                 if (paymentTypeAmount > 0.00) {
203                     paymentTally += paymentTypeAmount;
204
205                     // create the OrderPaymentPreference
206
// TODO: this should be done with a service
207
Map JavaDoc prefFields = UtilMisc.toMap("orderPaymentPreferenceId", delegator.getNextSeqId("OrderPaymentPreference").toString());
208                     GenericValue paymentPreference = delegator.makeValue("OrderPaymentPreference", prefFields);
209                     paymentPreference.set("paymentMethodTypeId", paymentMethodType.getString("paymentMethodTypeId"));
210                     paymentPreference.set("maxAmount", new Double JavaDoc(paymentTypeAmount));
211                     paymentPreference.set("statusId", "PAYMENT_RECEIVED");
212                     paymentPreference.set("orderId", orderId);
213                     paymentPreference.set("createdDate", UtilDateTime.nowTimestamp());
214                     if (userLogin != null) {
215                         paymentPreference.set("createdByUserLogin", userLogin.getString("userLoginId"));
216                     }
217                     
218                     try {
219                         delegator.create(paymentPreference);
220                     } catch (GenericEntityException ex) {
221                         Debug.logError(ex, "Cannot create a new OrderPaymentPreference", module);
222                         request.setAttribute("_ERROR_MESSAGE_", ex.getMessage());
223                         return "error";
224                     }
225
226                     // create a payment record
227
Map JavaDoc results = null;
228                     try {
229                         results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin,
230                                 "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "paymentRefNum", paymentReference,
231                                 "paymentFromId", placingCustomer.getString("partyId"), "comments", "Payment received offline and manually entered."));
232                     } catch (GenericServiceException e) {
233                         Debug.logError(e, "Failed to execute service createPaymentFromPreference", module);
234                         request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
235                         return "error";
236                     }
237                      
238                     if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) {
239                         Debug.logError((String JavaDoc) results.get(ModelService.ERROR_MESSAGE), module);
240                         request.setAttribute("_ERROR_MESSAGE_", (String JavaDoc) results.get(ModelService.ERROR_MESSAGE));
241                         return "error";
242                     }
243                 }
244             }
245         }
246
247         // get the current payment prefs
248
GenericValue offlineValue = null;
249         List JavaDoc currentPrefs = null;
250         try {
251             List JavaDoc oppFields = UtilMisc.toList(new EntityExpr("orderId", EntityOperator.EQUALS, orderId),
252                     new EntityExpr("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
253             currentPrefs = delegator.findByAnd("OrderPaymentPreference", oppFields);
254         } catch (GenericEntityException e) {
255             Debug.logError(e, "ERROR: Unable to get existing payment preferences from order", module);
256         }
257         if (currentPrefs != null && currentPrefs.size() > 0) {
258             Iterator JavaDoc cpi = currentPrefs.iterator();
259             while (cpi.hasNext()) {
260                 GenericValue cp = (GenericValue) cpi.next();
261                 String JavaDoc paymentMethodType = cp.getString("paymentMethodTypeId");
262                 if ("EXT_OFFLINE".equals(paymentMethodType)) {
263                     offlineValue = cp;
264                 } else {
265                     Double JavaDoc cpAmt = cp.getDouble("maxAmount");
266                     if (cpAmt != null) {
267                         paymentTally += cpAmt.doubleValue();
268                     }
269                 }
270             }
271         }
272
273         // now finish up
274
boolean okayToApprove = false;
275         if (paymentTally >= grandTotal.doubleValue()) {
276             // cancel the offline preference
277
okayToApprove = true;
278             if (offlineValue != null) {
279                 offlineValue.set("statusId", "PAYMENT_CANCELLED");
280                 toBeStored.add(offlineValue);
281             }
282         }
283
284         // store the status changes and the newly created payment preferences and payments
285
// TODO: updating order payment preference should be done with a service
286
try {
287             delegator.storeAll(toBeStored);
288         } catch (GenericEntityException e) {
289             Debug.logError(e, "Problems storing payment information", module);
290             request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderProblemStoringReceivedPaymentInformation", locale));
291             return "error";
292         }
293
294         if (okayToApprove) {
295             // update the status of the order and items
296
OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
297         }
298
299         return "success";
300     }
301
302 }
303
Popular Tags