KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: OrderChangeHelper.java 6536 2006-01-22 23:04:00Z 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  */

25 package org.ofbiz.order.order;
26
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import org.ofbiz.base.util.Debug;
32 import org.ofbiz.base.util.UtilDateTime;
33 import org.ofbiz.base.util.UtilMisc;
34 import org.ofbiz.entity.GenericDelegator;
35 import org.ofbiz.entity.GenericEntityException;
36 import org.ofbiz.entity.GenericValue;
37 import org.ofbiz.entity.util.EntityUtil;
38 import org.ofbiz.service.GenericServiceException;
39 import org.ofbiz.service.LocalDispatcher;
40 import org.ofbiz.service.ModelService;
41 import org.ofbiz.service.ServiceUtil;
42 import org.ofbiz.workflow.WfException;
43 import org.ofbiz.workflow.client.WorkflowClient;
44
45 /**
46  * Order Helper - Helper Methods For Non-Read Actions
47  *
48  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
49  * @version $Rev: 6536 $
50  * @since 2.0
51  */

52 public class OrderChangeHelper {
53
54     public static final String JavaDoc module = OrderChangeHelper.class.getName();
55
56     public static boolean approveOrder(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) {
57         return approveOrder(dispatcher, userLogin, orderId, false);
58     }
59
60     public static boolean approveOrder(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId, boolean holdOrder) {
61         GenericValue productStore = OrderReadHelper.getProductStoreFromOrder(dispatcher.getDelegator(), orderId);
62         if (productStore == null) {
63             throw new IllegalArgumentException JavaDoc("Could not find ProductStore for orderId [" + orderId + "], cannot approve order.");
64         }
65
66         // interal status for held orders
67
String JavaDoc HEADER_STATUS = "ORDER_PROCESSING";
68         String JavaDoc ITEM_STATUS = "ITEM_CREATED";
69         String JavaDoc DIGITAL_ITEM_STATUS = "ITEM_APPROVED";
70
71         if (!holdOrder) {
72             if (productStore.get("headerApprovedStatus") != null) {
73                 HEADER_STATUS = productStore.getString("headerApprovedStatus");
74             }
75             if (productStore.get("itemApprovedStatus") != null) {
76                 ITEM_STATUS = productStore.getString("itemApprovedStatus");
77             }
78             if (productStore.get("digitalItemApprovedStatus") != null) {
79                 DIGITAL_ITEM_STATUS = productStore.getString("digitalItemApprovedStatus");
80             }
81         }
82
83         try {
84             OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, "ITEM_CREATED", ITEM_STATUS, DIGITAL_ITEM_STATUS);
85             OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId);
86
87             /*
88             // call the service to check/run digital fulfillment
89             Map checkDigi = dispatcher.runSync("checkDigitalItemFulfillment", UtilMisc.toMap("orderId", orderId, "userLogin", userLogin));
90             // this service will return a message with success if there were any problems. Get this message and return it to the user
91             String message = (String) checkDigi.get(ModelService.SUCCESS_MESSAGE);
92             if (UtilValidate.isNotEmpty(message)) {
93                 throw new GeneralRuntimeException(message);
94             }
95             */

96         } catch (GenericServiceException e) {
97             Debug.logError(e, "Service invocation error, status changes were not updated for order #" + orderId, module);
98             return false;
99         }
100
101         return true;
102     }
103
104     public static boolean rejectOrder(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) {
105         GenericValue productStore = OrderReadHelper.getProductStoreFromOrder(dispatcher.getDelegator(), orderId);
106         String JavaDoc HEADER_STATUS = "ORDER_REJECTED";
107         String JavaDoc ITEM_STATUS = "ITEM_REJECTED";
108         if (productStore.get("headerDeclinedStatus") != null) {
109               HEADER_STATUS = productStore.getString("headerDeclinedStatus");
110           }
111           if (productStore.get("itemDeclinedStatus") != null) {
112               ITEM_STATUS = productStore.getString("itemDeclinedStatus");
113           }
114
115         try {
116             OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, null, ITEM_STATUS, null);
117             OrderChangeHelper.cancelInventoryReservations(dispatcher, userLogin, orderId);
118             OrderChangeHelper.releasePaymentAuthorizations(dispatcher, userLogin,orderId);
119             OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId);
120         } catch (GenericServiceException e) {
121             Debug.logError(e, "Service invocation error, status changes were not updated for order #" + orderId, module);
122             return false;
123         }
124         return true;
125     }
126
127     public static boolean completeOrder(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) {
128         try {
129             OrderChangeHelper.createReceivedPayments(dispatcher, userLogin, orderId);
130             OrderChangeHelper.createOrderInvoice(dispatcher, userLogin, orderId);
131             OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, "ORDER_COMPLETED", "ITEM_APPROVED", "ITEM_COMPLETED", null);
132         } catch (GenericEntityException e) {
133             Debug.logError(e, module);
134             return false;
135         } catch (GenericServiceException e) {
136             Debug.logError(e, module);
137             return false;
138         }
139         return true;
140     }
141
142     public static boolean cancelOrder(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) {
143         GenericValue productStore = OrderReadHelper.getProductStoreFromOrder(dispatcher.getDelegator(), orderId);
144         String JavaDoc HEADER_STATUS = "ORDER_CANCELLED";
145         String JavaDoc ITEM_STATUS = "ITEM_CANCELLED";
146         if (productStore.get("headerCancelStatus") != null) {
147               HEADER_STATUS = productStore.getString("headerCancelStatus");
148           }
149           if (productStore.get("itemCancelStatus") != null) {
150               ITEM_STATUS = productStore.getString("itemCancelStatus");
151           }
152
153         try {
154             OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, null, ITEM_STATUS, null);
155             OrderChangeHelper.cancelInventoryReservations(dispatcher, userLogin, orderId);
156             OrderChangeHelper.releasePaymentAuthorizations(dispatcher, userLogin,orderId);
157             OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId);
158         } catch (GenericServiceException e) {
159             Debug.logError(e, "Service invocation error, status changes were not updated for order #" + orderId, module);
160             return false;
161         }
162         return true;
163     }
164
165     public static void orderStatusChanges(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId, String JavaDoc orderStatus, String JavaDoc fromItemStatus, String JavaDoc toItemStatus, String JavaDoc digitalItemStatus) throws GenericServiceException {
166         // set the status on the order header
167
Map JavaDoc statusFields = UtilMisc.toMap("orderId", orderId, "statusId", orderStatus, "userLogin", userLogin);
168         Map JavaDoc statusResult = dispatcher.runSync("changeOrderStatus", statusFields);
169         if (statusResult.containsKey(ModelService.ERROR_MESSAGE)) {
170             Debug.logError("Problems adjusting order header status for order #" + orderId, module);
171         }
172
173         // set the status on the order item(s)
174
Map JavaDoc itemStatusFields = UtilMisc.toMap("orderId", orderId, "statusId", toItemStatus, "userLogin", userLogin);
175         if (fromItemStatus != null) {
176             itemStatusFields.put("fromStatusId", fromItemStatus);
177         }
178         Map JavaDoc itemStatusResult = dispatcher.runSync("changeOrderItemStatus", itemStatusFields);
179         if (itemStatusResult.containsKey(ModelService.ERROR_MESSAGE)) {
180             Debug.logError("Problems adjusting order item status for order #" + orderId, module);
181         }
182
183         // now set the status for digital items
184
if (digitalItemStatus != null && !digitalItemStatus.equals(toItemStatus)) {
185             GenericDelegator delegator = dispatcher.getDelegator();
186             GenericValue orderHeader = null;
187             try {
188                 orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
189             } catch (GenericEntityException e) {
190                 Debug.logError(e, "ERROR: Unable to get OrderHeader for OrderID : " + orderId, module);
191             }
192             if (orderHeader != null) {
193                 List JavaDoc orderItems = null;
194                 try {
195                     orderItems = orderHeader.getRelated("OrderItem");
196                 } catch (GenericEntityException e) {
197                     Debug.logError(e, "ERROR: Unable to get OrderItem records for OrderHeader : " + orderId, module);
198                 }
199                 if (orderItems != null && orderItems.size() > 0) {
200                     Iterator JavaDoc oii = orderItems.iterator();
201                     while (oii.hasNext()) {
202                         GenericValue orderItem = (GenericValue) oii.next();
203                         String JavaDoc orderItemSeqId = orderItem.getString("orderItemSeqId");
204                         GenericValue product = null;
205                         try {
206                             product = orderItem.getRelatedOne("Product");
207                         } catch (GenericEntityException e) {
208                             Debug.logError(e, "ERROR: Unable to get Product record for OrderItem : " + orderId + "/" + orderItemSeqId, module);
209                         }
210                         if (product != null) {
211                             GenericValue productType = null;
212                             try {
213                                 productType = product.getRelatedOne("ProductType");
214                             } catch (GenericEntityException e) {
215                                 Debug.logError(e, "ERROR: Unable to get ProductType from Product : " + product, module);
216                             }
217                             if (productType != null) {
218                                 String JavaDoc isDigital = productType.getString("isDigital");
219                                 if (isDigital != null && "Y".equalsIgnoreCase(isDigital)) {
220                                     // update the status
221
Map JavaDoc digitalStatusFields = UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "statusId", digitalItemStatus, "userLogin", userLogin);
222                                     Map JavaDoc digitalStatusChange = dispatcher.runSync("changeOrderItemStatus", digitalStatusFields);
223                                     if (ModelService.RESPOND_ERROR.equals(digitalStatusChange.get(ModelService.RESPONSE_MESSAGE))) {
224                                         Debug.logError("Problems with digital product status change : " + product, module);
225                                     }
226                                 }
227                             }
228                         }
229                     }
230                 }
231             }
232         }
233     }
234
235     public static void cancelInventoryReservations(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) throws GenericServiceException {
236         // cancel the inventory reservations
237
Map JavaDoc cancelInvFields = UtilMisc.toMap("orderId", orderId, "userLogin", userLogin);
238         Map JavaDoc cancelInvResult = dispatcher.runSync("cancelOrderInventoryReservation", cancelInvFields);
239         if (ModelService.RESPOND_ERROR.equals(cancelInvResult.get(ModelService.RESPONSE_MESSAGE))) {
240             Debug.logError("Problems reversing inventory reservations for order #" + orderId, module);
241         }
242     }
243
244     public static void releasePaymentAuthorizations(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) throws GenericServiceException {
245         Map JavaDoc releaseFields = UtilMisc.toMap("orderId", orderId, "userLogin", userLogin);
246         Map JavaDoc releaseResult = dispatcher.runSync("releaseOrderPayments", releaseFields);
247         if (ModelService.RESPOND_ERROR.equals(releaseResult.get(ModelService.RESPONSE_MESSAGE))) {
248             Debug.logError("Problems releasing payment authorizations for order #" + orderId, module);
249         }
250     }
251
252     public static void createReceivedPayments(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) throws GenericEntityException, GenericServiceException {
253         GenericValue orderHeader = null;
254         try {
255             orderHeader = dispatcher.getDelegator().findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
256         } catch (GenericEntityException e) {
257             Debug.logError(e, module);
258         }
259         if (orderHeader != null) {
260             OrderReadHelper orh = new OrderReadHelper(orderHeader);
261             GenericValue btparty = orh.getBillToParty();
262             String JavaDoc partyId = "_NA_";
263             if (btparty != null) {
264                 partyId = btparty.getString("partyId");
265             }
266
267             List JavaDoc opps = orh.getPaymentPreferences();
268             Iterator JavaDoc oppi = opps.iterator();
269             while (oppi.hasNext()) {
270                 GenericValue opp = (GenericValue) oppi.next();
271                 if ("PAYMENT_RECEIVED".equals(opp.getString("statusId"))) {
272                     List JavaDoc payments = orh.getOrderPayments(opp);
273                     if (payments == null || payments.size() == 0) {
274                         // only do this one time; if we have payment already for this pref ignore.
275
Map JavaDoc results = dispatcher.runSync("createPaymentFromPreference",
276                                 UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", opp.getString("orderPaymentPreferenceId"),
277                                 "paymentRefNum", UtilDateTime.nowTimestamp().toString(), "paymentFromId", partyId));
278                         if (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
279                             Debug.logError((String JavaDoc) results.get(ModelService.ERROR_MESSAGE), module);
280                         }
281                     }
282                 }
283             }
284         }
285     }
286
287     public static void createOrderInvoice(LocalDispatcher dispatcher, GenericValue userLogin, String JavaDoc orderId) throws GenericServiceException {
288         GenericValue orderHeader = null;
289         try {
290             orderHeader = dispatcher.getDelegator().findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
291         } catch (GenericEntityException e) {
292             Debug.logError(e, module);
293         }
294         if (orderHeader != null) {
295             OrderReadHelper orh = new OrderReadHelper(orderHeader);
296             List JavaDoc items = orh.getOrderItems();
297
298             Map JavaDoc serviceParam = UtilMisc.toMap("orderId", orderId, "billItems", items, "userLogin", userLogin);
299             Map JavaDoc serviceRes = dispatcher.runSync("createInvoiceForOrder", serviceParam);
300             if (ServiceUtil.isError(serviceRes)) {
301                 throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceRes));
302             }
303         }
304     }
305
306
307     public static boolean releaseInitialOrderHold(LocalDispatcher dispatcher, String JavaDoc orderId) {
308         // get the delegator from the dispatcher
309
GenericDelegator delegator = dispatcher.getDelegator();
310
311         // find the workEffortId for this order
312
List JavaDoc workEfforts = null;
313         try {
314             workEfforts = delegator.findByAnd("WorkEffort", UtilMisc.toMap("currentStatusId", "WF_SUSPENDED", "sourceReferenceId", orderId));
315         } catch (GenericEntityException e) {
316             Debug.logError(e, "Problems getting WorkEffort with order ref number: " + orderId, module);
317             return false;
318         }
319
320         if (workEfforts != null) {
321             // attempt to release the order workflow from 'Hold' status (resume workflow)
322
boolean allPass = true;
323             Iterator JavaDoc wei = workEfforts.iterator();
324             while (wei.hasNext()) {
325                 GenericValue workEffort = (GenericValue) wei.next();
326                 String JavaDoc workEffortId = workEffort.getString("workEffortId");
327                 try {
328                     if (workEffort.getString("currentStatusId").equals("WF_SUSPENDED")) {
329                         WorkflowClient client = new WorkflowClient(dispatcher.getDispatchContext());
330                         client.resume(workEffortId);
331                     } else {
332                         Debug.logVerbose("Current : --{" + workEffort + "}-- not resuming", module);
333                     }
334                 } catch (WfException e) {
335                     Debug.logError(e, "Problem resuming activity : " + workEffortId, module);
336                     allPass = false;
337                 }
338             }
339             return allPass;
340         } else {
341             Debug.logWarning("No WF found for order ID : " + orderId, module);
342         }
343         return false;
344     }
345
346     public static boolean abortOrderProcessing(LocalDispatcher dispatcher, String JavaDoc orderId) {
347         Debug.logInfo("Aborting workflow for order " + orderId, module);
348         GenericDelegator delegator = dispatcher.getDelegator();
349
350         // find the workEffortId for this order
351
GenericValue workEffort = null;
352         try {
353             List JavaDoc workEfforts = delegator.findByAnd("WorkEffort", UtilMisc.toMap("workEffortTypeId", "WORK_FLOW", "sourceReferenceId", orderId));
354             if (workEfforts != null && workEfforts.size() > 1) {
355                 Debug.logWarning("More then one workflow found for defined order: " + orderId, module);
356             }
357             workEffort = EntityUtil.getFirst(workEfforts);
358         } catch (GenericEntityException e) {
359             Debug.logError(e, "Problems getting WorkEffort with order ref number: " + orderId, module);
360             return false;
361         }
362
363         if (workEffort != null) {
364             String JavaDoc workEffortId = workEffort.getString("workEffortId");
365             if (workEffort.getString("currentStatusId").equals("WF_RUNNING")) {
366                 Debug.logInfo("WF is running; trying to abort", module);
367                 WorkflowClient client = new WorkflowClient(dispatcher.getDispatchContext());
368                 try {
369                     client.abortProcess(workEffortId);
370                 } catch (WfException e) {
371                     Debug.logError(e, "Problem aborting workflow", module);
372                     return false;
373                 }
374                 return true;
375             }
376         }
377         return false;
378     }
379 }
380
Popular Tags