KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: OrderReadHelper.java 7124 2006-03-30 06:19:11Z jacopo $
3  *
4  * Copyright (c) 2002-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 package org.ofbiz.order.order;
25
26 import java.math.BigDecimal JavaDoc;
27 import java.sql.Timestamp JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Arrays JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.HashSet JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.LinkedList JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Set JavaDoc;
38
39 import org.apache.commons.collections.set.ListOrderedSet;
40
41 import org.ofbiz.base.util.Debug;
42 import org.ofbiz.base.util.UtilFormatOut;
43 import org.ofbiz.base.util.UtilMisc;
44 import org.ofbiz.base.util.UtilNumber;
45 import org.ofbiz.base.util.UtilValidate;
46 import org.ofbiz.common.DataModelConstants;
47 import org.ofbiz.entity.GenericDelegator;
48 import org.ofbiz.entity.GenericEntity;
49 import org.ofbiz.entity.GenericEntityException;
50 import org.ofbiz.entity.GenericValue;
51 import org.ofbiz.entity.condition.EntityCondition;
52 import org.ofbiz.entity.condition.EntityExpr;
53 import org.ofbiz.entity.condition.EntityOperator;
54 import org.ofbiz.entity.condition.EntityConditionList;
55 import org.ofbiz.entity.util.EntityUtil;
56 import org.ofbiz.product.product.ProductWorker;
57 import org.ofbiz.security.Security;
58
59 /**
60  * Utility class for easily extracting important information from orders
61  *
62  * <p>NOTE: in the current scheme order adjustments are never included in tax or shipping,
63  * but order item adjustments ARE included in tax and shipping calcs unless they are
64  * tax or shipping adjustments or the includeInTax or includeInShipping are set to N.</p>
65  *
66  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
67  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
68  * @author Eric Pabst
69  * @author <a HREF="mailto:ray.barlow@whatsthe-point.com">Ray Barlow</a>
70  * @version $Rev: 7124 $
71  * @since 2.0
72  */

73 public class OrderReadHelper {
74
75     public static final String JavaDoc module = OrderReadHelper.class.getName();
76
77     // scales and rounding modes for BigDecimal math
78
public static final int scale = UtilNumber.getBigDecimalScale("order.decimals");
79     public static final int rounding = UtilNumber.getBigDecimalRoundingMode("order.rounding");
80     public static final int taxCalcScale = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
81     public static final int taxFinalScale = UtilNumber.getBigDecimalRoundingMode("salestax.final.decimals");
82     public static final int taxRounding = UtilNumber.getBigDecimalRoundingMode("salestax.rounding");
83     public static final BigDecimal JavaDoc ZERO = (new BigDecimal JavaDoc("0")).setScale(scale, rounding);
84
85     protected GenericValue orderHeader = null;
86     protected List JavaDoc orderItemAndShipGrp = null;
87     protected List JavaDoc orderItems = null;
88     protected List JavaDoc adjustments = null;
89     protected List JavaDoc paymentPrefs = null;
90     protected List JavaDoc orderStatuses = null;
91     protected List JavaDoc orderItemPriceInfos = null;
92     protected List JavaDoc orderItemShipGrpInvResList = null;
93     protected List JavaDoc orderItemIssuances = null;
94     protected List JavaDoc orderReturnItems = null;
95     protected BigDecimal JavaDoc totalPrice = null;
96
97     protected OrderReadHelper() {}
98
99     public OrderReadHelper(GenericValue orderHeader, List JavaDoc adjustments, List JavaDoc orderItems) {
100         this.orderHeader = orderHeader;
101         this.adjustments = adjustments;
102         this.orderItems = orderItems;
103         if (this.orderHeader != null && !this.orderHeader.getEntityName().equals("OrderHeader")) {
104             try {
105                 this.orderHeader = orderHeader.getDelegator().findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId",
106                         orderHeader.getString("orderId")));
107             } catch (GenericEntityException e) {
108                 Debug.logError(e, module);
109                 this.orderHeader = null;
110             }
111         } else if (this.orderHeader == null && orderItems != null) {
112             GenericValue firstItem = EntityUtil.getFirst(orderItems);
113             try {
114                 this.orderHeader = firstItem.getRelatedOne("OrderHeader");
115             } catch (GenericEntityException e) {
116                 Debug.logError(e, module);
117                 this.orderHeader = null;
118             }
119         }
120         if (this.orderHeader == null) {
121             throw new IllegalArgumentException JavaDoc("Order header is not valid");
122         }
123     }
124
125     public OrderReadHelper(GenericValue orderHeader) {
126         this(orderHeader, null, null);
127     }
128
129     public OrderReadHelper(List JavaDoc adjustments, List JavaDoc orderItems) {
130         this.adjustments = adjustments;
131         this.orderItems = orderItems;
132     }
133
134     public OrderReadHelper(GenericDelegator delegator, String JavaDoc orderId) {
135         try {
136             this.orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
137         } catch (GenericEntityException e) {
138             throw new IllegalArgumentException JavaDoc("Invalid orderId");
139         }
140     }
141
142     // ==========================================
143
// ========== Order Header Methods ==========
144
// ==========================================
145

146     public String JavaDoc getOrderId() {
147         return orderHeader.getString("orderId");
148     }
149
150     public String JavaDoc getWebSiteId() {
151         return orderHeader.getString("webSiteId");
152     }
153
154     public String JavaDoc getProductStoreId() {
155         return orderHeader.getString("productStoreId");
156     }
157
158     /**
159      * Returns the ProductStore of this Order or null in case of Exception
160      */

161     public GenericValue getProductStore() {
162         String JavaDoc productStoreId = orderHeader.getString("productStoreId");
163         try {
164             GenericDelegator delegator = orderHeader.getDelegator();
165             GenericValue productStore = delegator.findByPrimaryKeyCache("ProductStore", UtilMisc.toMap("productStoreId", productStoreId));
166             return productStore;
167         } catch (GenericEntityException ex) {
168             Debug.logError("Failed to get product store for order header [" + orderHeader + "] due to exception "+ ex.getMessage(), module);
169             return null;
170         }
171     }
172     
173     public String JavaDoc getOrderTypeId() {
174         return orderHeader.getString("orderTypeId");
175     }
176
177     public String JavaDoc getCurrency() {
178         return orderHeader.getString("currencyUom");
179     }
180
181     public List JavaDoc getAdjustments() {
182         if (adjustments == null) {
183             try {
184                 adjustments = orderHeader.getRelated("OrderAdjustment");
185             } catch (GenericEntityException e) {
186                 Debug.logError(e, module);
187             }
188             if (adjustments == null)
189                 adjustments = new ArrayList JavaDoc();
190         }
191         return (List JavaDoc) adjustments;
192     }
193
194     public List JavaDoc getPaymentPreferences() {
195         if (paymentPrefs == null) {
196             try {
197                 paymentPrefs = orderHeader.getRelated("OrderPaymentPreference", UtilMisc.toList("orderPaymentPreferenceId"));
198             } catch (GenericEntityException e) {
199                 Debug.logError(e, module);
200             }
201         }
202         return paymentPrefs;
203     }
204
205     public List JavaDoc getOrderPayments() {
206         return getOrderPayments(null);
207     }
208
209     public List JavaDoc getOrderPayments(GenericValue orderPaymentPreference) {
210         List JavaDoc orderPayments = new ArrayList JavaDoc();
211         List JavaDoc prefs = null;
212
213         if (orderPaymentPreference == null) {
214             prefs = getPaymentPreferences();
215         } else {
216             prefs = UtilMisc.toList(orderPaymentPreference);
217         }
218         if (prefs != null) {
219             Iterator JavaDoc i = prefs.iterator();
220             while (i.hasNext()) {
221                 GenericValue payPref = (GenericValue) i.next();
222                 try {
223                     orderPayments.addAll(payPref.getRelated("Payment"));
224                 } catch (GenericEntityException e) {
225                     Debug.logError(e, module);
226                     return null;
227                 }
228             }
229         }
230         return orderPayments;
231     }
232
233     public List JavaDoc getOrderStatuses() {
234         if (orderStatuses == null) {
235             try {
236                 orderStatuses = orderHeader.getRelated("OrderStatus");
237             } catch (GenericEntityException e) {
238                 Debug.logError(e, module);
239             }
240         }
241         return (List JavaDoc) orderStatuses;
242     }
243
244     public List JavaDoc getOrderTerms() {
245         try {
246            return orderHeader.getRelated("OrderTerm");
247         } catch (GenericEntityException e) {
248             Debug.logError(e, module);
249             return null;
250         }
251     }
252
253     /**
254      * @return Long number of days from termDays of first FIN_PAYMENT_TERM
255      */

256     public Long JavaDoc getOrderTermNetDays() {
257         List JavaDoc orderTerms = EntityUtil.filterByAnd(getOrderTerms(), UtilMisc.toMap("termTypeId", "FIN_PAYMENT_TERM"));
258         if ((orderTerms == null) || (orderTerms.size() == 0)) {
259             return null;
260         } else if (orderTerms.size() > 1) {
261             Debug.logWarning("Found " + orderTerms.size() + " FIN_PAYMENT_TERM order terms for orderId [" + getOrderId() + "], using the first one ", module);
262         }
263         return ((GenericValue) orderTerms.get(0)).getLong("termDays");
264     }
265
266     /** @deprecated */
267     public String JavaDoc getShippingMethod() {
268         throw new IllegalArgumentException JavaDoc("You must call the getShippingMethod method with the shipGroupdSeqId parameter, this is no londer supported since a single OrderShipmentPreference is no longer used.");
269     }
270
271     public String JavaDoc getShippingMethod(String JavaDoc shipGroupSeqId) {
272         try {
273             GenericValue shipGroup = orderHeader.getDelegator().findByPrimaryKey("OrderItemShipGroup",
274                     UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId));
275
276             if (shipGroup != null) {
277                 GenericValue carrierShipmentMethod = shipGroup.getRelatedOne("CarrierShipmentMethod");
278
279                 if (carrierShipmentMethod != null) {
280                     GenericValue shipmentMethodType = carrierShipmentMethod.getRelatedOne("ShipmentMethodType");
281
282                     if (shipmentMethodType != null) {
283                         return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId")) + " " +
284                                 UtilFormatOut.checkNull(shipmentMethodType.getString("description"));
285                     }
286                 }
287                 return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
288             }
289         } catch (GenericEntityException e) {
290             Debug.logWarning(e, module);
291         }
292         return "";
293     }
294
295     /** @deprecated */
296     public String JavaDoc getShippingMethodCode() {
297         throw new IllegalArgumentException JavaDoc("You must call the getShippingMethodCode method with the shipGroupdSeqId parameter, this is no londer supported since a single OrderShipmentPreference is no longer used.");
298     }
299
300     public String JavaDoc getShippingMethodCode(String JavaDoc shipGroupSeqId) {
301         try {
302             GenericValue shipGroup = orderHeader.getDelegator().findByPrimaryKey("OrderItemShipGroup",
303                     UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId));
304
305             if (shipGroup != null) {
306                 GenericValue carrierShipmentMethod = shipGroup.getRelatedOne("CarrierShipmentMethod");
307
308                 if (carrierShipmentMethod != null) {
309                     GenericValue shipmentMethodType = carrierShipmentMethod.getRelatedOne("ShipmentMethodType");
310
311                     if (shipmentMethodType != null) {
312                         return UtilFormatOut.checkNull(shipmentMethodType.getString("shipmentMethodTypeId")) + "@" + UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
313                     }
314                 }
315                 return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
316             }
317         } catch (GenericEntityException e) {
318             Debug.logWarning(e, module);
319         }
320         return "";
321     }
322
323     public boolean hasShippingAddress() {
324         if (UtilValidate.isNotEmpty(this.getShippingLocations())) {
325             return true;
326         }
327         return false;
328     }
329
330     public GenericValue getOrderItemShipGroup(String JavaDoc shipGroupSeqId) {
331         try {
332             return orderHeader.getDelegator().findByPrimaryKey("OrderItemShipGroup",
333                     UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId));
334         } catch (GenericEntityException e) {
335             Debug.logWarning(e, module);
336         }
337         return null;
338     }
339
340     public List JavaDoc getOrderItemShipGroups() {
341         try {
342             return orderHeader.getRelated("OrderItemShipGroup", UtilMisc.toList("shipGroupSeqId"));
343         } catch (GenericEntityException e) {
344             Debug.logWarning(e, module);
345         }
346         return null;
347     }
348
349     public List JavaDoc getShippingLocations() {
350         List JavaDoc shippingLocations = new LinkedList JavaDoc();
351         List JavaDoc shippingCms = this.getOrderContactMechs("SHIPPING_LOCATION");
352         if (shippingCms != null) {
353             Iterator JavaDoc i = shippingCms.iterator();
354             while (i.hasNext()) {
355                 GenericValue ocm = (GenericValue) i.next();
356                 if (ocm != null) {
357                     try {
358                         GenericValue addr = ocm.getDelegator().findByPrimaryKey("PostalAddress",
359                                 UtilMisc.toMap("contactMechId", ocm.getString("contactMechId")));
360                         if (addr != null) {
361                             shippingLocations.add(addr);
362                         }
363                     } catch (GenericEntityException e) {
364                         Debug.logWarning(e, module);
365                     }
366                 }
367             }
368         }
369         return shippingLocations;
370     }
371
372     public GenericValue getShippingAddress(String JavaDoc shipGroupSeqId) {
373         try {
374             GenericValue shipGroup = orderHeader.getDelegator().findByPrimaryKey("OrderItemShipGroup",
375                     UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId));
376
377             if (shipGroup != null) {
378                 return shipGroup.getRelatedOne("PostalAddress");
379
380             }
381         } catch (GenericEntityException e) {
382             Debug.logWarning(e, module);
383         }
384         return null;
385     }
386
387     /** @deprecated */
388     public GenericValue getShippingAddress() {
389         try {
390             GenericValue orderContactMech = EntityUtil.getFirst(orderHeader.getRelatedByAnd("OrderContactMech", UtilMisc.toMap(
391                             "contactMechPurposeTypeId", "SHIPPING_LOCATION")));
392
393             if (orderContactMech != null) {
394                 GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech");
395
396                 if (contactMech != null) {
397                     return contactMech.getRelatedOne("PostalAddress");
398                 }
399             }
400         } catch (GenericEntityException e) {
401             Debug.logWarning(e, module);
402         }
403         return null;
404     }
405
406     public List JavaDoc getBillingLocations() {
407         List JavaDoc billingLocations = new LinkedList JavaDoc();
408         List JavaDoc billingCms = this.getOrderContactMechs("BILLING_LOCATION");
409         if (billingCms != null) {
410             Iterator JavaDoc i = billingCms.iterator();
411             while (i.hasNext()) {
412                 GenericValue ocm = (GenericValue) i.next();
413                 if (ocm != null) {
414                     try {
415                         GenericValue addr = ocm.getDelegator().findByPrimaryKey("PostalAddress",
416                                 UtilMisc.toMap("contactMechId", ocm.getString("contactMechId")));
417                         if (addr != null) {
418                             billingLocations.add(addr);
419                         }
420                     } catch (GenericEntityException e) {
421                         Debug.logWarning(e, module);
422                     }
423                 }
424             }
425         }
426         return billingLocations;
427     }
428
429     /** @deprecated */
430     public GenericValue getBillingAddress() {
431         GenericValue billingAddress = null;
432         try {
433             GenericValue orderContactMech = EntityUtil.getFirst(orderHeader.getRelatedByAnd("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION")));
434
435             if (orderContactMech != null) {
436                 GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech");
437
438                 if (contactMech != null) {
439                     billingAddress = contactMech.getRelatedOne("PostalAddress");
440                 }
441             }
442         } catch (GenericEntityException e) {
443             Debug.logWarning(e, module);
444         }
445
446         if (billingAddress == null) {
447             // get the address from the billing account
448
GenericValue billingAccount = getBillingAccount();
449             if (billingAccount != null) {
450                 try {
451                     billingAddress = billingAccount.getRelatedOne("PostalAddress");
452                 } catch (GenericEntityException e) {
453                     Debug.logWarning(e, module);
454                 }
455             } else {
456                 // get the address from the first payment method
457
GenericValue paymentPreference = EntityUtil.getFirst(getPaymentPreferences());
458                 if (paymentPreference != null) {
459                     try {
460                         GenericValue paymentMethod = paymentPreference.getRelatedOne("PaymentMethod");
461                         if (paymentMethod != null) {
462                             GenericValue creditCard = paymentMethod.getRelatedOne("CreditCard");
463                             if (creditCard != null) {
464                                 billingAddress = creditCard.getRelatedOne("PostalAddress");
465                             } else {
466                                 GenericValue eftAccount = paymentMethod.getRelatedOne("EftAccount");
467                                 if (eftAccount != null) {
468                                     billingAddress = eftAccount.getRelatedOne("PostalAddress");
469                                 }
470                             }
471                         }
472                     } catch (GenericEntityException e) {
473                         Debug.logWarning(e, module);
474                     }
475                 }
476             }
477         }
478         return billingAddress;
479     }
480
481     public List JavaDoc getOrderContactMechs(String JavaDoc purposeTypeId) {
482         try {
483             return orderHeader.getRelatedByAnd("OrderContactMech",
484                     UtilMisc.toMap("contactMechPurposeTypeId", purposeTypeId));
485         } catch (GenericEntityException e) {
486             Debug.logWarning(e, module);
487         }
488         return null;
489     }
490
491     public Timestamp JavaDoc getEarliestShipByDate() {
492         try {
493             List JavaDoc groups = orderHeader.getRelated("OrderItemShipGroup", UtilMisc.toList("shipByDate DESC"));
494             if (groups.size() > 0) {
495                 GenericValue group = (GenericValue) groups.get(0);
496                 return group.getTimestamp("shipByDate");
497             }
498         } catch (GenericEntityException e) {
499             Debug.logWarning(e, module);
500         }
501         return null;
502     }
503
504     public Timestamp JavaDoc getEarliestShipAfterDate() {
505         try {
506             List JavaDoc groups = orderHeader.getRelated("OrderItemShipGroup", UtilMisc.toList("shipAfterDate DESC"));
507             if (groups.size() > 0) {
508                 GenericValue group = (GenericValue) groups.get(0);
509                 return group.getTimestamp("shipAfterDate");
510             }
511         } catch (GenericEntityException e) {
512             Debug.logWarning(e, module);
513         }
514         return null;
515     }
516
517     public String JavaDoc getCurrentStatusString() {
518         GenericValue statusItem = null;
519         try {
520             statusItem = orderHeader.getRelatedOneCache("StatusItem");
521         } catch (GenericEntityException e) {
522             Debug.logError(e, module);
523         }
524         if (statusItem != null) {
525             return statusItem.getString("description");
526         } else {
527             return orderHeader.getString("statusId");
528         }
529     }
530
531     public String JavaDoc getStatusString() {
532         List JavaDoc orderStatusList = this.getOrderHeaderStatuses();
533
534         if (orderStatusList == null || orderStatusList.size() == 0) return "";
535
536         Iterator JavaDoc orderStatusIter = orderStatusList.iterator();
537         StringBuffer JavaDoc orderStatusString = new StringBuffer JavaDoc(50);
538
539         try {
540             boolean isCurrent = true;
541             while (orderStatusIter.hasNext()) {
542                 GenericValue orderStatus = (GenericValue) orderStatusIter.next();
543                 GenericValue statusItem = orderStatus.getRelatedOneCache("StatusItem");
544
545                 if (statusItem != null) {
546                     orderStatusString.append(statusItem.getString("description"));
547                 } else {
548                     orderStatusString.append(orderStatus.getString("statusId"));
549                 }
550
551                 if (isCurrent && orderStatusIter.hasNext()) {
552                     orderStatusString.append(" (");
553                     isCurrent = false;
554                 } else {
555                     if (orderStatusIter.hasNext()) {
556                         orderStatusString.append("/");
557                     } else {
558                         if (!isCurrent) {
559                             orderStatusString.append(")");
560                         }
561                     }
562                 }
563             }
564         } catch (GenericEntityException e) {
565             Debug.logError(e, "Error getting Order Status information: " + e.toString(), module);
566         }
567
568         return orderStatusString.toString();
569     }
570
571     public GenericValue getBillingAccount() {
572         GenericValue billingAccount = null;
573         try {
574             billingAccount = orderHeader.getRelatedOne("BillingAccount");
575         } catch (GenericEntityException e) {
576             Debug.logError(e, module);
577         }
578         return billingAccount;
579     }
580
581     /**
582      * Returns the OrderPaymentPreference.maxAmount for the billing account associated with the order, or 0 if there is no
583      * billing account or no max amount set
584      */

585     public double getBillingAccountMaxAmount() {
586         if (getBillingAccount() == null) {
587             return 0.0;
588         } else {
589             List JavaDoc paymentPreferences = getPaymentPreferences();
590             GenericValue billingAccountPaymentPreference = EntityUtil.getFirst(EntityUtil.filterByAnd(paymentPreferences, UtilMisc.toMap("paymentMethodTypeId", "EXT_BILLACT")));
591             if ((billingAccountPaymentPreference != null) && (billingAccountPaymentPreference.getDouble("maxAmount") != null)) {
592                 return billingAccountPaymentPreference.getDouble("maxAmount").doubleValue();
593             } else {
594                 return 0.0;
595             }
596         }
597     }
598
599     /**
600      * Returns party from OrderRole of BILL_TO_CUSTOMER
601      */

602     public GenericValue getBillToParty() {
603         return this.getPartyFromRole("BILL_TO_CUSTOMER");
604     }
605
606     /**
607      * Returns bill from party based on BILL_FROM_VENDOR in OrderRole. If not found, then use the Order's ProductStore payToPartyId
608      */

609     public GenericValue getBillFromParty() {
610         GenericValue billFromParty = this.getPartyFromRole("BILL_FROM_VENDOR");
611         if (billFromParty == null) {
612             GenericValue productStore = getProductStore();
613             if (productStore != null) {
614                 try {
615                     return productStore.getRelatedOneCache("Party");
616                 } catch (GenericEntityException ex) {
617                     Debug.logError("Failed to get Pay to Party of ProductStore for OrderHeader [" + orderHeader +" ] due to exception " + ex.getMessage(), module);
618                     return null;
619                 }
620             } else {
621                 return null;
622             }
623         } else {
624             return this.getPartyFromRole("BILL_FROM_VENDOR");
625         }
626     }
627
628     /**
629      * Returns party from OrderRole of SHIP_TO_CUSTOMER
630      */

631     public GenericValue getShipToParty() {
632         return this.getPartyFromRole("SHIP_TO_CUSTOMER");
633     }
634
635     /**
636      * Returns party from OrderRole of PLACING_CUSTOMER
637      */

638     public GenericValue getPlacingParty() {
639         return this.getPartyFromRole("PLACING_CUSTOMER");
640     }
641
642     /**
643      * Returns party from OrderRole of END_USER_CUSTOMER
644      */

645     public GenericValue getEndUserParty() {
646         return this.getPartyFromRole("END_USER_CUSTOMER");
647     }
648
649     /**
650      * Returns party from OrderRole of SUPPLIER_AGENT
651      */

652     public GenericValue getSupplierAgent() {
653         return this.getPartyFromRole("SUPPLIER_AGENT");
654     }
655
656     public GenericValue getPartyFromRole(String JavaDoc roleTypeId) {
657         GenericDelegator delegator = orderHeader.getDelegator();
658         GenericValue partyObject = null;
659         try {
660             GenericValue orderRole = EntityUtil.getFirst(orderHeader.getRelatedByAnd("OrderRole", UtilMisc.toMap("roleTypeId", roleTypeId)));
661
662             if (orderRole != null) {
663                 partyObject = delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", orderRole.getString("partyId")));
664
665                 if (partyObject == null) {
666                     partyObject = delegator.findByPrimaryKey("PartyGroup", UtilMisc.toMap("partyId", orderRole.getString("partyId")));
667                 }
668             }
669         } catch (GenericEntityException e) {
670             Debug.logError(e, module);
671         }
672         return partyObject;
673     }
674
675     public String JavaDoc getDistributorId() {
676         try {
677             GenericEntity distributorRole = EntityUtil.getFirst(orderHeader.getRelatedByAnd("OrderRole", UtilMisc.toMap("roleTypeId", "DISTRIBUTOR")));
678
679             return distributorRole == null ? null : distributorRole.getString("partyId");
680         } catch (GenericEntityException e) {
681             Debug.logWarning(e, module);
682         }
683         return null;
684     }
685
686     public String JavaDoc getAffiliateId() {
687         try {
688             GenericEntity distributorRole = EntityUtil.getFirst(orderHeader.getRelatedByAnd("OrderRole", UtilMisc.toMap("roleTypeId", "AFFILIATE")));
689
690             return distributorRole == null ? null : distributorRole.getString("partyId");
691         } catch (GenericEntityException e) {
692             Debug.logWarning(e, module);
693         }
694         return null;
695     }
696
697     public BigDecimal JavaDoc getShippingTotalBd() {
698         return OrderReadHelper.calcOrderAdjustmentsBd(getOrderHeaderAdjustments(), getOrderItemsSubTotalBd(), false, false, true);
699     }
700
701     /** @deprecated Use getShippingTotalBd() instead */
702     public double getShippingTotal() {
703         return getShippingTotalBd().doubleValue();
704     }
705
706     public BigDecimal JavaDoc getHeaderTaxTotalBd() {
707         return OrderReadHelper.calcOrderAdjustmentsBd(getOrderHeaderAdjustments(), getOrderItemsSubTotalBd(), false, true, false);
708     }
709
710     /** @deprecated Use getHeaderTaxTotalBd() instead */
711     public double getHeaderTaxTotal() {
712         return getHeaderTaxTotalBd().doubleValue();
713     }
714
715     public BigDecimal JavaDoc getTaxTotalBd() {
716         return OrderReadHelper.calcOrderAdjustmentsBd(getAdjustments(), getOrderItemsSubTotalBd(), false, true, false);
717     }
718
719     /** @deprecated Use getTaxTotalBd() instead */
720     public double getTaxTotal() {
721         return getTaxTotalBd().doubleValue();
722     }
723
724     public Set JavaDoc getItemFeatureSet(GenericValue item) {
725         Set JavaDoc featureSet = new ListOrderedSet();
726         List JavaDoc featureAppls = null;
727         if (item.get("productId") != null) {
728             try {
729                 featureAppls = item.getDelegator().findByAndCache("ProductFeatureAppl", UtilMisc.toMap("productId", item.getString("productId")));
730                 List JavaDoc filterExprs = UtilMisc.toList(new EntityExpr("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
731                 filterExprs.add(new EntityExpr("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
732                 featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
733             } catch (GenericEntityException e) {
734                 Debug.logError(e, "Unable to get ProductFeatureAppl for item : " + item, module);
735             }
736             if (featureAppls != null) {
737                 Iterator JavaDoc fai = featureAppls.iterator();
738                 while (fai.hasNext()) {
739                     GenericValue appl = (GenericValue) fai.next();
740                     featureSet.add(appl.getString("productFeatureId"));
741                 }
742             }
743         }
744
745         // get the ADDITIONAL_FEATURE adjustments
746
List JavaDoc additionalFeatures = null;
747         try {
748             additionalFeatures = item.getRelatedByAnd("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "ADDITIONAL_FEATURE"));
749         } catch (GenericEntityException e) {
750             Debug.logError(e, "Unable to get OrderAdjustment from item : " + item, module);
751         }
752         if (additionalFeatures != null) {
753             Iterator JavaDoc afi = additionalFeatures.iterator();
754             while (afi.hasNext()) {
755                 GenericValue adj = (GenericValue) afi.next();
756                 String JavaDoc featureId = adj.getString("productFeatureId");
757                 if (featureId != null) {
758                     featureSet.add(featureId);
759                 }
760             }
761         }
762
763         return featureSet;
764     }
765
766     public Map JavaDoc getFeatureIdQtyMap(String JavaDoc shipGroupSeqId) {
767         Map JavaDoc featureMap = new HashMap JavaDoc();
768         List JavaDoc validItems = getValidOrderItems(shipGroupSeqId);
769         if (validItems != null) {
770             Iterator JavaDoc i = validItems.iterator();
771             while (i.hasNext()) {
772                 GenericValue item = (GenericValue) i.next();
773                 List JavaDoc featureAppls = null;
774                 if (item.get("productId") != null) {
775                     try {
776                         featureAppls = item.getDelegator().findByAndCache("ProductFeatureAppl", UtilMisc.toMap("productId", item.getString("productId")));
777                         List JavaDoc filterExprs = UtilMisc.toList(new EntityExpr("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
778                         filterExprs.add(new EntityExpr("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
779                         featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
780                     } catch (GenericEntityException e) {
781                         Debug.logError(e, "Unable to get ProductFeatureAppl for item : " + item, module);
782                     }
783                     if (featureAppls != null) {
784                         Iterator JavaDoc fai = featureAppls.iterator();
785                         while (fai.hasNext()) {
786                             GenericValue appl = (GenericValue) fai.next();
787                             Double JavaDoc lastQuantity = (Double JavaDoc) featureMap.get(appl.getString("productFeatureId"));
788                             if (lastQuantity == null) {
789                                 lastQuantity = new Double JavaDoc(0);
790                             }
791                             Double JavaDoc newQuantity = new Double JavaDoc(lastQuantity.doubleValue() + getOrderItemQuantity(item).doubleValue());
792                             featureMap.put(appl.getString("productFeatureId"), newQuantity);
793                         }
794                     }
795                 }
796
797                 // get the ADDITIONAL_FEATURE adjustments
798
List JavaDoc additionalFeatures = null;
799                 try {
800                     additionalFeatures = item.getRelatedByAnd("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "ADDITIONAL_FEATURE"));
801                 } catch (GenericEntityException e) {
802                     Debug.logError(e, "Unable to get OrderAdjustment from item : " + item, module);
803                 }
804                 if (additionalFeatures != null) {
805                     Iterator JavaDoc afi = additionalFeatures.iterator();
806                     while (afi.hasNext()) {
807                         GenericValue adj = (GenericValue) afi.next();
808                         String JavaDoc featureId = adj.getString("productFeatureId");
809                         if (featureId != null) {
810                             Double JavaDoc lastQuantity = (Double JavaDoc) featureMap.get(featureId);
811                             if (lastQuantity == null) {
812                                 lastQuantity = new Double JavaDoc(0);
813                             }
814                             Double JavaDoc newQuantity = new Double JavaDoc(lastQuantity.doubleValue() + getOrderItemQuantity(item).doubleValue());
815                             featureMap.put(featureId, newQuantity);
816                         }
817                     }
818                 }
819             }
820         }
821
822         return featureMap;
823     }
824
825     public boolean shippingApplies() {
826         boolean shippingApplies = false;
827         List JavaDoc validItems = this.getValidOrderItems();
828         if (validItems != null) {
829             Iterator JavaDoc i = validItems.iterator();
830             while (i.hasNext()) {
831                 GenericValue item = (GenericValue) i.next();
832                 GenericValue product = null;
833                 try {
834                     product = item.getRelatedOne("Product");
835                 } catch (GenericEntityException e) {
836                     Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
837                 }
838                 if (product != null) {
839                     if (ProductWorker.shippingApplies(product)) {
840                         shippingApplies = true;
841                         break;
842                     }
843                 }
844             }
845         }
846         return shippingApplies;
847     }
848
849     public boolean taxApplies() {
850         boolean taxApplies = false;
851         List JavaDoc validItems = this.getValidOrderItems();
852         if (validItems != null) {
853             Iterator JavaDoc i = validItems.iterator();
854             while (i.hasNext()) {
855                 GenericValue item = (GenericValue) i.next();
856                 GenericValue product = null;
857                 try {
858                     product = item.getRelatedOne("Product");
859                 } catch (GenericEntityException e) {
860                     Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
861                 }
862                 if (product != null) {
863                     if (ProductWorker.taxApplies(product)) {
864                         taxApplies = true;
865                         break;
866                     }
867                 }
868             }
869         }
870         return taxApplies;
871     }
872
873     public BigDecimal JavaDoc getShippableTotalBd(String JavaDoc shipGroupSeqId) {
874         BigDecimal JavaDoc shippableTotal = ZERO;
875         List JavaDoc validItems = getValidOrderItems(shipGroupSeqId);
876         if (validItems != null) {
877             Iterator JavaDoc i = validItems.iterator();
878             while (i.hasNext()) {
879                 GenericValue item = (GenericValue) i.next();
880                 GenericValue product = null;
881                 try {
882                     product = item.getRelatedOne("Product");
883                 } catch (GenericEntityException e) {
884                     Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
885                     return ZERO;
886                 }
887                 if (product != null) {
888                     if (ProductWorker.shippingApplies(product)) {
889                         shippableTotal = shippableTotal.add(OrderReadHelper.getOrderItemSubTotalBd(item, getAdjustments(), false, true)).setScale(scale, rounding);
890                     }
891                 }
892             }
893         }
894         return shippableTotal.setScale(scale, rounding);
895     }
896
897     /** @deprecated Use getShippableTotalBd() instead */
898     public double getShippableTotal(String JavaDoc shipGroupSeqId) {
899         return getShippableTotalBd(shipGroupSeqId).doubleValue();
900     }
901
902     public BigDecimal JavaDoc getShippableQuantityBd(String JavaDoc shipGroupSeqId) {
903         BigDecimal JavaDoc shippableQuantity = ZERO;
904         List JavaDoc validItems = getValidOrderItems(shipGroupSeqId);
905         if (validItems != null) {
906             Iterator JavaDoc i = validItems.iterator();
907             while (i.hasNext()) {
908                 GenericValue item = (GenericValue) i.next();
909                 GenericValue product = null;
910                 try {
911                     product = item.getRelatedOne("Product");
912                 } catch (GenericEntityException e) {
913                     Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
914                     return ZERO;
915                 }
916                 if (product != null) {
917                     if (ProductWorker.shippingApplies(product)) {
918                         shippableQuantity =shippableQuantity.add(getOrderItemQuantityBd(item)).setScale(scale, rounding);
919                     }
920                 }
921             }
922         }
923         return shippableQuantity.setScale(scale, rounding);
924     }
925
926     /** @deprecated Use getShippableQuantityBd() instead */
927     public double getShippableQuantity(String JavaDoc shipGroupSeqId) {
928         return getShippableQuantityBd(shipGroupSeqId).doubleValue();
929     }
930
931     public BigDecimal JavaDoc getShippableWeightBd(String JavaDoc shipGroupSeqId) {
932         BigDecimal JavaDoc shippableWeight = ZERO;
933         List JavaDoc validItems = getValidOrderItems(shipGroupSeqId);
934         if (validItems != null) {
935             Iterator JavaDoc i = validItems.iterator();
936             while (i.hasNext()) {
937                 GenericValue item = (GenericValue) i.next();
938                 shippableWeight = shippableWeight.add(this.getItemWeightBd(item).multiply( getOrderItemQuantityBd(item))).setScale(scale, rounding);
939             }
940         }
941
942         return shippableWeight.setScale(scale, rounding);
943     }
944
945     /** @deprecated Use getShippableWeightBd() instead */
946     public double getShippableWeight(String JavaDoc shipGroupSeqId) {
947         return getShippableWeightBd(shipGroupSeqId).doubleValue();
948     }
949
950     public BigDecimal JavaDoc getItemWeightBd(GenericValue item) {
951         GenericDelegator delegator = orderHeader.getDelegator();
952         BigDecimal JavaDoc itemWeight = ZERO;
953
954         GenericValue product = null;
955         try {
956             product = item.getRelatedOne("Product");
957         } catch (GenericEntityException e) {
958             Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
959             return new BigDecimal JavaDoc ("0.00");
960         }
961         if (product != null) {
962             if (ProductWorker.shippingApplies(product)) {
963                 BigDecimal JavaDoc weight = product.getBigDecimal("weight");
964                 String JavaDoc isVariant = product.getString("isVariant");
965                 if (weight == null && "Y".equals(isVariant)) {
966                     // get the virtual product and check its weight
967
try {
968                         String JavaDoc virtualId = ProductWorker.getVariantVirtualId(product);
969                         if (UtilValidate.isNotEmpty(virtualId)) {
970                             GenericValue virtual = delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", virtualId));
971                             if (virtual != null) {
972                                 weight = virtual.getBigDecimal("weight");
973                             }
974                         }
975                     } catch (GenericEntityException e) {
976                         Debug.logError(e, "Problem getting virtual product");
977                     }
978                 }
979
980                 if (weight != null) {
981                     itemWeight = weight;
982                 }
983             }
984         }
985
986         return itemWeight;
987     }
988
989     /** @deprecated Use getItemWeightBd() instead */
990     public double getItemWeight(GenericValue item) {
991         return getItemWeightBd(item).doubleValue();
992     }
993
994     public List JavaDoc getShippableSizes() {
995         List JavaDoc shippableSizes = new LinkedList JavaDoc();
996
997         List JavaDoc validItems = getValidOrderItems();
998         if (validItems != null) {
999             Iterator JavaDoc i = validItems.iterator();
1000            while (i.hasNext()) {
1001                GenericValue item = (GenericValue) i.next();
1002                shippableSizes.add(new Double JavaDoc(this.getItemSize(item)));
1003            }
1004        }
1005        return shippableSizes;
1006    }
1007
1008    // TODO: Might want to use BigDecimal here if precision matters
1009
public double getItemSize(GenericValue item) {
1010        GenericDelegator delegator = orderHeader.getDelegator();
1011        double size = 0;
1012
1013        GenericValue product = null;
1014        try {
1015            product = item.getRelatedOne("Product");
1016        } catch (GenericEntityException e) {
1017            Debug.logError(e, "Problem getting Product from OrderItem", module);
1018            return 0;
1019        }
1020        if (product != null) {
1021            if (ProductWorker.shippingApplies(product)) {
1022                Double JavaDoc height = product.getDouble("shippingHeight");
1023                Double JavaDoc width = product.getDouble("shippingWidth");
1024                Double JavaDoc depth = product.getDouble("shippingDepth");
1025                String JavaDoc isVariant = product.getString("isVariant");
1026                if ((height == null || width == null || depth == null) && "Y".equals(isVariant)) {
1027                    // get the virtual product and check its values
1028
try {
1029                        String JavaDoc virtualId = ProductWorker.getVariantVirtualId(product);
1030                        if (UtilValidate.isNotEmpty(virtualId)) {
1031                            GenericValue virtual = delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", virtualId));
1032                            if (virtual != null) {
1033                                if (height == null) height = virtual.getDouble("shippingHeight");
1034                                if (width == null) width = virtual.getDouble("shippingWidth");
1035                                if (depth == null) depth = virtual.getDouble("shippingDepth");
1036                            }
1037                        }
1038                    } catch (GenericEntityException e) {
1039                        Debug.logError(e, "Problem getting virtual product");
1040                    }
1041                }
1042
1043                if (height == null) height = new Double JavaDoc(0);
1044                if (width == null) width = new Double JavaDoc(0);
1045                if (depth == null) depth = new Double JavaDoc(0);
1046
1047                // determine girth (longest field is length)
1048
double[] sizeInfo = { height.doubleValue(), width.doubleValue(), depth.doubleValue() };
1049                Arrays.sort(sizeInfo);
1050
1051                size = (sizeInfo[0] * 2) + (sizeInfo[1] * 2) + sizeInfo[2];
1052            }
1053        }
1054
1055        return size;
1056    }
1057
1058    public long getItemPiecesIncluded(GenericValue item) {
1059        GenericDelegator delegator = orderHeader.getDelegator();
1060        long piecesIncluded = 1;
1061
1062        GenericValue product = null;
1063        try {
1064            product = item.getRelatedOne("Product");
1065        } catch (GenericEntityException e) {
1066            Debug.logError(e, "Problem getting Product from OrderItem; returning 1", module);
1067            return 1;
1068        }
1069        if (product != null) {
1070            if (ProductWorker.shippingApplies(product)) {
1071                Long JavaDoc pieces = product.getLong("piecesIncluded");
1072                String JavaDoc isVariant = product.getString("isVariant");
1073                if (pieces == null && isVariant != null && "Y".equals(isVariant)) {
1074                    // get the virtual product and check its weight
1075
GenericValue virtual = null;
1076                    try {
1077                        List JavaDoc virtuals = delegator.findByAnd("ProductAssoc", UtilMisc.toMap("productIdTo", product.getString("productId"), "productAssocTypeId", "PRODUCT_VARIANT"), UtilMisc.toList("-fromDate"));
1078                        if (virtuals != null) {
1079                            virtuals = EntityUtil.filterByDate(virtuals);
1080                        }
1081                        virtual = EntityUtil.getFirst(virtuals);
1082                    } catch (GenericEntityException e) {
1083                        Debug.logError(e, "Problem getting virtual product");
1084                    }
1085                    if (virtual != null) {
1086                        pieces = virtual.getLong("piecesIncluded");
1087                    }
1088                }
1089
1090                if (pieces != null) {
1091                    piecesIncluded = pieces.longValue();
1092                }
1093            }
1094        }
1095
1096        return piecesIncluded;
1097    }
1098
1099   public List JavaDoc getShippableItemInfo(String JavaDoc shipGroupSeqId) {
1100        List JavaDoc shippableInfo = new LinkedList JavaDoc();
1101
1102        List JavaDoc validItems = getValidOrderItems(shipGroupSeqId);
1103        if (validItems != null) {
1104            Iterator JavaDoc i = validItems.iterator();
1105            while (i.hasNext()) {
1106                GenericValue item = (GenericValue) i.next();
1107                shippableInfo.add(this.getItemInfoMap(item));
1108            }
1109        }
1110
1111        return shippableInfo;
1112    }
1113
1114    public Map JavaDoc getItemInfoMap(GenericValue item) {
1115        Map JavaDoc itemInfo = new HashMap JavaDoc();
1116        itemInfo.put("productId", item.getString("productId"));
1117        itemInfo.put("quantity", getOrderItemQuantity(item));
1118        itemInfo.put("weight", new Double JavaDoc(this.getItemWeight(item)));
1119        itemInfo.put("size", new Double JavaDoc(this.getItemSize(item)));
1120        itemInfo.put("piecesIncluded", new Long JavaDoc(this.getItemPiecesIncluded(item)));
1121        itemInfo.put("featureSet", this.getItemFeatureSet(item));
1122        return itemInfo;
1123    }
1124
1125    public String JavaDoc getOrderEmailString() {
1126        GenericDelegator delegator = orderHeader.getDelegator();
1127        // get the email addresses from the order contact mech(s)
1128
List JavaDoc orderContactMechs = null;
1129        try {
1130            Map JavaDoc ocFields = UtilMisc.toMap("orderId", orderHeader.get("orderId"), "contactMechPurposeTypeId", "ORDER_EMAIL");
1131            orderContactMechs = delegator.findByAnd("OrderContactMech", ocFields);
1132        } catch (GenericEntityException e) {
1133            Debug.logWarning(e, "Problems getting order contact mechs", module);
1134        }
1135
1136        StringBuffer JavaDoc emails = new StringBuffer JavaDoc();
1137        if (orderContactMechs != null) {
1138            Iterator JavaDoc oci = orderContactMechs.iterator();
1139            while (oci.hasNext()) {
1140                try {
1141                    GenericValue orderContactMech = (GenericValue) oci.next();
1142                    GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech");
1143                    emails.append(emails.length() > 0 ? "," : "").append(contactMech.getString("infoString"));
1144                } catch (GenericEntityException e) {
1145                    Debug.logWarning(e, "Problems getting contact mech from order contact mech", module);
1146                }
1147            }
1148        }
1149        return emails.toString();
1150    }
1151
1152    public BigDecimal JavaDoc getOrderGrandTotalBd() {
1153        if (totalPrice == null) {
1154            totalPrice = getOrderGrandTotalBd(getValidOrderItems(), getAdjustments());
1155        }// else already set
1156
return totalPrice;
1157    }
1158
1159    /** @deprecated Use getOrderGrandTotalBd() instead */
1160    public double getOrderGrandTotal() {
1161        return getOrderGrandTotalBd().doubleValue();
1162    }
1163
1164    public List JavaDoc getOrderHeaderAdjustments() {
1165        return getOrderHeaderAdjustments(getAdjustments(), null);
1166    }
1167
1168    public List JavaDoc getOrderHeaderAdjustments(String JavaDoc shipGroupSeqId) {
1169        return getOrderHeaderAdjustments(getAdjustments(), shipGroupSeqId);
1170    }
1171
1172    public List JavaDoc getOrderHeaderAdjustmentsToShow() {
1173        return filterOrderAdjustments(getOrderHeaderAdjustments(), true, false, false, false, false);
1174    }
1175
1176    public List JavaDoc getOrderHeaderStatuses() {
1177        return getOrderHeaderStatuses(getOrderStatuses());
1178    }
1179
1180    public BigDecimal JavaDoc getOrderAdjustmentsTotalBd() {
1181        return getOrderAdjustmentsTotalBd(getValidOrderItems(), getAdjustments());
1182    }
1183
1184    /** @deprecated Use getOrderAdjustmentsTotalBd() instead */
1185    public double getOrderAdjustmentsTotal() {
1186        return getOrderAdjustmentsTotalBd().doubleValue();
1187    }
1188
1189    public BigDecimal JavaDoc getOrderAdjustmentTotalBd(GenericValue adjustment) {
1190        return calcOrderAdjustmentBd(adjustment, getOrderItemsSubTotalBd());
1191    }
1192
1193    /** @deprecated Use getOrderAdjustmentsTotalBd() instead */
1194    public double getOrderAdjustmentTotal(GenericValue adjustment) {
1195        return getOrderAdjustmentTotalBd(adjustment).doubleValue();
1196    }
1197
1198    public int hasSurvey() {
1199        GenericDelegator delegator = orderHeader.getDelegator();
1200        List JavaDoc surveys = null;
1201        try {
1202            surveys = delegator.findByAnd("SurveyResponse", UtilMisc.toMap("orderId", orderHeader.getString("orderId")));
1203        } catch (GenericEntityException e) {
1204            Debug.logError(e, module);
1205        }
1206        int size = 0;
1207        if (surveys != null) {
1208            size = surveys.size();
1209        }
1210
1211        return size;
1212    }
1213
1214    // ========================================
1215
// ========== Order Item Methods ==========
1216
// ========================================
1217

1218    public List JavaDoc getOrderItems() {
1219        if (orderItems == null) {
1220            try {
1221                orderItems = orderHeader.getRelated("OrderItem", UtilMisc.toList("orderItemSeqId"));
1222            } catch (GenericEntityException e) {
1223                Debug.logWarning(e, module);
1224            }
1225        }
1226        return orderItems;
1227    }
1228
1229    public List JavaDoc getOrderItemAndShipGroupAssoc() {
1230        if (orderItemAndShipGrp == null) {
1231            try {
1232                orderItemAndShipGrp = orderHeader.getDelegator().findByAnd("OrderItemAndShipGroupAssoc",
1233                        UtilMisc.toMap("orderId", orderHeader.getString("orderId")));
1234            } catch (GenericEntityException e) {
1235                Debug.logWarning(e, module);
1236            }
1237        }
1238        return orderItemAndShipGrp;
1239    }
1240
1241    public List JavaDoc getOrderItemAndShipGroupAssoc(String JavaDoc shipGroupSeqId) {
1242        List JavaDoc exprs = UtilMisc.toList(new EntityExpr("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
1243        return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(), exprs);
1244    }
1245
1246    public List JavaDoc getValidOrderItems() {
1247        List JavaDoc exprs = UtilMisc.toList(
1248                new EntityExpr("statusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
1249                new EntityExpr("statusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
1250        return EntityUtil.filterByAnd(getOrderItems(), exprs);
1251    }
1252
1253    public List JavaDoc getValidOrderItems(String JavaDoc shipGroupSeqId) {
1254        if (shipGroupSeqId == null) return getValidOrderItems();
1255        List JavaDoc exprs = UtilMisc.toList(
1256                new EntityExpr("statusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
1257                new EntityExpr("statusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"),
1258                new EntityExpr("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
1259        return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(), exprs);
1260    }
1261
1262    public GenericValue getOrderItem(String JavaDoc orderItemSeqId) {
1263        List JavaDoc exprs = UtilMisc.toList(new EntityExpr("orderItemSeqId", EntityOperator.EQUALS, orderItemSeqId));
1264        return EntityUtil.getFirst(EntityUtil.filterByAnd(getOrderItems(), exprs));
1265    }
1266
1267    public List JavaDoc getValidDigitalItems() {
1268        List JavaDoc digitalItems = new ArrayList JavaDoc();
1269        // only approved or complete items apply
1270
List JavaDoc exprs = UtilMisc.toList(
1271                new EntityExpr("statusId", EntityOperator.EQUALS, "ITEM_APPROVED"),
1272                new EntityExpr("statusId", EntityOperator.EQUALS, "ITEM_COMPLETED"));
1273        List JavaDoc items = EntityUtil.filterByOr(getOrderItems(), exprs);
1274        Iterator JavaDoc i = items.iterator();
1275        while (i.hasNext()) {
1276            GenericValue item = (GenericValue) i.next();
1277            if (item.get("productId") != null) {
1278                GenericValue product = null;
1279                try {
1280                    product = item.getRelatedOne("Product");
1281                } catch (GenericEntityException e) {
1282                    Debug.logError(e, "Unable to get Product from OrderItem", module);
1283                }
1284                if (product != null) {
1285                    GenericValue productType = null;
1286                    try {
1287                        productType = product.getRelatedOne("ProductType");
1288                    } catch (GenericEntityException e) {
1289                        Debug.logError(e, "ERROR: Unable to get ProductType from Product", module);
1290                    }
1291
1292                    if (productType != null) {
1293                        String JavaDoc isDigital = productType.getString("isDigital");
1294
1295                        if (isDigital != null && "Y".equalsIgnoreCase(isDigital)) {
1296                            // make sure we have an OrderItemBilling record
1297
List JavaDoc orderItemBillings = null;
1298                            try {
1299                                orderItemBillings = item.getRelated("OrderItemBilling");
1300                            } catch (GenericEntityException e) {
1301                                Debug.logError(e, "Unable to get OrderItemBilling from OrderItem");
1302                            }
1303
1304                            if (orderItemBillings != null && orderItemBillings.size() > 0) {
1305                                // get the ProductContent records
1306
List JavaDoc productContents = null;
1307                                try {
1308                                    productContents = product.getRelated("ProductContent");
1309                                } catch (GenericEntityException e) {
1310                                    Debug.logError("Unable to get ProductContent from Product", module);
1311                                }
1312                                List JavaDoc cExprs = UtilMisc.toList(
1313                                        new EntityExpr("productContentTypeId", EntityOperator.EQUALS, "DIGITAL_DOWNLOAD"),
1314                                        new EntityExpr("productContentTypeId", EntityOperator.EQUALS, "FULFILLMENT_EMAIL"),
1315                                        new EntityExpr("productContentTypeId", EntityOperator.EQUALS, "FULFILLMENT_EXTERNAL"));
1316                                // add more as needed
1317
productContents = EntityUtil.filterByDate(productContents);
1318                                productContents = EntityUtil.filterByOr(productContents, cExprs);
1319
1320                                if (productContents != null && productContents.size() > 0) {
1321                                    // make sure we are still within the allowed timeframe and use limits
1322
Iterator JavaDoc pci = productContents.iterator();
1323                                    while (pci.hasNext()) {
1324                                        GenericValue productContent = (GenericValue) pci.next();
1325                                        Timestamp JavaDoc fromDate = productContent.getTimestamp("purchaseFromDate");
1326                                        Timestamp JavaDoc thruDate = productContent.getTimestamp("purchaseThruDate");
1327                                        if (fromDate == null || item.getTimestamp("orderDate").after(fromDate)) {
1328                                            if (thruDate == null || item.getTimestamp("orderDate").before(thruDate)) {
1329                                                // TODO: Implement use count and days
1330
digitalItems.add(item);
1331                                            }
1332                                        }
1333                                    }
1334                                }
1335                            }
1336                        }
1337                    }
1338                }
1339            }
1340        }
1341        return digitalItems;
1342    }
1343
1344    public List JavaDoc getOrderItemAdjustments(GenericValue orderItem) {
1345        return getOrderItemAdjustmentList(orderItem, getAdjustments());
1346    }
1347
1348    public String JavaDoc getCurrentOrderItemWorkEffort(GenericValue orderItem) {
1349        GenericValue workOrderItemFulFillment;
1350        try {
1351            workOrderItemFulFillment = orderItem.getRelatedOne("WorkOrderItemFulFillment");
1352        }
1353        catch (GenericEntityException e) {
1354            return null;
1355        }
1356        GenericValue workEffort = null;
1357        try {
1358        workEffort = workOrderItemFulFillment.getRelatedOne("WorkEffort");
1359        }
1360        catch (GenericEntityException e) {
1361            return null;
1362        }
1363        return workEffort.getString("workEffortId");
1364    }
1365
1366    public String JavaDoc getCurrentItemStatus(GenericValue orderItem) {
1367        GenericValue statusItem = null;
1368        try {
1369            statusItem = orderItem.getRelatedOne("StatusItem");
1370        } catch (GenericEntityException e) {
1371            Debug.logError(e, "Trouble getting StatusItem : " + orderItem, module);
1372        }
1373        if (statusItem == null || statusItem.get("description") == null) {
1374            return "Not Available";
1375        } else {
1376            return statusItem.getString("description");
1377        }
1378    }
1379
1380    public List JavaDoc getOrderItemPriceInfos(GenericValue orderItem) {
1381        if (orderItem == null) return null;
1382        if (this.orderItemPriceInfos == null) {
1383            GenericDelegator delegator = orderHeader.getDelegator();
1384
1385            try {
1386                orderItemPriceInfos = delegator.findByAnd("OrderItemPriceInfo", UtilMisc.toMap("orderId", orderHeader.get("orderId")));
1387            } catch (GenericEntityException e) {
1388                Debug.logWarning(e, module);
1389            }
1390        }
1391        String JavaDoc orderItemSeqId = (String JavaDoc) orderItem.get("orderItemSeqId");
1392
1393        return EntityUtil.filterByAnd(this.orderItemPriceInfos, UtilMisc.toMap("orderItemSeqId", orderItemSeqId));
1394    }
1395
1396    public List JavaDoc getOrderItemShipGroupAssocs(GenericValue orderItem) {
1397        if (orderItem == null) return null;
1398        try {
1399            return orderHeader.getDelegator().findByAnd("OrderItemShipGroupAssoc",
1400                    UtilMisc.toMap("orderId", orderItem.getString("orderId"), "orderItemSeqId", orderItem.getString("orderItemSeqId")), UtilMisc.toList("shipGroupSeqId"));
1401        } catch (GenericEntityException e) {
1402            Debug.logWarning(e, module);
1403        }
1404        return null;
1405    }
1406
1407    public List JavaDoc getOrderItemShipGrpInvResList(GenericValue orderItem) {
1408        if (orderItem == null) return null;
1409        if (this.orderItemShipGrpInvResList == null) {
1410            GenericDelegator delegator = orderItem.getDelegator();
1411            try {
1412                orderItemShipGrpInvResList = delegator.findByAnd("OrderItemShipGrpInvRes", UtilMisc.toMap("orderId", orderItem.get("orderId")));
1413            } catch (GenericEntityException e) {
1414                Debug.logWarning(e, "Trouble getting OrderItemShipGrpInvRes List", module);
1415            }
1416        }
1417        return EntityUtil.filterByAnd(orderItemShipGrpInvResList, UtilMisc.toMap("orderItemSeqId", orderItem.getString("orderItemSeqId")));
1418    }
1419
1420    public List JavaDoc getOrderItemIssuances(GenericValue orderItem) {
1421        return this.getOrderItemIssuances(orderItem, null);
1422    }
1423
1424    public List JavaDoc getOrderItemIssuances(GenericValue orderItem, String JavaDoc shipmentId) {
1425        if (orderItem == null) return null;
1426        if (this.orderItemIssuances == null) {
1427            GenericDelegator delegator = orderItem.getDelegator();
1428
1429            try {
1430                orderItemIssuances = delegator.findByAnd("ItemIssuance", UtilMisc.toMap("orderId", orderItem.get("orderId")));
1431            } catch (GenericEntityException e) {
1432                Debug.logWarning(e, "Trouble getting ItemIssuance(s)", module);
1433            }
1434        }
1435
1436        // filter the issuances
1437
Map JavaDoc filter = UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId"));
1438        if (shipmentId != null) {
1439            filter.put("shipmentId", shipmentId);
1440        }
1441        return EntityUtil.filterByAnd(orderItemIssuances, filter);
1442    }
1443
1444    /** Get a set of productIds in the order. */
1445    public Collection JavaDoc getOrderProductIds() {
1446        Set JavaDoc productIds = new HashSet JavaDoc();
1447        for (Iterator JavaDoc iter = getOrderItems().iterator(); iter.hasNext(); ) {
1448            productIds.add(((GenericValue) iter.next()).getString("productId"));
1449        }
1450        return productIds;
1451    }
1452
1453    public List JavaDoc getOrderReturnItems() {
1454        GenericDelegator delegator = orderHeader.getDelegator();
1455        if (this.orderReturnItems == null) {
1456            try {
1457                this.orderReturnItems = delegator.findByAnd("ReturnItem", UtilMisc.toMap("orderId", orderHeader.getString("orderId")));
1458            } catch (GenericEntityException e) {
1459                Debug.logError(e, "Problem getting ReturnItem from order", module);
1460                return null;
1461            }
1462        }
1463        return this.orderReturnItems;
1464    }
1465
1466   /**
1467    * Get the quantity returned per order item.
1468    * In other words, this method will count the ReturnItems
1469    * related to each OrderItem.
1470    *
1471    * @return Map of returned quantities as Doubles keyed to the orderItemSeqId
1472    */

1473   public Map JavaDoc getOrderItemReturnedQuantities() {
1474       List JavaDoc returnItems = getOrderReturnItems();
1475
1476       // since we don't have a handy grouped view entity, we'll have to group the return items by hand
1477
Map JavaDoc returnMap = new HashMap JavaDoc();
1478       for (Iterator JavaDoc iter = this.getValidOrderItems().iterator(); iter.hasNext(); ) {
1479           GenericValue orderItem = (GenericValue) iter.next();
1480           List JavaDoc group = EntityUtil.filterByAnd(returnItems,
1481                   UtilMisc.toMap("orderId", orderItem.get("orderId"), "orderItemSeqId", orderItem.get("orderItemSeqId")));
1482
1483           // add up the returned quantities for this group TODO: received quantity should be used eventually
1484
double returned = 0;
1485           for (Iterator JavaDoc groupiter = group.iterator(); groupiter.hasNext(); ) {
1486               GenericValue returnItem = (GenericValue) groupiter.next();
1487               if (returnItem.getDouble("returnQuantity") != null) {
1488                   returned += ((Double JavaDoc) returnItem.getDouble("returnQuantity")).doubleValue();
1489               }
1490           }
1491
1492           // the quantity returned per order item
1493
returnMap.put(orderItem.get("orderItemSeqId"), new Double JavaDoc(returned));
1494       }
1495       return returnMap;
1496   }
1497
1498   /**
1499    * Get the total quantity of returned items for an order. This will count
1500    * only the ReturnItems that are directly correlated to an OrderItem.
1501    */

1502    public BigDecimal JavaDoc getOrderReturnedQuantityBd() {
1503        List JavaDoc returnedItemsBase = getOrderReturnItems();
1504        List JavaDoc returnedItems = new ArrayList JavaDoc(returnedItemsBase.size());
1505
1506        // filter just order items
1507
List JavaDoc orderItemExprs = UtilMisc.toList(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_PROD_ITEM"));
1508        orderItemExprs.add(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_FPROD_ITEM"));
1509        orderItemExprs.add(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_DPROD_ITEM"));
1510        orderItemExprs.add(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_FDPROD_ITEM"));
1511        orderItemExprs.add(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_PROD_FEATR_ITEM"));
1512        orderItemExprs.add(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_SPROD_ITEM"));
1513        orderItemExprs.add(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_WE_ITEM"));
1514        orderItemExprs.add(new EntityExpr("returnItemTypeId", EntityOperator.EQUALS, "RET_TE_ITEM"));
1515        returnedItemsBase = EntityUtil.filterByOr(returnedItemsBase, orderItemExprs);
1516
1517        // get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
1518
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
1519        returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
1520
1521        BigDecimal JavaDoc returnedQuantity = ZERO;
1522        if (returnedItems != null) {
1523            Iterator JavaDoc i = returnedItems.iterator();
1524            while (i.hasNext()) {
1525                GenericValue returnedItem = (GenericValue) i.next();
1526                if (returnedItem.get("returnQuantity") != null) {
1527                    returnedQuantity = returnedQuantity.add(returnedItem.getBigDecimal("returnQuantity")).setScale(scale, rounding);
1528                }
1529            }
1530        }
1531        return returnedQuantity.setScale(scale, rounding);
1532    }
1533
1534    /** @deprecated */
1535    public double getOrderReturnedQuantity() {
1536        return getOrderReturnedQuantityBd().doubleValue();
1537    }
1538
1539    /**
1540     * Returns total of all return items for this order except those return items which have been cancelled
1541     */

1542    public BigDecimal JavaDoc getOrderReturnedTotalBd() {
1543        return getOrderReturnedTotalBd(false);
1544    }
1545
1546    /** @deprecated */
1547    public double getOrderReturnedTotal() {
1548        return getOrderReturnedTotalBd().doubleValue();
1549    }
1550
1551    
1552    /**
1553     * @includeAll -- if true, will use all return items except the CANCELLED ones. if false, will use only ACCEPTED, RECEIVED and COMPLETED return items
1554     */

1555    public BigDecimal JavaDoc getOrderReturnedTotalBd(boolean includeAll) {
1556        List JavaDoc returnedItemsBase = getOrderReturnItems();
1557        List JavaDoc returnedItems = new ArrayList JavaDoc(returnedItemsBase.size());
1558
1559        // get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
1560
if (!includeAll) {
1561            returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_ACCEPTED")));
1562            returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
1563            returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
1564        } else {
1565            returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
1566                    UtilMisc.toList(new EntityExpr("statusId", EntityOperator.NOT_EQUAL, "RETURN_CANCELLED"))));
1567        }
1568        BigDecimal JavaDoc returnedAmount = ZERO;
1569        Iterator JavaDoc i = returnedItems.iterator();
1570        String JavaDoc orderId = orderHeader.getString("orderId");
1571        List JavaDoc returnHeaderList = new ArrayList JavaDoc();
1572        while (i.hasNext()) {
1573            GenericValue returnedItem = (GenericValue) i.next();
1574            if ((returnedItem.get("returnPrice") != null) && (returnedItem.get("returnQuantity") != null)) {
1575                returnedAmount = returnedAmount.add(returnedItem.getBigDecimal("returnPrice").multiply(returnedItem.getBigDecimal("returnQuantity"))).setScale(scale, rounding);
1576            }
1577            Map JavaDoc itemAdjustmentCondition = UtilMisc.toMap("returnId", returnedItem.get("returnId"), "returnItemSeqId", returnedItem.get("returnItemSeqId"));
1578            returnedAmount = returnedAmount.add(getReturnAdjustmentTotalBd(orderHeader.getDelegator(), itemAdjustmentCondition));
1579            if(orderId.equals(returnedItem.getString("orderId")) && (!returnHeaderList.contains(returnedItem.getString("returnId")))) {
1580                returnHeaderList.add(returnedItem.getString("returnId"));
1581            }
1582        }
1583        //get returnedAmount from returnHeader adjustments whose orderId must equals to current orderHeader.orderId
1584
Iterator JavaDoc returnHeaderIterator = returnHeaderList.iterator();
1585        while(returnHeaderIterator.hasNext()) {
1586            String JavaDoc returnId = (String JavaDoc) returnHeaderIterator.next();
1587            Map JavaDoc returnHeaderAdjFilter = UtilMisc.toMap("returnId", returnId, "returnItemSeqId", "_NA_");
1588            returnedAmount =returnedAmount.add(getReturnAdjustmentTotalBd(orderHeader.getDelegator(), returnHeaderAdjFilter)).setScale(scale, rounding);
1589        }
1590        return returnedAmount.setScale(scale, rounding);
1591    }
1592
1593    /** @deprecated */
1594    public double getOrderReturnedTotal(boolean includeAll) {
1595        return getOrderReturnedTotalBd(includeAll).doubleValue();
1596    }
1597
1598    public BigDecimal JavaDoc getOrderNonReturnedTaxAndShippingBd() {
1599        // first make a Map of orderItemSeqId key, returnQuantity value
1600
List JavaDoc returnedItemsBase = getOrderReturnItems();
1601        List JavaDoc returnedItems = new ArrayList JavaDoc(returnedItemsBase.size());
1602
1603        // get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
1604
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
1605        returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
1606
1607        Map JavaDoc itemReturnedQuantities = new HashMap JavaDoc();
1608        Iterator JavaDoc i = returnedItems.iterator();
1609        while (i.hasNext()) {
1610            GenericValue returnedItem = (GenericValue) i.next();
1611            String JavaDoc orderItemSeqId = returnedItem.getString("orderItemSeqId");
1612            BigDecimal JavaDoc returnedQuantity = returnedItem.getBigDecimal("returnQuantity");
1613            if (orderItemSeqId != null && returnedQuantity != null) {
1614                BigDecimal JavaDoc existingQuantity = (BigDecimal JavaDoc) itemReturnedQuantities.get(orderItemSeqId);
1615                if (existingQuantity == null) {
1616                    itemReturnedQuantities.put(orderItemSeqId, returnedQuantity);
1617                } else {
1618                    itemReturnedQuantities.put(orderItemSeqId, returnedQuantity.add(existingQuantity));
1619                }
1620            }
1621        }
1622
1623        // then go through all order items and for the quantity not returned calculate it's portion of the item, and of the entire order
1624
BigDecimal JavaDoc totalSubTotalNotReturned = ZERO;
1625        BigDecimal JavaDoc totalTaxNotReturned = ZERO;
1626        BigDecimal JavaDoc totalShippingNotReturned = ZERO;
1627
1628        Iterator JavaDoc orderItems = this.getValidOrderItems().iterator();
1629        while (orderItems.hasNext()) {
1630            GenericValue orderItem = (GenericValue) orderItems.next();
1631
1632            BigDecimal JavaDoc itemQuantityDbl = orderItem.getBigDecimal("quantity");
1633            if (itemQuantityDbl == null) {
1634                continue;
1635            }
1636            BigDecimal JavaDoc itemQuantity = itemQuantityDbl;
1637            BigDecimal JavaDoc itemSubTotal = this.getOrderItemSubTotalBd(orderItem);
1638            BigDecimal JavaDoc itemTaxes = this.getOrderItemTaxBd(orderItem);
1639            BigDecimal JavaDoc itemShipping = this.getOrderItemShippingBd(orderItem);
1640
1641            BigDecimal JavaDoc quantityReturnedDouble = (BigDecimal JavaDoc) itemReturnedQuantities.get(orderItem.get("orderItemSeqId"));
1642            BigDecimal JavaDoc quantityReturned = ZERO;
1643            if (quantityReturnedDouble != null) {
1644                quantityReturned = quantityReturnedDouble;
1645            }
1646
1647            BigDecimal JavaDoc quantityNotReturned = itemQuantity.subtract(quantityReturned);
1648
1649            // pro-rated factor (quantity not returned / total items ordered), which shouldn't be rounded to 2 decimals
1650
BigDecimal JavaDoc factorNotReturned = quantityNotReturned.divide(itemQuantity, 100, rounding);
1651
1652            BigDecimal JavaDoc subTotalNotReturned = itemSubTotal.multiply(factorNotReturned).setScale(scale, rounding);
1653
1654            // calculate tax and shipping adjustments for each item, add to accumulators
1655
BigDecimal JavaDoc itemTaxNotReturned = itemTaxes.multiply(factorNotReturned).setScale(scale, rounding);
1656            BigDecimal JavaDoc itemShippingNotReturned = itemShipping.multiply(factorNotReturned).setScale(scale, rounding);
1657
1658            totalSubTotalNotReturned = totalSubTotalNotReturned.add(subTotalNotReturned);
1659            totalTaxNotReturned = totalTaxNotReturned.add(itemTaxNotReturned);
1660            totalShippingNotReturned = totalShippingNotReturned.add(itemShippingNotReturned);
1661        }
1662
1663        // calculate tax and shipping adjustments for entire order, add to result
1664
BigDecimal JavaDoc orderItemsSubTotal = this.getOrderItemsSubTotalBd();
1665        BigDecimal JavaDoc orderFactorNotReturned = ZERO;
1666        if (orderItemsSubTotal.signum() != 0) {
1667            // pro-rated factor (subtotal not returned / item subtotal), which shouldn't be rounded to 2 decimals
1668
orderFactorNotReturned = totalSubTotalNotReturned.divide(orderItemsSubTotal, 100, rounding);
1669        }
1670        BigDecimal JavaDoc orderTaxNotReturned = this.getHeaderTaxTotalBd().multiply(orderFactorNotReturned).setScale(scale, rounding);
1671        BigDecimal JavaDoc orderShippingNotReturned = this.getShippingTotalBd().multiply(orderFactorNotReturned).setScale(scale, rounding);
1672
1673        return totalTaxNotReturned.add(totalShippingNotReturned).add(orderTaxNotReturned).add(orderShippingNotReturned).setScale(scale, rounding);
1674    }
1675
1676    /** @deprecated */
1677    public double getOrderNonReturnedTaxAndShipping() {
1678        return getOrderNonReturnedTaxAndShippingBd().doubleValue();
1679    }
1680
1681    public BigDecimal JavaDoc getOrderBackorderQuantityBd() {
1682        BigDecimal JavaDoc backorder = ZERO;
1683        List JavaDoc items = this.getValidOrderItems();
1684        if (items != null) {
1685            Iterator JavaDoc ii = items.iterator();
1686            while (ii.hasNext()) {
1687                GenericValue item = (GenericValue) ii.next();
1688                List JavaDoc reses = this.getOrderItemShipGrpInvResList(item);
1689                if (reses != null) {
1690                    Iterator JavaDoc ri = reses.iterator();
1691                    while (ri.hasNext()) {
1692                        GenericValue res = (GenericValue) ri.next();
1693                        BigDecimal JavaDoc nav = res.getBigDecimal("quantityNotAvailable");
1694                        if (nav != null) {
1695                            backorder = backorder.add(nav).setScale(scale, rounding);
1696                        }
1697                    }
1698                }
1699            }
1700        }
1701        return backorder.setScale(scale, rounding);
1702    }
1703
1704    /** @deprecated */
1705    public double getOrderBackorderQuantity() {
1706        return getOrderBackorderQuantityBd().doubleValue();
1707    }
1708
1709    public BigDecimal JavaDoc getItemShippedQuantityBd(GenericValue orderItem) {
1710        BigDecimal JavaDoc quantityShipped = ZERO;
1711        List JavaDoc issuance = getOrderItemIssuances(orderItem);
1712        if (issuance != null) {
1713            Iterator JavaDoc i = issuance.iterator();
1714            while (i.hasNext()) {
1715                GenericValue issue = (GenericValue) i.next();
1716                BigDecimal JavaDoc issueQty = issue.getBigDecimal("quantity");
1717                if (issueQty != null) {
1718                    quantityShipped = quantityShipped.add(issueQty).setScale(scale, rounding);
1719                }
1720            }
1721        }
1722        return quantityShipped.setScale(scale, rounding);
1723    }
1724
1725    /** @deprecated */
1726    public double getItemShippedQuantity(GenericValue orderItem) {
1727        return getItemShippedQuantityBd(orderItem).doubleValue();
1728    }
1729
1730    public BigDecimal JavaDoc getItemReservedQuantityBd(GenericValue orderItem) {
1731        BigDecimal JavaDoc reserved = ZERO;
1732
1733        List JavaDoc reses = getOrderItemShipGrpInvResList(orderItem);
1734        if (reses != null) {
1735            Iterator JavaDoc i = reses.iterator();
1736            while (i.hasNext()) {
1737                GenericValue res = (GenericValue) i.next();
1738                BigDecimal JavaDoc quantity = res.getBigDecimal("quantity");
1739                if (quantity != null) {
1740                    reserved = reserved.add(quantity).setScale(scale, rounding);
1741                }
1742            }
1743        }
1744        return reserved.setScale(scale, rounding);
1745    }
1746
1747    /** @deprecated */
1748    public double getItemReservedQuantity(GenericValue orderItem) {
1749        return getItemReservedQuantityBd(orderItem).doubleValue();
1750    }
1751
1752    public BigDecimal JavaDoc getItemBackorderedQuantityBd(GenericValue orderItem) {
1753        BigDecimal JavaDoc backOrdered = ZERO;
1754
1755        Timestamp JavaDoc shipDate = orderItem.getTimestamp("estimatedShipDate");
1756        Timestamp JavaDoc autoCancel = orderItem.getTimestamp("autoCancelDate");
1757
1758        List JavaDoc reses = getOrderItemShipGrpInvResList(orderItem);
1759        if (reses != null) {
1760            Iterator JavaDoc i = reses.iterator();
1761            while (i.hasNext()) {
1762                GenericValue res = (GenericValue) i.next();
1763                Timestamp JavaDoc promised = res.getTimestamp("currentPromisedDate");
1764                if (promised == null) {
1765                    promised = res.getTimestamp("promisedDatetime");
1766                }
1767                if (autoCancel != null || (shipDate != null && shipDate.after(promised))) {
1768                    BigDecimal JavaDoc resQty = res.getBigDecimal("quantity");
1769                    if (resQty != null) {
1770                        backOrdered = backOrdered.add(resQty).setScale(scale, rounding);
1771                    }
1772                }
1773            }
1774        }
1775        return backOrdered;
1776    }
1777
1778    /** @deprecated */
1779    public double getItemBackorderedQuantity(GenericValue orderItem) {
1780        return getItemBackorderedQuantityBd(orderItem).doubleValue();
1781    }
1782
1783    public BigDecimal JavaDoc getItemPendingShipmentQuantityBd(GenericValue orderItem) {
1784        BigDecimal JavaDoc reservedQty = getItemReservedQuantityBd(orderItem);
1785        BigDecimal JavaDoc backordered = getItemBackorderedQuantityBd(orderItem);
1786        return reservedQty.subtract(backordered).setScale(scale, rounding);
1787    }
1788
1789    /** @deprecated */
1790    public double getItemPendingShipmentQuantity(GenericValue orderItem) {
1791        return getItemPendingShipmentQuantityBd(orderItem).doubleValue();
1792    }
1793
1794    public double getItemCanceledQuantity(GenericValue orderItem) {
1795        Double JavaDoc cancelQty = orderItem.getDouble("cancelQuantity");
1796        if (cancelQty == null) cancelQty = new Double JavaDoc(0);
1797        return cancelQty.doubleValue();
1798    }
1799
1800    public BigDecimal JavaDoc getTotalOrderItemsQuantityBd() {
1801        List JavaDoc orderItems = getValidOrderItems();
1802        BigDecimal JavaDoc totalItems = ZERO;
1803
1804        for (int i = 0; i < orderItems.size(); i++) {
1805            GenericValue oi = (GenericValue) orderItems.get(i);
1806
1807            totalItems = totalItems.add(getOrderItemQuantityBd(oi)).setScale(scale, rounding);
1808        }
1809        return totalItems.setScale(scale, rounding);
1810    }
1811
1812    /** @deprecated */
1813    public double getTotalOrderItemsQuantity() {
1814        return getTotalOrderItemsQuantityBd().doubleValue();
1815    }
1816
1817    public BigDecimal JavaDoc getTotalOrderItemsOrderedQuantityBd() {
1818        List JavaDoc orderItems = getValidOrderItems();
1819        BigDecimal JavaDoc totalItems = ZERO;
1820
1821        for (int i = 0; i < orderItems.size(); i++) {
1822            GenericValue oi = (GenericValue) orderItems.get(i);
1823
1824            totalItems =totalItems.add(oi.getBigDecimal("quantity")).setScale(scale, rounding);
1825        }
1826        return totalItems;
1827    }
1828
1829    /** @deprecated */
1830    public double getTotalOrderItemsOrderedQuantity() {
1831        return getTotalOrderItemsOrderedQuantityBd().doubleValue();
1832    }
1833
1834    public BigDecimal JavaDoc getOrderItemsSubTotalBd() {
1835        return getOrderItemsSubTotalBd(getValidOrderItems(), getAdjustments());
1836    }
1837
1838    /** @deprecated */
1839    public double getOrderItemsSubTotal() {
1840        return getOrderItemsSubTotalBd().doubleValue();
1841    }
1842
1843    public BigDecimal JavaDoc getOrderItemSubTotalBd(GenericValue orderItem) {
1844        return getOrderItemSubTotalBd(orderItem, getAdjustments());
1845    }
1846
1847    /** @deprecated */
1848    public double getOrderItemSubTotal(GenericValue orderItem) {
1849        return getOrderItemSubTotalBd(orderItem).doubleValue();
1850    }
1851
1852    public BigDecimal JavaDoc getOrderItemsTotalBd() {
1853        return getOrderItemsTotalBd(getValidOrderItems(), getAdjustments());
1854    }
1855
1856    /** @deprecated */
1857    public double getOrderItemsTotal() {
1858        return getOrderItemsTotalBd().doubleValue();
1859    }
1860
1861    public BigDecimal JavaDoc getOrderItemTotalBd(GenericValue orderItem) {
1862        return getOrderItemTotalBd(orderItem, getAdjustments());
1863    }
1864
1865    /** @deprecated */
1866    public double getOrderItemTotal(GenericValue orderItem) {
1867        return getOrderItemTotalBd(orderItem).doubleValue();
1868    }
1869
1870    public BigDecimal JavaDoc getOrderItemTaxBd(GenericValue orderItem) {
1871        return getOrderItemAdjustmentsTotalBd(orderItem, false, true, false);
1872    }
1873
1874    /** @deprecated */
1875    public double getOrderItemTax(GenericValue orderItem) {
1876        return getOrderItemTaxBd(orderItem).doubleValue();
1877    }
1878
1879    public BigDecimal JavaDoc getOrderItemShippingBd(GenericValue orderItem) {
1880        return getOrderItemAdjustmentsTotalBd(orderItem, false, false, true);
1881    }
1882
1883    /** @deprecated */
1884    public double getOrderItemShipping(GenericValue orderItem) {
1885        return getOrderItemShippingBd(orderItem).doubleValue();
1886    }
1887
1888    public BigDecimal JavaDoc getOrderItemAdjustmentsTotalBd(GenericValue orderItem, boolean includeOther, boolean includeTax, boolean includeShipping) {
1889        return getOrderItemAdjustmentsTotalBd(orderItem, getAdjustments(), includeOther, includeTax, includeShipping);
1890    }
1891
1892    /** @deprecated */
1893    public double getOrderItemAdjustmentsTotal(GenericValue orderItem, boolean includeOther, boolean includeTax, boolean includeShipping) {
1894        return getOrderItemAdjustmentsTotalBd(orderItem, getAdjustments(), includeOther, includeTax, includeShipping).doubleValue();
1895    }
1896
1897    public BigDecimal JavaDoc getOrderItemAdjustmentsTotalBd(GenericValue orderItem) {
1898        return getOrderItemAdjustmentsTotalBd(orderItem, true, false, false);
1899    }
1900
1901    /** @deprecated */
1902    public double getOrderItemAdjustmentsTotal(GenericValue orderItem) {
1903        return getOrderItemAdjustmentsTotalBd(orderItem, true, false, false).doubleValue();
1904    }
1905
1906    public BigDecimal JavaDoc getOrderItemAdjustmentTotalBd(GenericValue orderItem, GenericValue adjustment) {
1907        return calcItemAdjustmentBd(adjustment, orderItem);
1908    }
1909
1910    /** @deprecated */
1911    public double getOrderItemAdjustmentTotal(GenericValue orderItem, GenericValue adjustment) {
1912        return getOrderItemAdjustmentTotalBd(orderItem, adjustment).doubleValue();
1913    }
1914
1915    public String JavaDoc getAdjustmentType(GenericValue adjustment) {
1916        GenericValue adjustmentType = null;
1917        try {
1918            adjustmentType = adjustment.getRelatedOne("OrderAdjustmentType");
1919        } catch (GenericEntityException e) {
1920            Debug.logError(e, "Problems with order adjustment", module);
1921        }
1922        if (adjustmentType == null || adjustmentType.get("description") == null) {
1923            return "";
1924        } else {
1925            return adjustmentType.getString("description");
1926        }
1927    }
1928
1929    public List JavaDoc getOrderItemStatuses(GenericValue orderItem) {
1930        return getOrderItemStatuses(orderItem, getOrderStatuses());
1931    }
1932
1933    public String JavaDoc getCurrentItemStatusString(GenericValue orderItem) {
1934        GenericValue statusItem = null;
1935        try {
1936            statusItem = orderItem.getRelatedOneCache("StatusItem");
1937        } catch (GenericEntityException e) {
1938            Debug.logError(e, module);
1939        }
1940        if (statusItem != null) {
1941            return statusItem.getString("description");
1942        } else {
1943            return orderHeader.getString("statusId");
1944        }
1945    }
1946
1947    /** Fetches the set of order items with the given EntityCondition. */
1948    public List JavaDoc getOrderItemsByCondition(EntityCondition entityCondition) {
1949        return EntityUtil.filterByCondition(getOrderItems(), entityCondition);
1950    }
1951
1952    /**
1953     * Checks to see if this user has read permission on this order
1954     * @param userLogin The UserLogin value object to check
1955     * @return boolean True if we have read permission
1956     */

1957    public boolean hasPermission(Security security, GenericValue userLogin) {
1958        return OrderReadHelper.hasPermission(security, userLogin, orderHeader);
1959    }
1960
1961    /**
1962     * Getter for property orderHeader.
1963     * @return Value of property orderHeader.
1964     */

1965    public GenericValue getOrderHeader() {
1966        return orderHeader;
1967    }
1968
1969    // ======================================================
1970
// =================== Static Methods ===================
1971
// ======================================================
1972

1973    public static GenericValue getOrderHeader(GenericDelegator delegator, String JavaDoc orderId) {
1974        GenericValue orderHeader = null;
1975        if (orderId != null && delegator != null) {
1976            try {
1977                orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
1978            } catch (GenericEntityException e) {
1979                Debug.logError(e, "Cannot get order header", module);
1980            }
1981        }
1982        return orderHeader;
1983    }
1984
1985    public static BigDecimal JavaDoc getOrderItemQuantityBd(GenericValue orderItem) {
1986        String JavaDoc cancelQtyField = "cancelQuantity";
1987        String JavaDoc quantityField = "quantity";
1988
1989        if ("OrderItemAndShipGroupAssoc".equals(orderItem.getEntityName())) {
1990            cancelQtyField = "cancelQuantity";
1991            quantityField = "quantity";
1992        }
1993
1994        BigDecimal JavaDoc cancelQty = orderItem.getBigDecimal(cancelQtyField);
1995        BigDecimal JavaDoc orderQty = orderItem.getBigDecimal(quantityField);
1996
1997        if (cancelQty == null) cancelQty = ZERO;
1998        if (orderQty == null) orderQty = ZERO;
1999
2000        return orderQty.subtract(cancelQty).setScale(scale, rounding);
2001    }
2002
2003    /** @deprecated */
2004    public static Double JavaDoc getOrderItemQuantity(GenericValue orderItem) {
2005        return new Double JavaDoc(getOrderItemQuantityBd(orderItem).doubleValue());
2006    }
2007
2008    public static Double JavaDoc getOrderItemShipGroupQuantity(GenericValue shipGroupAssoc) {
2009        Double JavaDoc cancelQty = shipGroupAssoc.getDouble("cancelQuantity");
2010        Double JavaDoc orderQty = shipGroupAssoc.getDouble("quantity");
2011
2012        if (cancelQty == null) cancelQty = new Double JavaDoc(0.0);
2013        if (orderQty == null) orderQty = new Double JavaDoc(0.0);
2014
2015        return new Double JavaDoc(orderQty.doubleValue() - cancelQty.doubleValue());
2016    }
2017
2018    public static GenericValue getProductStoreFromOrder(GenericDelegator delegator, String JavaDoc orderId) {
2019        GenericValue orderHeader = getOrderHeader(delegator, orderId);
2020        if (orderHeader == null) {
2021            Debug.logWarning("Could not find OrderHeader for orderId [" + orderId + "] in getProductStoreFromOrder, returning null", module);
2022        }
2023        return getProductStoreFromOrder(orderHeader);
2024    }
2025
2026    public static GenericValue getProductStoreFromOrder(GenericValue orderHeader) {
2027        if (orderHeader == null) {
2028            return null;
2029        }
2030        GenericDelegator delegator = orderHeader.getDelegator();
2031        GenericValue productStore = null;
2032        if (orderHeader != null && orderHeader.get("productStoreId") != null) {
2033            try {
2034                productStore = delegator.findByPrimaryKeyCache("ProductStore", UtilMisc.toMap("productStoreId", orderHeader.getString("productStoreId")));
2035            } catch (GenericEntityException e) {
2036                Debug.logError(e, "Cannot locate ProductStore from OrderHeader", module);
2037            }
2038        } else {
2039            Debug.logError("Null header or productStoreId", module);
2040        }
2041        return productStore;
2042    }
2043
2044    public static BigDecimal JavaDoc getOrderGrandTotalBd(List JavaDoc orderItems, List JavaDoc adjustments) {
2045        BigDecimal JavaDoc total = getOrderItemsTotalBd(orderItems, adjustments);
2046        BigDecimal JavaDoc adj = getOrderAdjustmentsTotalBd(orderItems, adjustments);
2047        return total.add(adj).setScale(scale,rounding);
2048    }
2049
2050    /** @deprecated */
2051    public static double getOrderGrandTotal(List JavaDoc orderItems, List JavaDoc adjustments) {
2052        return getOrderGrandTotalBd(orderItems, adjustments).doubleValue();
2053    }
2054
2055    public static List JavaDoc getOrderHeaderAdjustments(List JavaDoc adjustments, String JavaDoc shipGroupSeqId) {
2056        List JavaDoc contraints1 = UtilMisc.toList(new EntityExpr("orderItemSeqId", EntityOperator.EQUALS, null));
2057        List JavaDoc contraints2 = UtilMisc.toList(new EntityExpr("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
2058        List JavaDoc contraints3 = UtilMisc.toList(new EntityExpr("orderItemSeqId", EntityOperator.EQUALS, ""));
2059        List JavaDoc contraints4 = new LinkedList JavaDoc();
2060        if (shipGroupSeqId != null) {
2061            contraints4.add(new EntityExpr("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
2062        }
2063        List JavaDoc toFilter = null;
2064        List JavaDoc adj = new LinkedList JavaDoc();
2065
2066        if (shipGroupSeqId != null) {
2067            toFilter = EntityUtil.filterByAnd(adjustments, contraints4);
2068        } else {
2069            toFilter = adjustments;
2070        }
2071
2072        adj.addAll(EntityUtil.filterByAnd(toFilter, contraints1));
2073        adj.addAll(EntityUtil.filterByAnd(toFilter, contraints2));
2074        adj.addAll(EntityUtil.filterByAnd(toFilter, contraints3));
2075        return adj;
2076    }
2077
2078    public static List JavaDoc getOrderHeaderStatuses(List JavaDoc orderStatuses) {
2079        List JavaDoc contraints1 = UtilMisc.toList(new EntityExpr("orderItemSeqId", EntityOperator.EQUALS, null));
2080        List JavaDoc contraints2 = UtilMisc.toList(new EntityExpr("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
2081        List JavaDoc contraints3 = UtilMisc.toList(new EntityExpr("orderItemSeqId", EntityOperator.EQUALS, ""));
2082        List JavaDoc newOrderStatuses = new LinkedList JavaDoc();
2083
2084        newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses, contraints1));
2085        newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses, contraints2));
2086        newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses, contraints3));
2087        newOrderStatuses = EntityUtil.orderBy(newOrderStatuses, UtilMisc.toList("-statusDatetime"));
2088        return newOrderStatuses;
2089    }
2090
2091    public static BigDecimal JavaDoc getOrderAdjustmentsTotalBd(List JavaDoc orderItems, List JavaDoc adjustments) {
2092        return calcOrderAdjustmentsBd(getOrderHeaderAdjustments(adjustments, null), getOrderItemsSubTotalBd(orderItems, adjustments), true, true, true);
2093    }
2094
2095    /** @deprecated */
2096    public static double getOrderAdjustmentsTotal(List JavaDoc orderItems, List JavaDoc adjustments) {
2097        return getOrderAdjustmentsTotalBd(orderItems, adjustments).doubleValue();
2098    }
2099
2100    public static List JavaDoc getOrderSurveyResponses(GenericValue orderHeader) {
2101        GenericDelegator delegator = orderHeader.getDelegator();
2102        String JavaDoc orderId = orderHeader.getString("orderId");
2103         List JavaDoc responses = null;
2104        try {
2105            responses = delegator.findByAnd("SurveyResponse", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", "_NA_"));
2106        } catch (GenericEntityException e) {
2107            Debug.logError(e, module);
2108        }
2109
2110        if (responses == null) {
2111            responses = new LinkedList JavaDoc();
2112        }
2113        return responses;
2114    }
2115
2116    public static List JavaDoc getOrderItemSurveyResponse(GenericValue orderItem) {
2117        GenericDelegator delegator = orderItem.getDelegator();
2118        String JavaDoc orderItemSeqId = orderItem.getString("orderItemSeqId");
2119        String JavaDoc orderId = orderItem.getString("orderId");
2120        List JavaDoc responses = null;
2121        try {
2122            responses = delegator.findByAnd("SurveyResponse", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId));
2123        } catch (GenericEntityException e) {
2124            Debug.logError(e, module);
2125        }
2126
2127        if (responses == null) {
2128            responses = new LinkedList JavaDoc();
2129        }
2130        return responses;
2131    }
2132
2133    // ================= Order Adjustments =================
2134

2135    public static BigDecimal JavaDoc calcOrderAdjustmentsBd(List JavaDoc orderHeaderAdjustments, BigDecimal JavaDoc subTotal, boolean includeOther, boolean includeTax, boolean includeShipping) {
2136        BigDecimal JavaDoc adjTotal = ZERO;
2137
2138        if (orderHeaderAdjustments != null && orderHeaderAdjustments.size() > 0) {
2139            List JavaDoc filteredAdjs = filterOrderAdjustments(orderHeaderAdjustments, includeOther, includeTax, includeShipping, false, false);
2140            Iterator JavaDoc adjIt = filteredAdjs.iterator();
2141
2142            while (adjIt.hasNext()) {
2143                GenericValue orderAdjustment = (GenericValue) adjIt.next();
2144
2145                adjTotal = adjTotal.add(OrderReadHelper.calcOrderAdjustmentBd(orderAdjustment, subTotal)).setScale(scale, rounding);
2146            }
2147        }
2148        return adjTotal.setScale(scale, rounding);
2149    }
2150
2151    /** @deprecated */
2152    public static double calcOrderAdjustments(List JavaDoc orderHeaderAdjustments, double subTotal, boolean includeOther, boolean includeTax, boolean includeShipping) {
2153        return calcOrderAdjustmentsBd(orderHeaderAdjustments, new BigDecimal JavaDoc(subTotal), includeOther, includeTax, includeShipping).doubleValue();
2154    }
2155
2156    public static BigDecimal JavaDoc calcOrderAdjustmentBd(GenericValue orderAdjustment, BigDecimal JavaDoc orderSubTotal) {
2157        BigDecimal JavaDoc adjustment = ZERO;
2158
2159        if (orderAdjustment.get("amount") != null) {
2160            // round amount to best precision (taxCalcScale) because db value of 0.825 is pulled as 0.8249999...
2161
BigDecimal JavaDoc amount = orderAdjustment.getBigDecimal("amount").setScale(taxCalcScale, taxRounding);
2162            adjustment = adjustment.add(amount);
2163        }
2164        return adjustment.setScale(scale, rounding);
2165    }
2166
2167    /** @deprecated */
2168    public static double calcOrderAdjustment(GenericValue orderAdjustment, double orderSubTotal) {
2169        return calcOrderAdjustmentBd(orderAdjustment, new BigDecimal JavaDoc(orderSubTotal)).doubleValue();
2170    }
2171
2172    // ================= Order Item Adjustments =================
2173
public static BigDecimal JavaDoc getOrderItemsSubTotalBd(List JavaDoc orderItems, List JavaDoc adjustments) {
2174        return getOrderItemsSubTotalBd(orderItems, adjustments, null);
2175    }
2176
2177    /** @deprecated */
2178    public static double getOrderItemsSubTotal(List JavaDoc orderItems, List JavaDoc adjustments) {
2179        return getOrderItemsSubTotalBd(orderItems, adjustments).doubleValue();
2180    }
2181
2182    public static BigDecimal JavaDoc getOrderItemsSubTotalBd(List JavaDoc orderItems, List JavaDoc adjustments, List JavaDoc workEfforts) {
2183        BigDecimal JavaDoc result = ZERO;
2184        Iterator JavaDoc itemIter = UtilMisc.toIterator(orderItems);
2185
2186        while (itemIter != null && itemIter.hasNext()) {
2187            GenericValue orderItem = (GenericValue) itemIter.next();
2188            BigDecimal JavaDoc itemTotal = getOrderItemSubTotalBd(orderItem, adjustments);
2189            // Debug.log("Item : " + orderItem.getString("orderId") + " / " + orderItem.getString("orderItemSeqId") + " = " + itemTotal, module);
2190

2191            if (workEfforts != null && orderItem.getString("orderItemTypeId").compareTo("RENTAL_ORDER_ITEM") == 0) {
2192                Iterator JavaDoc weIter = UtilMisc.toIterator(workEfforts);
2193                while (weIter != null && weIter.hasNext()) {
2194                    GenericValue workEffort = (GenericValue) weIter.next();
2195                    if (workEffort.getString("workEffortId").compareTo(orderItem.getString("orderItemSeqId")) == 0) {
2196                        itemTotal = itemTotal.multiply(getWorkEffortRentalQuantityBd(workEffort)).setScale(scale, rounding);
2197                        break;
2198                    }
2199// Debug.log("Item : " + orderItem.getString("orderId") + " / " + orderItem.getString("orderItemSeqId") + " = " + itemTotal, module);
2200
}
2201            }
2202            result = result.add(itemTotal).setScale(scale, rounding);
2203
2204        }
2205        return result.setScale(scale, rounding);
2206    }
2207
2208    /** @deprecated */
2209    public static double getOrderItemsSubTotal(List JavaDoc orderItems, List JavaDoc adjustments, List JavaDoc workEfforts) {
2210        return getOrderItemsSubTotalBd(orderItems, adjustments, workEfforts).doubleValue();
2211    }
2212
2213    /** The passed adjustments can be all adjustments for the order, ie for all line items */
2214    public static BigDecimal JavaDoc getOrderItemSubTotalBd(GenericValue orderItem, List JavaDoc adjustments) {
2215        return getOrderItemSubTotalBd(orderItem, adjustments, false, false);
2216    }
2217
2218    /** @deprecated */
2219    public static double getOrderItemSubTotal(GenericValue orderItem, List JavaDoc adjustments) {
2220        return getOrderItemSubTotalBd(orderItem, adjustments).doubleValue();
2221    }
2222
2223    /** The passed adjustments can be all adjustments for the order, ie for all line items */
2224    public static BigDecimal JavaDoc getOrderItemSubTotalBd(GenericValue orderItem, List JavaDoc adjustments, boolean forTax, boolean forShipping) {
2225        BigDecimal JavaDoc unitPrice = orderItem.getBigDecimal("unitPrice");
2226        BigDecimal JavaDoc quantity = getOrderItemQuantityBd(orderItem);
2227        BigDecimal JavaDoc result = ZERO;
2228
2229        if (unitPrice == null || quantity == null) {
2230            Debug.logWarning("[getOrderItemTotal] unitPrice or quantity are null, using 0 for the item base price", module);
2231        } else {
2232            if (Debug.verboseOn()) Debug.logVerbose("Unit Price : " + unitPrice + " / " + "Quantity : " + quantity, module);
2233            result = unitPrice.multiply(quantity);
2234
2235            if (orderItem.getString("orderItemTypeId").compareTo("RENTAL_ORDER_ITEM") == 0) { // retrieve related work effort when required.
2236
List JavaDoc WorkOrderItemFulfillments = null;
2237                try {
2238                    WorkOrderItemFulfillments = orderItem.getRelatedCache("WorkOrderItemFulfillment");
2239                } catch (GenericEntityException e) {}
2240                Iterator JavaDoc iter = WorkOrderItemFulfillments.iterator();
2241                if (iter.hasNext()) {
2242                    GenericValue WorkOrderItemFulfillment = (GenericValue) iter.next();
2243                    GenericValue workEffort = null;
2244                    try {
2245                        workEffort = WorkOrderItemFulfillment.getRelatedOneCache("WorkEffort");
2246                    } catch (GenericEntityException e) {}
2247                    result = result.multiply(getWorkEffortRentalQuantityBd(workEffort));
2248                }
2249            }
2250        }
2251
2252        // subtotal also includes non tax and shipping adjustments; tax and shipping will be calculated using this adjusted value
2253
result =result.add(getOrderItemAdjustmentsTotalBd(orderItem, adjustments, true, false, false, forTax, forShipping));
2254
2255        return result.setScale(scale, rounding);
2256    }
2257
2258    /** @deprecated */
2259    public static double getOrderItemSubTotal(GenericValue orderItem, List JavaDoc adjustments, boolean forTax, boolean forShipping) {
2260        return getOrderItemSubTotalBd(orderItem, adjustments, forTax, forShipping).doubleValue();
2261    }
2262
2263    public static BigDecimal JavaDoc getOrderItemsTotalBd(List JavaDoc orderItems, List JavaDoc adjustments) {
2264        BigDecimal JavaDoc result = ZERO;
2265        Iterator JavaDoc itemIter = UtilMisc.toIterator(orderItems);
2266
2267        while (itemIter != null && itemIter.hasNext()) {
2268            result = result.add(getOrderItemTotalBd((GenericValue) itemIter.next(), adjustments)).setScale(scale, rounding);
2269        }
2270        return result.setScale(scale, rounding);
2271    }
2272
2273    /** @deprecated */
2274    public static double getOrderItemsTotal(List JavaDoc orderItems, List JavaDoc adjustments) {
2275        return getOrderItemsTotalBd(orderItems, adjustments).doubleValue();
2276    }
2277
2278    public static BigDecimal JavaDoc getOrderItemTotalBd(GenericValue orderItem, List JavaDoc adjustments) {
2279        // add tax and shipping to subtotal
2280
return getOrderItemSubTotalBd(orderItem, adjustments).add(getOrderItemAdjustmentsTotalBd(orderItem, adjustments, false, true, true)).setScale(scale, rounding);
2281    }
2282
2283    /** @deprecated */
2284    public static double getOrderItemTotal(GenericValue orderItem, List JavaDoc adjustments) {
2285        return getOrderItemTotalBd(orderItem, adjustments).doubleValue();
2286    }
2287
2288    public static BigDecimal JavaDoc getWorkEffortRentalQuantityBd(GenericValue workEffort){
2289        BigDecimal JavaDoc persons = new BigDecimal JavaDoc(1);
2290        if (workEffort.get("reservPersons") != null)
2291            persons = workEffort.getBigDecimal("reservPersons");
2292        BigDecimal JavaDoc secondPersonPerc = ZERO;
2293        if (workEffort.get("reserv2ndPPPerc") != null)
2294            secondPersonPerc = workEffort.getBigDecimal("reserv2ndPPPerc");
2295        BigDecimal JavaDoc nthPersonPerc = ZERO;
2296        if (workEffort.get("reservNthPPPerc") != null)
2297            nthPersonPerc = workEffort.getBigDecimal("reservNthPPPerc");
2298        long length = 1;
2299        if (workEffort.get("estimatedStartDate") != null && workEffort.get("estimatedCompletionDate") != null)
2300            length = (workEffort.getTimestamp("estimatedCompletionDate").getTime() - workEffort.getTimestamp("estimatedStartDate").getTime()) / 86400000;
2301
2302        BigDecimal JavaDoc rentalAdjustment = ZERO;
2303        if (persons.compareTo(new BigDecimal JavaDoc(1)) == 1) {
2304            if (persons.compareTo(new BigDecimal JavaDoc(2)) == 1) {
2305                persons = persons.subtract(new BigDecimal JavaDoc(2));
2306                if(nthPersonPerc.signum() == 1)
2307                    rentalAdjustment = persons.multiply(nthPersonPerc);
2308                else
2309                    rentalAdjustment = persons.multiply(secondPersonPerc);
2310                persons = new BigDecimal JavaDoc("2");
2311            }
2312            if (persons.compareTo(new BigDecimal JavaDoc("2")) == 0)
2313                rentalAdjustment = rentalAdjustment.add(secondPersonPerc);
2314        }
2315        rentalAdjustment = rentalAdjustment.add(new BigDecimal JavaDoc(100)); // add final 100 percent for first person
2316
rentalAdjustment = rentalAdjustment.divide(new BigDecimal JavaDoc(100), scale, rounding).multiply(new BigDecimal JavaDoc(String.valueOf(length)));
2317// Debug.logInfo("rental parameters....Nbr of persons:" + persons + " extra% 2nd person:" + secondPersonPerc + " extra% Nth person:" + nthPersonPerc + " Length: " + length + " total rental adjustment:" + rentalAdjustment ,module);
2318
return rentalAdjustment; // return total rental adjustment
2319
}
2320
2321    /** @deprecated */
2322    public static double getWorkEffortRentalQuantity(GenericValue workEffort) {
2323        return getWorkEffortRentalQuantityBd(workEffort).doubleValue();
2324    }
2325
2326    public static BigDecimal JavaDoc getAllOrderItemsAdjustmentsTotalBd(List JavaDoc orderItems, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
2327        BigDecimal JavaDoc result = ZERO;
2328        Iterator JavaDoc itemIter = UtilMisc.toIterator(orderItems);
2329
2330        while (itemIter != null && itemIter.hasNext()) {
2331            result = result.add(getOrderItemAdjustmentsTotalBd((GenericValue) itemIter.next(), adjustments, includeOther, includeTax, includeShipping)).setScale(scale, rounding);
2332        }
2333        return result;
2334    }
2335
2336    /** @deprecated */
2337    public static double getAllOrderItemsAdjustmentsTotal(List JavaDoc orderItems, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
2338        return getAllOrderItemsAdjustmentsTotalBd(orderItems, adjustments, includeOther, includeTax, includeShipping).doubleValue();
2339    }
2340
2341    /** The passed adjustments can be all adjustments for the order, ie for all line items */
2342    public static BigDecimal JavaDoc getOrderItemAdjustmentsTotalBd(GenericValue orderItem, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
2343        return getOrderItemAdjustmentsTotalBd(orderItem, adjustments, includeOther, includeTax, includeShipping, false, false);
2344    }
2345
2346    /** @deprecated */
2347    public static double getOrderItemAdjustmentsTotal(GenericValue orderItem, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
2348        return getOrderItemAdjustmentsTotalBd(orderItem, adjustments, includeOther, includeTax, includeShipping, false, false).doubleValue();
2349    }
2350
2351    /** The passed adjustments can be all adjustments for the order, ie for all line items */
2352    public static BigDecimal JavaDoc getOrderItemAdjustmentsTotalBd(GenericValue orderItem, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
2353        return calcItemAdjustmentsBd(getOrderItemQuantityBd(orderItem), orderItem.getBigDecimal("unitPrice"),
2354                getOrderItemAdjustmentList(orderItem, adjustments),
2355                includeOther, includeTax, includeShipping, forTax, forShipping);
2356    }
2357
2358    /** @deprecated */
2359    public double getOrderItemAdjustmentsTotal(GenericValue orderItem, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
2360        return getOrderItemAdjustmentsTotalBd(orderItem, adjustments, includeOther, includeTax, includeShipping, forTax, forShipping).doubleValue();
2361    }
2362
2363    public static List JavaDoc getOrderItemAdjustmentList(GenericValue orderItem, List JavaDoc adjustments) {
2364        return EntityUtil.filterByAnd(adjustments, UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId")));
2365    }
2366
2367    public static List JavaDoc getOrderItemStatuses(GenericValue orderItem, List JavaDoc orderStatuses) {
2368        return EntityUtil.orderBy(EntityUtil.filterByAnd(orderStatuses, UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId"))), UtilMisc.toList("-statusDatetime"));
2369    }
2370
2371
2372    // Order Item Adjs Utility Methods
2373

2374    public static BigDecimal JavaDoc calcItemAdjustmentsBd(BigDecimal JavaDoc quantity, BigDecimal JavaDoc unitPrice, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
2375        BigDecimal JavaDoc adjTotal = ZERO;
2376
2377        if (adjustments != null && adjustments.size() > 0) {
2378            List JavaDoc filteredAdjs = filterOrderAdjustments(adjustments, includeOther, includeTax, includeShipping, forTax, forShipping);
2379            Iterator JavaDoc adjIt = filteredAdjs.iterator();
2380
2381            while (adjIt.hasNext()) {
2382                GenericValue orderAdjustment = (GenericValue) adjIt.next();
2383
2384                adjTotal = adjTotal.add(OrderReadHelper.calcItemAdjustmentBd(orderAdjustment, quantity, unitPrice)).setScale(scale, rounding);
2385            }
2386        }
2387        return adjTotal;
2388    }
2389
2390    /** @deprecated */
2391    public static double calcItemAdjustments(Double JavaDoc quantity, Double JavaDoc unitPrice, List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
2392        return calcItemAdjustmentsBd(new BigDecimal JavaDoc(quantity.doubleValue()), new BigDecimal JavaDoc(unitPrice.doubleValue()), adjustments, includeOther, includeTax, includeShipping, forTax, forShipping).doubleValue();
2393    }
2394
2395    public static BigDecimal JavaDoc calcItemAdjustmentBd(GenericValue itemAdjustment, GenericValue item) {
2396        return calcItemAdjustmentBd(itemAdjustment, getOrderItemQuantityBd(item), item.getBigDecimal("unitPrice"));
2397    }
2398
2399    /** @deprecated */
2400    public static double calcItemAdjustment(GenericValue itemAdjustment, GenericValue item) {
2401        return calcItemAdjustmentBd(itemAdjustment, item).doubleValue();
2402    }
2403
2404    public static BigDecimal JavaDoc calcItemAdjustmentBd(GenericValue itemAdjustment, BigDecimal JavaDoc quantity, BigDecimal JavaDoc unitPrice) {
2405        BigDecimal JavaDoc adjustment = ZERO;
2406        if (itemAdjustment.get("amount") != null) {
2407            adjustment = adjustment.add(setScaleByType("SALES_TAX".equals(itemAdjustment.get("orderAdjustmentTypeId")), itemAdjustment.getBigDecimal("amount")));
2408        }
2409        if (Debug.verboseOn()) Debug.logVerbose("calcItemAdjustment: " + itemAdjustment + ", quantity=" + quantity + ", unitPrice=" + unitPrice + ", adjustment=" + adjustment, module);
2410        return adjustment.setScale(scale, rounding);
2411    }
2412
2413    /** @deprecated */
2414    public static double calcItemAdjustment(GenericValue itemAdjustment, Double JavaDoc quantity, Double JavaDoc unitPrice) {
2415        return calcItemAdjustmentBd(itemAdjustment, new BigDecimal JavaDoc(quantity.doubleValue()), new BigDecimal JavaDoc(unitPrice.doubleValue())).doubleValue();
2416    }
2417
2418    public static List JavaDoc filterOrderAdjustments(List JavaDoc adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
2419        List JavaDoc newOrderAdjustmentsList = new LinkedList JavaDoc();
2420
2421        if (adjustments != null && adjustments.size() > 0) {
2422            Iterator JavaDoc adjIt = adjustments.iterator();
2423
2424            while (adjIt.hasNext()) {
2425                GenericValue orderAdjustment = (GenericValue) adjIt.next();
2426
2427                boolean includeAdjustment = false;
2428
2429                if ("SALES_TAX".equals(orderAdjustment.getString("orderAdjustmentTypeId"))) {
2430                    if (includeTax) includeAdjustment = true;
2431                } else if ("SHIPPING_CHARGES".equals(orderAdjustment.getString("orderAdjustmentTypeId"))) {
2432                    if (includeShipping) includeAdjustment = true;
2433                } else {
2434                    if (includeOther) includeAdjustment = true;
2435                }
2436
2437                // default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included
2438
if (forTax && "N".equals(orderAdjustment.getString("includeInTax"))) {
2439                    includeAdjustment = false;
2440                }
2441
2442                // default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included
2443
if (forShipping && "N".equals(orderAdjustment.getString("includeInShipping"))) {
2444                    includeAdjustment = false;
2445                }
2446
2447                if (includeAdjustment) {
2448                    newOrderAdjustmentsList.add(orderAdjustment);
2449                }
2450            }
2451        }
2452        return newOrderAdjustmentsList;
2453    }
2454
2455    public static double getQuantityOnOrder(GenericDelegator delegator, String JavaDoc productId) {
2456        double quantity = 0.0;
2457
2458        // first find all open purchase orders
2459
List JavaDoc openOrdersExprs = UtilMisc.toList(new EntityExpr("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER"));
2460        openOrdersExprs.add(new EntityExpr("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"));
2461        openOrdersExprs.add(new EntityExpr("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
2462        openOrdersExprs.add(new EntityExpr("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"));
2463        openOrdersExprs.add(new EntityExpr("productId", EntityOperator.EQUALS, productId));
2464        EntityCondition openOrdersCond = new EntityConditionList(openOrdersExprs, EntityOperator.AND);
2465        List JavaDoc openOrders = null;
2466        try {
2467            openOrders = delegator.findByCondition("OrderHeaderAndItems", openOrdersCond, null, null);
2468        } catch (GenericEntityException e) {
2469            Debug.logError(e, module);
2470        }
2471
2472        if (openOrders != null && openOrders.size() > 0) {
2473            Iterator JavaDoc i = openOrders.iterator();
2474            while (i.hasNext()) {
2475                GenericValue order = (GenericValue) i.next();
2476                Double JavaDoc thisQty = order.getDouble("quantity");
2477                if (thisQty == null) {
2478                    thisQty = new Double JavaDoc(0);
2479                }
2480                quantity += thisQty.doubleValue();
2481            }
2482        }
2483
2484        return quantity;
2485    }
2486
2487    /**
2488     * Checks to see if this user has read permission on the specified order
2489     * @param userLogin The UserLogin value object to check
2490     * @param orderHeader The OrderHeader for the specified order
2491     * @return boolean True if we have read permission
2492     */

2493    public static boolean hasPermission(Security security, GenericValue userLogin, GenericValue orderHeader) {
2494        if (userLogin == null || orderHeader == null)
2495            return false;
2496
2497        if (security.hasEntityPermission("ORDERMGR", "_VIEW", userLogin)) {
2498            return true;
2499        } else if (security.hasEntityPermission("ORDERMGR", "_ROLEVIEW", userLogin)) {
2500            List JavaDoc orderRoles = null;
2501            try {
2502                orderRoles = orderHeader.getRelatedByAnd("OrderRole",
2503                        UtilMisc.toMap("partyId", userLogin.getString("partyId")));
2504            } catch (GenericEntityException e) {
2505                Debug.logError(e, "Cannot get OrderRole from OrderHeader", module);
2506            }
2507
2508            if (orderRoles.size() > 0) {
2509                // we are in at least one role
2510
return true;
2511            }
2512        }
2513
2514        return false;
2515    }
2516
2517    public static OrderReadHelper getHelper(GenericValue orderHeader) {
2518        return new OrderReadHelper(orderHeader);
2519    }
2520
2521    /**
2522     * Get orderAdjustments that have no corresponding returnAdjustment
2523     * @return orderAdjustmentList
2524     */

2525    public List JavaDoc getAvailableOrderHeaderAdjustments() {
2526        List JavaDoc orderHeaderAdjustments = this.getOrderHeaderAdjustments();
2527        List JavaDoc filteredAdjustments = new ArrayList JavaDoc();
2528        if (orderHeaderAdjustments != null) {
2529            Iterator JavaDoc orderAdjIterator = orderHeaderAdjustments.iterator();
2530            while (orderAdjIterator.hasNext()) {
2531                GenericValue orderAdjustment = (GenericValue) orderAdjIterator.next();
2532                long count = 0;
2533                try {
2534                    count = orderHeader.getDelegator().findCountByAnd("ReturnAdjustment", UtilMisc.toMap("orderAdjustmentId", orderAdjustment.get("orderAdjustmentId")));
2535                } catch (GenericEntityException e) {
2536                    Debug.logError(e, module);
2537                }
2538                if (count == 0) {
2539                    filteredAdjustments.add(orderAdjustment);
2540                }
2541            }
2542        }
2543        return filteredAdjustments;
2544    }
2545
2546    /**
2547     * Get the total return adjustments for a set of key -> value condition pairs. Done for code efficiency.
2548     * @param delegator
2549     * @param condition
2550     * @return
2551     */

2552    public static BigDecimal JavaDoc getReturnAdjustmentTotalBd(GenericDelegator delegator, Map JavaDoc condition) {
2553        BigDecimal JavaDoc total = ZERO;
2554        List JavaDoc adjustments;
2555        try {
2556            // TODO: find on a view-entity with a sum is probably more efficient
2557
adjustments = delegator.findByAnd("ReturnAdjustment", condition);
2558            if (adjustments != null) {
2559                Iterator JavaDoc adjustmentIterator = adjustments.iterator();
2560                while (adjustmentIterator.hasNext()) {
2561                    GenericValue returnAdjustment = (GenericValue) adjustmentIterator.next();
2562                    total = total.add(setScaleByType("RET_SALES_TAX_ADJ".equals(returnAdjustment.get("returnAdjustmentTypeId")),returnAdjustment.getBigDecimal("amount"))).setScale(scale, rounding);
2563                }
2564            }
2565        } catch (GenericEntityException e) {
2566            Debug.logError(e, OrderReturnServices.module);
2567        }
2568        return total.setScale(scale, rounding);
2569    }
2570
2571    /** @deprecated */
2572    public static double getReturnAdjustmentTotal(GenericDelegator delegator, Map JavaDoc condition) {
2573        return getReturnAdjustmentTotalBd(delegator, condition).doubleValue();
2574    }
2575
2576    // little helper method to set the scale according to tax type
2577
public static BigDecimal JavaDoc setScaleByType(boolean isTax, BigDecimal JavaDoc value){
2578        return isTax ? value.setScale(taxCalcScale, taxRounding) : value.setScale(scale, rounding);
2579    }
2580
2581   /** Get the quantity of order items that have been invoiced */
2582   public static double getOrderItemInvoicedQuantity(GenericValue orderItem) {
2583       double invoiced = 0;
2584       try {
2585           // this is simply the sum of quantity billed in all related OrderItemBillings
2586
List JavaDoc billings = orderItem.getRelated("OrderItemBilling");
2587           for (Iterator JavaDoc iter = billings.iterator(); iter.hasNext(); ) {
2588               GenericValue billing = (GenericValue) iter.next();
2589               Double JavaDoc quantity = billing.getDouble("quantity");
2590               if (quantity != null) {
2591                   invoiced += quantity.doubleValue();
2592               }
2593           }
2594       } catch (GenericEntityException e) {
2595           Debug.logError(e, e.getMessage(), module);
2596       }
2597       return invoiced;
2598   }
2599}
2600
Popular Tags