Source Code Cross Referenced for OrderReadHelper.java in  » ERP-CRM-Financial » ofbiz » org » ofbiz » order » order » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » ERP CRM Financial » ofbiz » org.ofbiz.order.order 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*******************************************************************************
0002:         * Licensed to the Apache Software Foundation (ASF) under one
0003:         * or more contributor license agreements.  See the NOTICE file
0004:         * distributed with this work for additional information
0005:         * regarding copyright ownership.  The ASF licenses this file
0006:         * to you under the Apache License, Version 2.0 (the
0007:         * "License"); you may not use this file except in compliance
0008:         * with the License.  You may obtain a copy of the License at
0009:         * 
0010:         * http://www.apache.org/licenses/LICENSE-2.0
0011:         * 
0012:         * Unless required by applicable law or agreed to in writing,
0013:         * software distributed under the License is distributed on an
0014:         * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
0015:         * KIND, either express or implied.  See the License for the
0016:         * specific language governing permissions and limitations
0017:         * under the License.
0018:         *******************************************************************************/package org.ofbiz.order.order;
0019:
0020:        import java.math.BigDecimal;
0021:        import org.ofbiz.base.util.UtilDateTime;
0022:        import java.sql.Timestamp;
0023:        import java.util.ArrayList;
0024:        import java.util.Arrays;
0025:        import java.util.Collection;
0026:        import java.util.HashSet;
0027:        import java.util.Iterator;
0028:        import java.util.List;
0029:        import java.util.Map;
0030:        import java.util.Set;
0031:
0032:        import javolution.util.FastList;
0033:        import javolution.util.FastMap;
0034:
0035:        import org.apache.commons.collections.set.ListOrderedSet;
0036:        import org.ofbiz.base.util.Debug;
0037:        import org.ofbiz.base.util.UtilFormatOut;
0038:        import org.ofbiz.base.util.UtilMisc;
0039:        import org.ofbiz.base.util.UtilNumber;
0040:        import org.ofbiz.base.util.UtilValidate;
0041:        import org.ofbiz.common.DataModelConstants;
0042:        import org.ofbiz.entity.GenericDelegator;
0043:        import org.ofbiz.entity.GenericEntity;
0044:        import org.ofbiz.entity.GenericEntityException;
0045:        import org.ofbiz.entity.GenericValue;
0046:        import org.ofbiz.entity.condition.EntityCondition;
0047:        import org.ofbiz.entity.condition.EntityConditionList;
0048:        import org.ofbiz.entity.condition.EntityExpr;
0049:        import org.ofbiz.entity.condition.EntityOperator;
0050:        import org.ofbiz.entity.util.EntityUtil;
0051:        import org.ofbiz.product.product.ProductWorker;
0052:        import org.ofbiz.security.Security;
0053:
0054:        /**
0055:         * Utility class for easily extracting important information from orders
0056:         *
0057:         * <p>NOTE: in the current scheme order adjustments are never included in tax or shipping,
0058:         * but order item adjustments ARE included in tax and shipping calcs unless they are
0059:         * tax or shipping adjustments or the includeInTax or includeInShipping are set to N.</p>
0060:         */
0061:        public class OrderReadHelper {
0062:
0063:            public static final String module = OrderReadHelper.class.getName();
0064:
0065:            // scales and rounding modes for BigDecimal math
0066:            public static final int scale = UtilNumber
0067:                    .getBigDecimalScale("order.decimals");
0068:            public static final int rounding = UtilNumber
0069:                    .getBigDecimalRoundingMode("order.rounding");
0070:            public static final int taxCalcScale = UtilNumber
0071:                    .getBigDecimalScale("salestax.calc.decimals");
0072:            public static final int taxFinalScale = UtilNumber
0073:                    .getBigDecimalScale("salestax.final.decimals");
0074:            public static final int taxRounding = UtilNumber
0075:                    .getBigDecimalRoundingMode("salestax.rounding");
0076:            public static final BigDecimal ZERO = (new BigDecimal("0"))
0077:                    .setScale(scale, rounding);
0078:            public static final BigDecimal percentage = (new BigDecimal("0.01"))
0079:                    .setScale(scale, rounding);
0080:
0081:            protected GenericValue orderHeader = null;
0082:            protected List orderItemAndShipGrp = null;
0083:            protected List orderItems = null;
0084:            protected List adjustments = null;
0085:            protected List paymentPrefs = null;
0086:            protected List orderStatuses = null;
0087:            protected List orderItemPriceInfos = null;
0088:            protected List orderItemShipGrpInvResList = null;
0089:            protected List orderItemIssuances = null;
0090:            protected List orderReturnItems = null;
0091:            protected BigDecimal totalPrice = null;
0092:
0093:            protected OrderReadHelper() {
0094:            }
0095:
0096:            public OrderReadHelper(GenericValue orderHeader, List adjustments,
0097:                    List orderItems) {
0098:                this .orderHeader = orderHeader;
0099:                this .adjustments = adjustments;
0100:                this .orderItems = orderItems;
0101:                if (this .orderHeader != null
0102:                        && !this .orderHeader.getEntityName().equals(
0103:                                "OrderHeader")) {
0104:                    try {
0105:                        this .orderHeader = orderHeader.getDelegator()
0106:                                .findByPrimaryKey(
0107:                                        "OrderHeader",
0108:                                        UtilMisc.toMap("orderId", orderHeader
0109:                                                .getString("orderId")));
0110:                    } catch (GenericEntityException e) {
0111:                        Debug.logError(e, module);
0112:                        this .orderHeader = null;
0113:                    }
0114:                } else if (this .orderHeader == null && orderItems != null) {
0115:                    GenericValue firstItem = EntityUtil.getFirst(orderItems);
0116:                    try {
0117:                        this .orderHeader = firstItem
0118:                                .getRelatedOne("OrderHeader");
0119:                    } catch (GenericEntityException e) {
0120:                        Debug.logError(e, module);
0121:                        this .orderHeader = null;
0122:                    }
0123:                }
0124:                if (this .orderHeader == null) {
0125:                    throw new IllegalArgumentException(
0126:                            "Order header is not valid");
0127:                }
0128:            }
0129:
0130:            public OrderReadHelper(GenericValue orderHeader) {
0131:                this (orderHeader, null, null);
0132:            }
0133:
0134:            public OrderReadHelper(List adjustments, List orderItems) {
0135:                this .adjustments = adjustments;
0136:                this .orderItems = orderItems;
0137:            }
0138:
0139:            public OrderReadHelper(GenericDelegator delegator, String orderId) {
0140:                try {
0141:                    this .orderHeader = delegator.findByPrimaryKey(
0142:                            "OrderHeader", UtilMisc.toMap("orderId", orderId));
0143:                } catch (GenericEntityException e) {
0144:                    throw new IllegalArgumentException("Invalid orderId");
0145:                }
0146:            }
0147:
0148:            // ==========================================
0149:            // ========== Order Header Methods ==========
0150:            // ==========================================
0151:
0152:            public String getOrderId() {
0153:                return orderHeader.getString("orderId");
0154:            }
0155:
0156:            public String getWebSiteId() {
0157:                return orderHeader.getString("webSiteId");
0158:            }
0159:
0160:            public String getProductStoreId() {
0161:                return orderHeader.getString("productStoreId");
0162:            }
0163:
0164:            /**
0165:             * Returns the ProductStore of this Order or null in case of Exception
0166:             */
0167:            public GenericValue getProductStore() {
0168:                String productStoreId = orderHeader.getString("productStoreId");
0169:                try {
0170:                    GenericDelegator delegator = orderHeader.getDelegator();
0171:                    GenericValue productStore = delegator
0172:                            .findByPrimaryKeyCache("ProductStore", UtilMisc
0173:                                    .toMap("productStoreId", productStoreId));
0174:                    return productStore;
0175:                } catch (GenericEntityException ex) {
0176:                    Debug.logError(
0177:                            "Failed to get product store for order header ["
0178:                                    + orderHeader + "] due to exception "
0179:                                    + ex.getMessage(), module);
0180:                    return null;
0181:                }
0182:            }
0183:
0184:            public String getOrderTypeId() {
0185:                return orderHeader.getString("orderTypeId");
0186:            }
0187:
0188:            public String getCurrency() {
0189:                return orderHeader.getString("currencyUom");
0190:            }
0191:
0192:            public String getOrderName() {
0193:                return orderHeader.getString("orderName");
0194:            }
0195:
0196:            public List getAdjustments() {
0197:                if (adjustments == null) {
0198:                    try {
0199:                        adjustments = orderHeader.getRelated("OrderAdjustment");
0200:                    } catch (GenericEntityException e) {
0201:                        Debug.logError(e, module);
0202:                    }
0203:                    if (adjustments == null)
0204:                        adjustments = new ArrayList();
0205:                }
0206:                return adjustments;
0207:            }
0208:
0209:            public List getPaymentPreferences() {
0210:                if (paymentPrefs == null) {
0211:                    try {
0212:                        paymentPrefs = orderHeader.getRelated(
0213:                                "OrderPaymentPreference", UtilMisc
0214:                                        .toList("orderPaymentPreferenceId"));
0215:                    } catch (GenericEntityException e) {
0216:                        Debug.logError(e, module);
0217:                    }
0218:                }
0219:                return paymentPrefs;
0220:            }
0221:
0222:            /**
0223:             * Returns a Map of paymentMethodId -> amount charged (Double) based on PaymentGatewayResponse.  
0224:             * @return
0225:             */
0226:            public Map getReceivedPaymentTotalsByPaymentMethod() {
0227:                Map paymentMethodAmounts = FastMap.newInstance();
0228:                List paymentPrefs = getPaymentPreferences();
0229:                Iterator ppit = paymentPrefs.iterator();
0230:                while (ppit.hasNext()) {
0231:                    GenericValue paymentPref = (GenericValue) ppit.next();
0232:                    List paymentGatewayResponses = new ArrayList();
0233:                    try {
0234:                        paymentGatewayResponses = paymentPref.getRelatedByAnd(
0235:                                "PaymentGatewayResponse", UtilMisc.toMap(
0236:                                        "paymentServiceTypeEnumId",
0237:                                        "PRDS_PAY_CAPTURE"));
0238:                    } catch (GenericEntityException e) {
0239:                        Debug.logError(e, module);
0240:                    }
0241:
0242:                    BigDecimal chargedToPaymentPref = ZERO;
0243:                    Iterator pgrit = paymentGatewayResponses.iterator();
0244:                    while (pgrit.hasNext()) {
0245:                        GenericValue paymentGatewayResponse = (GenericValue) pgrit
0246:                                .next();
0247:                        if (paymentGatewayResponse.get("amount") != null) {
0248:                            chargedToPaymentPref = chargedToPaymentPref.add(
0249:                                    paymentGatewayResponse
0250:                                            .getBigDecimal("amount")).setScale(
0251:                                    scale + 1, rounding);
0252:                        }
0253:                    }
0254:
0255:                    // if chargedToPaymentPref > 0
0256:                    if (chargedToPaymentPref.compareTo(ZERO) == 1) {
0257:                        // key of the resulting map is paymentMethodId or paymentMethodTypeId if the paymentMethodId is not available
0258:                        String paymentMethodKey = paymentPref
0259:                                .getString("paymentMethodId") != null ? paymentPref
0260:                                .getString("paymentMethodId")
0261:                                : paymentPref.getString("paymentMethodTypeId");
0262:                        paymentMethodAmounts.put(paymentMethodKey, new Double(
0263:                                chargedToPaymentPref.setScale(scale, rounding)
0264:                                        .doubleValue()));
0265:                    }
0266:                }
0267:                return paymentMethodAmounts;
0268:            }
0269:
0270:            /**
0271:             * Returns a Map of paymentMethodId -> amount refunded 
0272:             * @return
0273:             */
0274:            public Map getReturnedTotalsByPaymentMethod() {
0275:                Map paymentMethodAmounts = FastMap.newInstance();
0276:                List paymentPrefs = getPaymentPreferences();
0277:                Iterator ppit = paymentPrefs.iterator();
0278:                while (ppit.hasNext()) {
0279:                    GenericValue paymentPref = (GenericValue) ppit.next();
0280:                    List returnItemResponses = new ArrayList();
0281:                    try {
0282:                        returnItemResponses = orderHeader
0283:                                .getDelegator()
0284:                                .findByAnd(
0285:                                        "ReturnItemResponse",
0286:                                        UtilMisc
0287:                                                .toMap(
0288:                                                        "orderPaymentPreferenceId",
0289:                                                        paymentPref
0290:                                                                .getString("orderPaymentPreferenceId")));
0291:                    } catch (GenericEntityException e) {
0292:                        Debug.logError(e, module);
0293:                    }
0294:                    BigDecimal refundedToPaymentPref = ZERO;
0295:                    Iterator ririt = returnItemResponses.iterator();
0296:                    while (ririt.hasNext()) {
0297:                        GenericValue returnItemResponse = (GenericValue) ririt
0298:                                .next();
0299:                        refundedToPaymentPref = refundedToPaymentPref.add(
0300:                                returnItemResponse
0301:                                        .getBigDecimal("responseAmount"))
0302:                                .setScale(scale + 1, rounding);
0303:                    }
0304:
0305:                    // if refundedToPaymentPref > 0
0306:                    if (refundedToPaymentPref.compareTo(ZERO) == 1) {
0307:                        String paymentMethodId = paymentPref
0308:                                .getString("paymentMethodId") != null ? paymentPref
0309:                                .getString("paymentMethodId")
0310:                                : paymentPref.getString("paymentMethodTypeId");
0311:                        paymentMethodAmounts.put(paymentMethodId, new Double(
0312:                                refundedToPaymentPref.setScale(scale, rounding)
0313:                                        .doubleValue()));
0314:                    }
0315:                }
0316:                return paymentMethodAmounts;
0317:            }
0318:
0319:            public List getOrderPayments() {
0320:                return getOrderPayments(null);
0321:            }
0322:
0323:            public List getOrderPayments(GenericValue orderPaymentPreference) {
0324:                List orderPayments = new ArrayList();
0325:                List prefs = null;
0326:
0327:                if (orderPaymentPreference == null) {
0328:                    prefs = getPaymentPreferences();
0329:                } else {
0330:                    prefs = UtilMisc.toList(orderPaymentPreference);
0331:                }
0332:                if (prefs != null) {
0333:                    Iterator i = prefs.iterator();
0334:                    while (i.hasNext()) {
0335:                        GenericValue payPref = (GenericValue) i.next();
0336:                        try {
0337:                            orderPayments.addAll(payPref.getRelated("Payment"));
0338:                        } catch (GenericEntityException e) {
0339:                            Debug.logError(e, module);
0340:                            return null;
0341:                        }
0342:                    }
0343:                }
0344:                return orderPayments;
0345:            }
0346:
0347:            public List getOrderStatuses() {
0348:                if (orderStatuses == null) {
0349:                    try {
0350:                        orderStatuses = orderHeader.getRelated("OrderStatus");
0351:                    } catch (GenericEntityException e) {
0352:                        Debug.logError(e, module);
0353:                    }
0354:                }
0355:                return orderStatuses;
0356:            }
0357:
0358:            public List getOrderTerms() {
0359:                try {
0360:                    return orderHeader.getRelated("OrderTerm");
0361:                } catch (GenericEntityException e) {
0362:                    Debug.logError(e, module);
0363:                    return null;
0364:                }
0365:            }
0366:
0367:            /**
0368:             * @return Long number of days from termDays of first FIN_PAYMENT_TERM
0369:             */
0370:            public Long getOrderTermNetDays() {
0371:                List orderTerms = EntityUtil.filterByAnd(getOrderTerms(),
0372:                        UtilMisc.toMap("termTypeId", "FIN_PAYMENT_TERM"));
0373:                if ((orderTerms == null) || (orderTerms.size() == 0)) {
0374:                    return null;
0375:                } else if (orderTerms.size() > 1) {
0376:                    Debug.logWarning("Found " + orderTerms.size()
0377:                            + " FIN_PAYMENT_TERM order terms for orderId ["
0378:                            + getOrderId() + "], using the first one ", module);
0379:                }
0380:                return ((GenericValue) orderTerms.get(0)).getLong("termDays");
0381:            }
0382:
0383:            /** @deprecated */
0384:            public String getShippingMethod() {
0385:                throw new IllegalArgumentException(
0386:                        "You must call the getShippingMethod method with the shipGroupdSeqId parameter, this is no londer supported since a single OrderShipmentPreference is no longer used.");
0387:            }
0388:
0389:            public String getShippingMethod(String shipGroupSeqId) {
0390:                try {
0391:                    GenericValue shipGroup = orderHeader.getDelegator()
0392:                            .findByPrimaryKey(
0393:                                    "OrderItemShipGroup",
0394:                                    UtilMisc.toMap("orderId", orderHeader
0395:                                            .getString("orderId"),
0396:                                            "shipGroupSeqId", shipGroupSeqId));
0397:
0398:                    if (shipGroup != null) {
0399:                        GenericValue carrierShipmentMethod = shipGroup
0400:                                .getRelatedOne("CarrierShipmentMethod");
0401:
0402:                        if (carrierShipmentMethod != null) {
0403:                            GenericValue shipmentMethodType = carrierShipmentMethod
0404:                                    .getRelatedOne("ShipmentMethodType");
0405:
0406:                            if (shipmentMethodType != null) {
0407:                                return UtilFormatOut.checkNull(shipGroup
0408:                                        .getString("carrierPartyId"))
0409:                                        + " "
0410:                                        + UtilFormatOut
0411:                                                .checkNull(shipmentMethodType
0412:                                                        .getString("description"));
0413:                            }
0414:                        }
0415:                        return UtilFormatOut.checkNull(shipGroup
0416:                                .getString("carrierPartyId"));
0417:                    }
0418:                } catch (GenericEntityException e) {
0419:                    Debug.logWarning(e, module);
0420:                }
0421:                return "";
0422:            }
0423:
0424:            /** @deprecated */
0425:            public String getShippingMethodCode() {
0426:                throw new IllegalArgumentException(
0427:                        "You must call the getShippingMethodCode method with the shipGroupdSeqId parameter, this is no londer supported since a single OrderShipmentPreference is no longer used.");
0428:            }
0429:
0430:            public String getShippingMethodCode(String shipGroupSeqId) {
0431:                try {
0432:                    GenericValue shipGroup = orderHeader.getDelegator()
0433:                            .findByPrimaryKey(
0434:                                    "OrderItemShipGroup",
0435:                                    UtilMisc.toMap("orderId", orderHeader
0436:                                            .getString("orderId"),
0437:                                            "shipGroupSeqId", shipGroupSeqId));
0438:
0439:                    if (shipGroup != null) {
0440:                        GenericValue carrierShipmentMethod = shipGroup
0441:                                .getRelatedOne("CarrierShipmentMethod");
0442:
0443:                        if (carrierShipmentMethod != null) {
0444:                            GenericValue shipmentMethodType = carrierShipmentMethod
0445:                                    .getRelatedOne("ShipmentMethodType");
0446:
0447:                            if (shipmentMethodType != null) {
0448:                                return UtilFormatOut
0449:                                        .checkNull(shipmentMethodType
0450:                                                .getString("shipmentMethodTypeId"))
0451:                                        + "@"
0452:                                        + UtilFormatOut.checkNull(shipGroup
0453:                                                .getString("carrierPartyId"));
0454:                            }
0455:                        }
0456:                        return UtilFormatOut.checkNull(shipGroup
0457:                                .getString("carrierPartyId"));
0458:                    }
0459:                } catch (GenericEntityException e) {
0460:                    Debug.logWarning(e, module);
0461:                }
0462:                return "";
0463:            }
0464:
0465:            public boolean hasShippingAddress() {
0466:                if (UtilValidate.isNotEmpty(this .getShippingLocations())) {
0467:                    return true;
0468:                }
0469:                return false;
0470:            }
0471:
0472:            public GenericValue getOrderItemShipGroup(String shipGroupSeqId) {
0473:                try {
0474:                    return orderHeader.getDelegator().findByPrimaryKey(
0475:                            "OrderItemShipGroup",
0476:                            UtilMisc.toMap("orderId", orderHeader
0477:                                    .getString("orderId"), "shipGroupSeqId",
0478:                                    shipGroupSeqId));
0479:                } catch (GenericEntityException e) {
0480:                    Debug.logWarning(e, module);
0481:                }
0482:                return null;
0483:            }
0484:
0485:            public List getOrderItemShipGroups() {
0486:                try {
0487:                    return orderHeader.getRelated("OrderItemShipGroup",
0488:                            UtilMisc.toList("shipGroupSeqId"));
0489:                } catch (GenericEntityException e) {
0490:                    Debug.logWarning(e, module);
0491:                }
0492:                return null;
0493:            }
0494:
0495:            public List getShippingLocations() {
0496:                List shippingLocations = FastList.newInstance();
0497:                List shippingCms = this 
0498:                        .getOrderContactMechs("SHIPPING_LOCATION");
0499:                if (shippingCms != null) {
0500:                    Iterator i = shippingCms.iterator();
0501:                    while (i.hasNext()) {
0502:                        GenericValue ocm = (GenericValue) i.next();
0503:                        if (ocm != null) {
0504:                            try {
0505:                                GenericValue addr = ocm
0506:                                        .getDelegator()
0507:                                        .findByPrimaryKey(
0508:                                                "PostalAddress",
0509:                                                UtilMisc
0510:                                                        .toMap(
0511:                                                                "contactMechId",
0512:                                                                ocm
0513:                                                                        .getString("contactMechId")));
0514:                                if (addr != null) {
0515:                                    shippingLocations.add(addr);
0516:                                }
0517:                            } catch (GenericEntityException e) {
0518:                                Debug.logWarning(e, module);
0519:                            }
0520:                        }
0521:                    }
0522:                }
0523:                return shippingLocations;
0524:            }
0525:
0526:            public GenericValue getShippingAddress(String shipGroupSeqId) {
0527:                try {
0528:                    GenericValue shipGroup = orderHeader.getDelegator()
0529:                            .findByPrimaryKey(
0530:                                    "OrderItemShipGroup",
0531:                                    UtilMisc.toMap("orderId", orderHeader
0532:                                            .getString("orderId"),
0533:                                            "shipGroupSeqId", shipGroupSeqId));
0534:
0535:                    if (shipGroup != null) {
0536:                        return shipGroup.getRelatedOne("PostalAddress");
0537:
0538:                    }
0539:                } catch (GenericEntityException e) {
0540:                    Debug.logWarning(e, module);
0541:                }
0542:                return null;
0543:            }
0544:
0545:            /** @deprecated */
0546:            public GenericValue getShippingAddress() {
0547:                try {
0548:                    GenericValue orderContactMech = EntityUtil
0549:                            .getFirst(orderHeader.getRelatedByAnd(
0550:                                    "OrderContactMech", UtilMisc.toMap(
0551:                                            "contactMechPurposeTypeId",
0552:                                            "SHIPPING_LOCATION")));
0553:
0554:                    if (orderContactMech != null) {
0555:                        GenericValue contactMech = orderContactMech
0556:                                .getRelatedOne("ContactMech");
0557:
0558:                        if (contactMech != null) {
0559:                            return contactMech.getRelatedOne("PostalAddress");
0560:                        }
0561:                    }
0562:                } catch (GenericEntityException e) {
0563:                    Debug.logWarning(e, module);
0564:                }
0565:                return null;
0566:            }
0567:
0568:            public List getBillingLocations() {
0569:                List billingLocations = FastList.newInstance();
0570:                List billingCms = this .getOrderContactMechs("BILLING_LOCATION");
0571:                if (billingCms != null) {
0572:                    Iterator i = billingCms.iterator();
0573:                    while (i.hasNext()) {
0574:                        GenericValue ocm = (GenericValue) i.next();
0575:                        if (ocm != null) {
0576:                            try {
0577:                                GenericValue addr = ocm
0578:                                        .getDelegator()
0579:                                        .findByPrimaryKey(
0580:                                                "PostalAddress",
0581:                                                UtilMisc
0582:                                                        .toMap(
0583:                                                                "contactMechId",
0584:                                                                ocm
0585:                                                                        .getString("contactMechId")));
0586:                                if (addr != null) {
0587:                                    billingLocations.add(addr);
0588:                                }
0589:                            } catch (GenericEntityException e) {
0590:                                Debug.logWarning(e, module);
0591:                            }
0592:                        }
0593:                    }
0594:                }
0595:                return billingLocations;
0596:            }
0597:
0598:            /** @deprecated */
0599:            public GenericValue getBillingAddress() {
0600:                GenericValue billingAddress = null;
0601:                try {
0602:                    GenericValue orderContactMech = EntityUtil
0603:                            .getFirst(orderHeader.getRelatedByAnd(
0604:                                    "OrderContactMech", UtilMisc.toMap(
0605:                                            "contactMechPurposeTypeId",
0606:                                            "BILLING_LOCATION")));
0607:
0608:                    if (orderContactMech != null) {
0609:                        GenericValue contactMech = orderContactMech
0610:                                .getRelatedOne("ContactMech");
0611:
0612:                        if (contactMech != null) {
0613:                            billingAddress = contactMech
0614:                                    .getRelatedOne("PostalAddress");
0615:                        }
0616:                    }
0617:                } catch (GenericEntityException e) {
0618:                    Debug.logWarning(e, module);
0619:                }
0620:
0621:                if (billingAddress == null) {
0622:                    // get the address from the billing account
0623:                    GenericValue billingAccount = getBillingAccount();
0624:                    if (billingAccount != null) {
0625:                        try {
0626:                            billingAddress = billingAccount
0627:                                    .getRelatedOne("PostalAddress");
0628:                        } catch (GenericEntityException e) {
0629:                            Debug.logWarning(e, module);
0630:                        }
0631:                    } else {
0632:                        // get the address from the first payment method
0633:                        GenericValue paymentPreference = EntityUtil
0634:                                .getFirst(getPaymentPreferences());
0635:                        if (paymentPreference != null) {
0636:                            try {
0637:                                GenericValue paymentMethod = paymentPreference
0638:                                        .getRelatedOne("PaymentMethod");
0639:                                if (paymentMethod != null) {
0640:                                    GenericValue creditCard = paymentMethod
0641:                                            .getRelatedOne("CreditCard");
0642:                                    if (creditCard != null) {
0643:                                        billingAddress = creditCard
0644:                                                .getRelatedOne("PostalAddress");
0645:                                    } else {
0646:                                        GenericValue eftAccount = paymentMethod
0647:                                                .getRelatedOne("EftAccount");
0648:                                        if (eftAccount != null) {
0649:                                            billingAddress = eftAccount
0650:                                                    .getRelatedOne("PostalAddress");
0651:                                        }
0652:                                    }
0653:                                }
0654:                            } catch (GenericEntityException e) {
0655:                                Debug.logWarning(e, module);
0656:                            }
0657:                        }
0658:                    }
0659:                }
0660:                return billingAddress;
0661:            }
0662:
0663:            public List getOrderContactMechs(String purposeTypeId) {
0664:                try {
0665:                    return orderHeader.getRelatedByAnd("OrderContactMech",
0666:                            UtilMisc.toMap("contactMechPurposeTypeId",
0667:                                    purposeTypeId));
0668:                } catch (GenericEntityException e) {
0669:                    Debug.logWarning(e, module);
0670:                }
0671:                return null;
0672:            }
0673:
0674:            public Timestamp getEarliestShipByDate() {
0675:                try {
0676:                    List groups = orderHeader.getRelated("OrderItemShipGroup",
0677:                            UtilMisc.toList("shipByDate"));
0678:                    if (groups.size() > 0) {
0679:                        GenericValue group = (GenericValue) groups.get(0);
0680:                        return group.getTimestamp("shipByDate");
0681:                    }
0682:                } catch (GenericEntityException e) {
0683:                    Debug.logWarning(e, module);
0684:                }
0685:                return null;
0686:            }
0687:
0688:            public Timestamp getLatestShipAfterDate() {
0689:                try {
0690:                    List groups = orderHeader.getRelated("OrderItemShipGroup",
0691:                            UtilMisc.toList("shipAfterDate DESC"));
0692:                    if (groups.size() > 0) {
0693:                        GenericValue group = (GenericValue) groups.get(0);
0694:                        return group.getTimestamp("shipAfterDate");
0695:                    }
0696:                } catch (GenericEntityException e) {
0697:                    Debug.logWarning(e, module);
0698:                }
0699:                return null;
0700:            }
0701:
0702:            public String getCurrentStatusString() {
0703:                GenericValue statusItem = null;
0704:                try {
0705:                    statusItem = orderHeader.getRelatedOneCache("StatusItem");
0706:                } catch (GenericEntityException e) {
0707:                    Debug.logError(e, module);
0708:                }
0709:                if (statusItem != null) {
0710:                    return statusItem.getString("description");
0711:                } else {
0712:                    return orderHeader.getString("statusId");
0713:                }
0714:            }
0715:
0716:            public String getStatusString() {
0717:                List orderStatusList = this .getOrderHeaderStatuses();
0718:
0719:                if (orderStatusList == null || orderStatusList.size() == 0)
0720:                    return "";
0721:
0722:                Iterator orderStatusIter = orderStatusList.iterator();
0723:                StringBuffer orderStatusString = new StringBuffer(50);
0724:
0725:                try {
0726:                    boolean isCurrent = true;
0727:                    while (orderStatusIter.hasNext()) {
0728:                        GenericValue orderStatus = (GenericValue) orderStatusIter
0729:                                .next();
0730:                        GenericValue statusItem = orderStatus
0731:                                .getRelatedOneCache("StatusItem");
0732:
0733:                        if (statusItem != null) {
0734:                            orderStatusString.append(statusItem
0735:                                    .getString("description"));
0736:                        } else {
0737:                            orderStatusString.append(orderStatus
0738:                                    .getString("statusId"));
0739:                        }
0740:
0741:                        if (isCurrent && orderStatusIter.hasNext()) {
0742:                            orderStatusString.append(" (");
0743:                            isCurrent = false;
0744:                        } else {
0745:                            if (orderStatusIter.hasNext()) {
0746:                                orderStatusString.append("/");
0747:                            } else {
0748:                                if (!isCurrent) {
0749:                                    orderStatusString.append(")");
0750:                                }
0751:                            }
0752:                        }
0753:                    }
0754:                } catch (GenericEntityException e) {
0755:                    Debug.logError(e,
0756:                            "Error getting Order Status information: "
0757:                                    + e.toString(), module);
0758:                }
0759:
0760:                return orderStatusString.toString();
0761:            }
0762:
0763:            public GenericValue getBillingAccount() {
0764:                GenericValue billingAccount = null;
0765:                try {
0766:                    billingAccount = orderHeader
0767:                            .getRelatedOne("BillingAccount");
0768:                } catch (GenericEntityException e) {
0769:                    Debug.logError(e, module);
0770:                }
0771:                return billingAccount;
0772:            }
0773:
0774:            /**
0775:             * Returns the OrderPaymentPreference.maxAmount for the billing account associated with the order, or 0 if there is no
0776:             * billing account or no max amount set
0777:             */
0778:            public double getBillingAccountMaxAmount() {
0779:                if (getBillingAccount() == null) {
0780:                    return 0.0;
0781:                } else {
0782:                    List paymentPreferences = getPaymentPreferences();
0783:                    GenericValue billingAccountPaymentPreference = EntityUtil
0784:                            .getFirst(EntityUtil.filterByAnd(
0785:                                    paymentPreferences, UtilMisc.toMap(
0786:                                            "paymentMethodTypeId",
0787:                                            "EXT_BILLACT")));
0788:                    if ((billingAccountPaymentPreference != null)
0789:                            && (billingAccountPaymentPreference
0790:                                    .getDouble("maxAmount") != null)) {
0791:                        return billingAccountPaymentPreference.getDouble(
0792:                                "maxAmount").doubleValue();
0793:                    } else {
0794:                        return 0.0;
0795:                    }
0796:                }
0797:            }
0798:
0799:            /**
0800:             * Returns party from OrderRole of BILL_TO_CUSTOMER
0801:             */
0802:            public GenericValue getBillToParty() {
0803:                return this .getPartyFromRole("BILL_TO_CUSTOMER");
0804:            }
0805:
0806:            /**
0807:             * Returns party from OrderRole of BILL_FROM_VENDOR
0808:             */
0809:            public GenericValue getBillFromParty() {
0810:                return this .getPartyFromRole("BILL_FROM_VENDOR");
0811:            }
0812:
0813:            /**
0814:             * Returns party from OrderRole of SHIP_TO_CUSTOMER
0815:             */
0816:            public GenericValue getShipToParty() {
0817:                return this .getPartyFromRole("SHIP_TO_CUSTOMER");
0818:            }
0819:
0820:            /**
0821:             * Returns party from OrderRole of PLACING_CUSTOMER
0822:             */
0823:            public GenericValue getPlacingParty() {
0824:                return this .getPartyFromRole("PLACING_CUSTOMER");
0825:            }
0826:
0827:            /**
0828:             * Returns party from OrderRole of END_USER_CUSTOMER
0829:             */
0830:            public GenericValue getEndUserParty() {
0831:                return this .getPartyFromRole("END_USER_CUSTOMER");
0832:            }
0833:
0834:            /**
0835:             * Returns party from OrderRole of SUPPLIER_AGENT
0836:             */
0837:            public GenericValue getSupplierAgent() {
0838:                return this .getPartyFromRole("SUPPLIER_AGENT");
0839:            }
0840:
0841:            public GenericValue getPartyFromRole(String roleTypeId) {
0842:                GenericDelegator delegator = orderHeader.getDelegator();
0843:                GenericValue partyObject = null;
0844:                try {
0845:                    GenericValue orderRole = EntityUtil.getFirst(orderHeader
0846:                            .getRelatedByAnd("OrderRole", UtilMisc.toMap(
0847:                                    "roleTypeId", roleTypeId)));
0848:
0849:                    if (orderRole != null) {
0850:                        partyObject = delegator.findByPrimaryKey("Person",
0851:                                UtilMisc.toMap("partyId", orderRole
0852:                                        .getString("partyId")));
0853:
0854:                        if (partyObject == null) {
0855:                            partyObject = delegator.findByPrimaryKey(
0856:                                    "PartyGroup", UtilMisc.toMap("partyId",
0857:                                            orderRole.getString("partyId")));
0858:                        }
0859:                    }
0860:                } catch (GenericEntityException e) {
0861:                    Debug.logError(e, module);
0862:                }
0863:                return partyObject;
0864:            }
0865:
0866:            public String getDistributorId() {
0867:                try {
0868:                    GenericEntity distributorRole = EntityUtil
0869:                            .getFirst(orderHeader
0870:                                    .getRelatedByAnd("OrderRole", UtilMisc
0871:                                            .toMap("roleTypeId", "DISTRIBUTOR")));
0872:
0873:                    return distributorRole == null ? null : distributorRole
0874:                            .getString("partyId");
0875:                } catch (GenericEntityException e) {
0876:                    Debug.logWarning(e, module);
0877:                }
0878:                return null;
0879:            }
0880:
0881:            public String getAffiliateId() {
0882:                try {
0883:                    GenericEntity distributorRole = EntityUtil
0884:                            .getFirst(orderHeader.getRelatedByAnd("OrderRole",
0885:                                    UtilMisc.toMap("roleTypeId", "AFFILIATE")));
0886:
0887:                    return distributorRole == null ? null : distributorRole
0888:                            .getString("partyId");
0889:                } catch (GenericEntityException e) {
0890:                    Debug.logWarning(e, module);
0891:                }
0892:                return null;
0893:            }
0894:
0895:            public BigDecimal getShippingTotalBd() {
0896:                return OrderReadHelper.calcOrderAdjustmentsBd(
0897:                        getOrderHeaderAdjustments(), getOrderItemsSubTotalBd(),
0898:                        false, false, true);
0899:            }
0900:
0901:            /** @deprecated Use getShippingTotalBd() instead */
0902:            public double getShippingTotal() {
0903:                return getShippingTotalBd().doubleValue();
0904:            }
0905:
0906:            public BigDecimal getHeaderTaxTotalBd() {
0907:                return OrderReadHelper.calcOrderAdjustmentsBd(
0908:                        getOrderHeaderAdjustments(), getOrderItemsSubTotalBd(),
0909:                        false, true, false);
0910:            }
0911:
0912:            /** @deprecated Use getHeaderTaxTotalBd() instead */
0913:            public double getHeaderTaxTotal() {
0914:                return getHeaderTaxTotalBd().doubleValue();
0915:            }
0916:
0917:            public BigDecimal getTaxTotalBd() {
0918:                return OrderReadHelper.calcOrderAdjustmentsBd(getAdjustments(),
0919:                        getOrderItemsSubTotalBd(), false, true, false);
0920:            }
0921:
0922:            /** @deprecated Use getTaxTotalBd() instead */
0923:            public double getTaxTotal() {
0924:                return getTaxTotalBd().doubleValue();
0925:            }
0926:
0927:            public Set getItemFeatureSet(GenericValue item) {
0928:                Set featureSet = new ListOrderedSet();
0929:                List featureAppls = null;
0930:                if (item.get("productId") != null) {
0931:                    try {
0932:                        featureAppls = item.getDelegator().findByAndCache(
0933:                                "ProductFeatureAppl",
0934:                                UtilMisc.toMap("productId", item
0935:                                        .getString("productId")));
0936:                        List filterExprs = UtilMisc.toList(new EntityExpr(
0937:                                "productFeatureApplTypeId",
0938:                                EntityOperator.EQUALS, "STANDARD_FEATURE"));
0939:                        filterExprs.add(new EntityExpr(
0940:                                "productFeatureApplTypeId",
0941:                                EntityOperator.EQUALS, "REQUIRED_FEATURE"));
0942:                        featureAppls = EntityUtil.filterByOr(featureAppls,
0943:                                filterExprs);
0944:                    } catch (GenericEntityException e) {
0945:                        Debug.logError(e,
0946:                                "Unable to get ProductFeatureAppl for item : "
0947:                                        + item, module);
0948:                    }
0949:                    if (featureAppls != null) {
0950:                        Iterator fai = featureAppls.iterator();
0951:                        while (fai.hasNext()) {
0952:                            GenericValue appl = (GenericValue) fai.next();
0953:                            featureSet.add(appl.getString("productFeatureId"));
0954:                        }
0955:                    }
0956:                }
0957:
0958:                // get the ADDITIONAL_FEATURE adjustments
0959:                List additionalFeatures = null;
0960:                try {
0961:                    additionalFeatures = item.getRelatedByAnd(
0962:                            "OrderAdjustment", UtilMisc.toMap(
0963:                                    "orderAdjustmentTypeId",
0964:                                    "ADDITIONAL_FEATURE"));
0965:                } catch (GenericEntityException e) {
0966:                    Debug
0967:                            .logError(e,
0968:                                    "Unable to get OrderAdjustment from item : "
0969:                                            + item, module);
0970:                }
0971:                if (additionalFeatures != null) {
0972:                    Iterator afi = additionalFeatures.iterator();
0973:                    while (afi.hasNext()) {
0974:                        GenericValue adj = (GenericValue) afi.next();
0975:                        String featureId = adj.getString("productFeatureId");
0976:                        if (featureId != null) {
0977:                            featureSet.add(featureId);
0978:                        }
0979:                    }
0980:                }
0981:
0982:                return featureSet;
0983:            }
0984:
0985:            public Map getFeatureIdQtyMap(String shipGroupSeqId) {
0986:                Map featureMap = FastMap.newInstance();
0987:                List validItems = getValidOrderItems(shipGroupSeqId);
0988:                if (validItems != null) {
0989:                    Iterator i = validItems.iterator();
0990:                    while (i.hasNext()) {
0991:                        GenericValue item = (GenericValue) i.next();
0992:                        List featureAppls = null;
0993:                        if (item.get("productId") != null) {
0994:                            try {
0995:                                featureAppls = item
0996:                                        .getDelegator()
0997:                                        .findByAndCache(
0998:                                                "ProductFeatureAppl",
0999:                                                UtilMisc
1000:                                                        .toMap(
1001:                                                                "productId",
1002:                                                                item
1003:                                                                        .getString("productId")));
1004:                                List filterExprs = UtilMisc
1005:                                        .toList(new EntityExpr(
1006:                                                "productFeatureApplTypeId",
1007:                                                EntityOperator.EQUALS,
1008:                                                "STANDARD_FEATURE"));
1009:                                filterExprs.add(new EntityExpr(
1010:                                        "productFeatureApplTypeId",
1011:                                        EntityOperator.EQUALS,
1012:                                        "REQUIRED_FEATURE"));
1013:                                featureAppls = EntityUtil.filterByOr(
1014:                                        featureAppls, filterExprs);
1015:                            } catch (GenericEntityException e) {
1016:                                Debug.logError(e,
1017:                                        "Unable to get ProductFeatureAppl for item : "
1018:                                                + item, module);
1019:                            }
1020:                            if (featureAppls != null) {
1021:                                Iterator fai = featureAppls.iterator();
1022:                                while (fai.hasNext()) {
1023:                                    GenericValue appl = (GenericValue) fai
1024:                                            .next();
1025:                                    Double lastQuantity = (Double) featureMap
1026:                                            .get(appl
1027:                                                    .getString("productFeatureId"));
1028:                                    if (lastQuantity == null) {
1029:                                        lastQuantity = new Double(0);
1030:                                    }
1031:                                    Double newQuantity = new Double(
1032:                                            lastQuantity.doubleValue()
1033:                                                    + getOrderItemQuantity(item)
1034:                                                            .doubleValue());
1035:                                    featureMap.put(appl
1036:                                            .getString("productFeatureId"),
1037:                                            newQuantity);
1038:                                }
1039:                            }
1040:                        }
1041:
1042:                        // get the ADDITIONAL_FEATURE adjustments
1043:                        List additionalFeatures = null;
1044:                        try {
1045:                            additionalFeatures = item.getRelatedByAnd(
1046:                                    "OrderAdjustment", UtilMisc.toMap(
1047:                                            "orderAdjustmentTypeId",
1048:                                            "ADDITIONAL_FEATURE"));
1049:                        } catch (GenericEntityException e) {
1050:                            Debug.logError(e,
1051:                                    "Unable to get OrderAdjustment from item : "
1052:                                            + item, module);
1053:                        }
1054:                        if (additionalFeatures != null) {
1055:                            Iterator afi = additionalFeatures.iterator();
1056:                            while (afi.hasNext()) {
1057:                                GenericValue adj = (GenericValue) afi.next();
1058:                                String featureId = adj
1059:                                        .getString("productFeatureId");
1060:                                if (featureId != null) {
1061:                                    Double lastQuantity = (Double) featureMap
1062:                                            .get(featureId);
1063:                                    if (lastQuantity == null) {
1064:                                        lastQuantity = new Double(0);
1065:                                    }
1066:                                    Double newQuantity = new Double(
1067:                                            lastQuantity.doubleValue()
1068:                                                    + getOrderItemQuantity(item)
1069:                                                            .doubleValue());
1070:                                    featureMap.put(featureId, newQuantity);
1071:                                }
1072:                            }
1073:                        }
1074:                    }
1075:                }
1076:
1077:                return featureMap;
1078:            }
1079:
1080:            public boolean shippingApplies() {
1081:                boolean shippingApplies = false;
1082:                List validItems = this .getValidOrderItems();
1083:                if (validItems != null) {
1084:                    Iterator i = validItems.iterator();
1085:                    while (i.hasNext()) {
1086:                        GenericValue item = (GenericValue) i.next();
1087:                        GenericValue product = null;
1088:                        try {
1089:                            product = item.getRelatedOne("Product");
1090:                        } catch (GenericEntityException e) {
1091:                            Debug
1092:                                    .logError(
1093:                                            e,
1094:                                            "Problem getting Product from OrderItem; returning 0",
1095:                                            module);
1096:                        }
1097:                        if (product != null) {
1098:                            if (ProductWorker.shippingApplies(product)) {
1099:                                shippingApplies = true;
1100:                                break;
1101:                            }
1102:                        }
1103:                    }
1104:                }
1105:                return shippingApplies;
1106:            }
1107:
1108:            public boolean taxApplies() {
1109:                boolean taxApplies = false;
1110:                List validItems = this .getValidOrderItems();
1111:                if (validItems != null) {
1112:                    Iterator i = validItems.iterator();
1113:                    while (i.hasNext()) {
1114:                        GenericValue item = (GenericValue) i.next();
1115:                        GenericValue product = null;
1116:                        try {
1117:                            product = item.getRelatedOne("Product");
1118:                        } catch (GenericEntityException e) {
1119:                            Debug
1120:                                    .logError(
1121:                                            e,
1122:                                            "Problem getting Product from OrderItem; returning 0",
1123:                                            module);
1124:                        }
1125:                        if (product != null) {
1126:                            if (ProductWorker.taxApplies(product)) {
1127:                                taxApplies = true;
1128:                                break;
1129:                            }
1130:                        }
1131:                    }
1132:                }
1133:                return taxApplies;
1134:            }
1135:
1136:            public BigDecimal getShippableTotalBd(String shipGroupSeqId) {
1137:                BigDecimal shippableTotal = ZERO;
1138:                List validItems = getValidOrderItems(shipGroupSeqId);
1139:                if (validItems != null) {
1140:                    Iterator i = validItems.iterator();
1141:                    while (i.hasNext()) {
1142:                        GenericValue item = (GenericValue) i.next();
1143:                        GenericValue product = null;
1144:                        try {
1145:                            product = item.getRelatedOne("Product");
1146:                        } catch (GenericEntityException e) {
1147:                            Debug
1148:                                    .logError(
1149:                                            e,
1150:                                            "Problem getting Product from OrderItem; returning 0",
1151:                                            module);
1152:                            return ZERO;
1153:                        }
1154:                        if (product != null) {
1155:                            if (ProductWorker.shippingApplies(product)) {
1156:                                shippableTotal = shippableTotal.add(
1157:                                        OrderReadHelper.getOrderItemSubTotalBd(
1158:                                                item, getAdjustments(), false,
1159:                                                true))
1160:                                        .setScale(scale, rounding);
1161:                            }
1162:                        }
1163:                    }
1164:                }
1165:                return shippableTotal.setScale(scale, rounding);
1166:            }
1167:
1168:            /** @deprecated Use getShippableTotalBd() instead */
1169:            public double getShippableTotal(String shipGroupSeqId) {
1170:                return getShippableTotalBd(shipGroupSeqId).doubleValue();
1171:            }
1172:
1173:            public BigDecimal getShippableQuantityBd(String shipGroupSeqId) {
1174:                BigDecimal shippableQuantity = ZERO;
1175:                List validItems = getValidOrderItems(shipGroupSeqId);
1176:                if (validItems != null) {
1177:                    Iterator i = validItems.iterator();
1178:                    while (i.hasNext()) {
1179:                        GenericValue item = (GenericValue) i.next();
1180:                        GenericValue product = null;
1181:                        try {
1182:                            product = item.getRelatedOne("Product");
1183:                        } catch (GenericEntityException e) {
1184:                            Debug
1185:                                    .logError(
1186:                                            e,
1187:                                            "Problem getting Product from OrderItem; returning 0",
1188:                                            module);
1189:                            return ZERO;
1190:                        }
1191:                        if (product != null) {
1192:                            if (ProductWorker.shippingApplies(product)) {
1193:                                shippableQuantity = shippableQuantity.add(
1194:                                        getOrderItemQuantityBd(item)).setScale(
1195:                                        scale, rounding);
1196:                            }
1197:                        }
1198:                    }
1199:                }
1200:                return shippableQuantity.setScale(scale, rounding);
1201:            }
1202:
1203:            /** @deprecated Use getShippableQuantityBd() instead */
1204:            public double getShippableQuantity(String shipGroupSeqId) {
1205:                return getShippableQuantityBd(shipGroupSeqId).doubleValue();
1206:            }
1207:
1208:            public BigDecimal getShippableWeightBd(String shipGroupSeqId) {
1209:                BigDecimal shippableWeight = ZERO;
1210:                List validItems = getValidOrderItems(shipGroupSeqId);
1211:                if (validItems != null) {
1212:                    Iterator i = validItems.iterator();
1213:                    while (i.hasNext()) {
1214:                        GenericValue item = (GenericValue) i.next();
1215:                        shippableWeight = shippableWeight.add(
1216:                                this .getItemWeightBd(item).multiply(
1217:                                        getOrderItemQuantityBd(item)))
1218:                                .setScale(scale, rounding);
1219:                    }
1220:                }
1221:
1222:                return shippableWeight.setScale(scale, rounding);
1223:            }
1224:
1225:            /** @deprecated Use getShippableWeightBd() instead */
1226:            public double getShippableWeight(String shipGroupSeqId) {
1227:                return getShippableWeightBd(shipGroupSeqId).doubleValue();
1228:            }
1229:
1230:            public BigDecimal getItemWeightBd(GenericValue item) {
1231:                GenericDelegator delegator = orderHeader.getDelegator();
1232:                BigDecimal itemWeight = ZERO;
1233:
1234:                GenericValue product = null;
1235:                try {
1236:                    product = item.getRelatedOne("Product");
1237:                } catch (GenericEntityException e) {
1238:                    Debug
1239:                            .logError(
1240:                                    e,
1241:                                    "Problem getting Product from OrderItem; returning 0",
1242:                                    module);
1243:                    return new BigDecimal("0.00");
1244:                }
1245:                if (product != null) {
1246:                    if (ProductWorker.shippingApplies(product)) {
1247:                        BigDecimal weight = product.getBigDecimal("weight");
1248:                        String isVariant = product.getString("isVariant");
1249:                        if (weight == null && "Y".equals(isVariant)) {
1250:                            // get the virtual product and check its weight
1251:                            try {
1252:                                String virtualId = ProductWorker
1253:                                        .getVariantVirtualId(product);
1254:                                if (UtilValidate.isNotEmpty(virtualId)) {
1255:                                    GenericValue virtual = delegator
1256:                                            .findByPrimaryKeyCache("Product",
1257:                                                    UtilMisc.toMap("productId",
1258:                                                            virtualId));
1259:                                    if (virtual != null) {
1260:                                        weight = virtual
1261:                                                .getBigDecimal("weight");
1262:                                    }
1263:                                }
1264:                            } catch (GenericEntityException e) {
1265:                                Debug.logError(e,
1266:                                        "Problem getting virtual product");
1267:                            }
1268:                        }
1269:
1270:                        if (weight != null) {
1271:                            itemWeight = weight;
1272:                        }
1273:                    }
1274:                }
1275:
1276:                return itemWeight;
1277:            }
1278:
1279:            /** @deprecated Use getItemWeightBd() instead */
1280:            public double getItemWeight(GenericValue item) {
1281:                return getItemWeightBd(item).doubleValue();
1282:            }
1283:
1284:            public List getShippableSizes() {
1285:                List shippableSizes = FastList.newInstance();
1286:
1287:                List validItems = getValidOrderItems();
1288:                if (validItems != null) {
1289:                    Iterator i = validItems.iterator();
1290:                    while (i.hasNext()) {
1291:                        GenericValue item = (GenericValue) i.next();
1292:                        shippableSizes.add(new Double(this .getItemSize(item)));
1293:                    }
1294:                }
1295:                return shippableSizes;
1296:            }
1297:
1298:            /**
1299:             * Get the total payment preference amount by payment type.  Specify null to get amount
1300:             * for all preference types.  TODO: filter by status as well?
1301:             */
1302:            public BigDecimal getOrderPaymentPreferenceTotalByType(
1303:                    String paymentMethodTypeId) {
1304:                BigDecimal total = ZERO;
1305:                for (Iterator iter = getPaymentPreferences().iterator(); iter
1306:                        .hasNext();) {
1307:                    GenericValue preference = (GenericValue) iter.next();
1308:                    if (preference.get("maxAmount") == null)
1309:                        continue;
1310:                    if (paymentMethodTypeId == null
1311:                            || paymentMethodTypeId.equals(preference
1312:                                    .get("paymentMethodTypeId"))) {
1313:                        total = total
1314:                                .add(preference.getBigDecimal("maxAmount"))
1315:                                .setScale(scale, rounding);
1316:                    }
1317:                }
1318:                return total;
1319:            }
1320:
1321:            public BigDecimal getCreditCardPaymentPreferenceTotal() {
1322:                return getOrderPaymentPreferenceTotalByType("CREDIT_CARD");
1323:            }
1324:
1325:            public BigDecimal getBillingAccountPaymentPreferenceTotal() {
1326:                return getOrderPaymentPreferenceTotalByType("EXT_BILLACT");
1327:            }
1328:
1329:            public BigDecimal getGiftCardPaymentPreferenceTotal() {
1330:                return getOrderPaymentPreferenceTotalByType("GIFT_CARD");
1331:            }
1332:
1333:            /**
1334:             * Get the total payment received amount by payment type.  Specify null to get amount
1335:             * over all types. This method works by going through all the PaymentAndApplications
1336:             * for all order Invoices that have status PMNT_RECEIVED.  
1337:             */
1338:            public BigDecimal getOrderPaymentReceivedTotalByType(
1339:                    String paymentMethodTypeId) {
1340:                BigDecimal total = ZERO;
1341:
1342:                try {
1343:                    // get a set of invoice IDs that belong to the order
1344:                    List orderItemBillings = orderHeader
1345:                            .getRelatedCache("OrderItemBilling");
1346:                    Set invoiceIds = new HashSet();
1347:                    for (Iterator iter = orderItemBillings.iterator(); iter
1348:                            .hasNext();) {
1349:                        GenericValue orderItemBilling = (GenericValue) iter
1350:                                .next();
1351:                        invoiceIds.add(orderItemBilling.get("invoiceId"));
1352:                    }
1353:
1354:                    // get the payments of the desired type for these invoices TODO: in models where invoices can have many orders, this needs to be refined
1355:                    List conditions = UtilMisc
1356:                            .toList(new EntityExpr("statusId",
1357:                                    EntityOperator.EQUALS, "PMNT_RECEIVED"),
1358:                                    new EntityExpr("invoiceId",
1359:                                            EntityOperator.IN, invoiceIds));
1360:                    if (paymentMethodTypeId != null) {
1361:                        conditions.add(new EntityExpr("paymentMethodTypeId",
1362:                                EntityOperator.EQUALS, paymentMethodTypeId));
1363:                    }
1364:                    EntityConditionList ecl = new EntityConditionList(
1365:                            conditions, EntityOperator.AND);
1366:                    List payments = orderHeader.getDelegator()
1367:                            .findByConditionCache("PaymentAndApplication", ecl,
1368:                                    null, null);
1369:
1370:                    for (Iterator iter = payments.iterator(); iter.hasNext();) {
1371:                        GenericValue payment = (GenericValue) iter.next();
1372:                        if (payment.get("amountApplied") == null)
1373:                            continue;
1374:                        total = total.add(
1375:                                payment.getBigDecimal("amountApplied"))
1376:                                .setScale(scale, rounding);
1377:                    }
1378:                } catch (GenericEntityException e) {
1379:                    Debug.logError(e, e.getMessage(), module);
1380:                }
1381:                return total;
1382:            }
1383:
1384:            // TODO: Might want to use BigDecimal here if precision matters
1385:            public double getItemSize(GenericValue item) {
1386:                GenericDelegator delegator = orderHeader.getDelegator();
1387:                double size = 0;
1388:
1389:                GenericValue product = null;
1390:                try {
1391:                    product = item.getRelatedOne("Product");
1392:                } catch (GenericEntityException e) {
1393:                    Debug.logError(e, "Problem getting Product from OrderItem",
1394:                            module);
1395:                    return 0;
1396:                }
1397:                if (product != null) {
1398:                    if (ProductWorker.shippingApplies(product)) {
1399:                        Double height = product.getDouble("shippingHeight");
1400:                        Double width = product.getDouble("shippingWidth");
1401:                        Double depth = product.getDouble("shippingDepth");
1402:                        String isVariant = product.getString("isVariant");
1403:                        if ((height == null || width == null || depth == null)
1404:                                && "Y".equals(isVariant)) {
1405:                            // get the virtual product and check its values
1406:                            try {
1407:                                String virtualId = ProductWorker
1408:                                        .getVariantVirtualId(product);
1409:                                if (UtilValidate.isNotEmpty(virtualId)) {
1410:                                    GenericValue virtual = delegator
1411:                                            .findByPrimaryKeyCache("Product",
1412:                                                    UtilMisc.toMap("productId",
1413:                                                            virtualId));
1414:                                    if (virtual != null) {
1415:                                        if (height == null)
1416:                                            height = virtual
1417:                                                    .getDouble("shippingHeight");
1418:                                        if (width == null)
1419:                                            width = virtual
1420:                                                    .getDouble("shippingWidth");
1421:                                        if (depth == null)
1422:                                            depth = virtual
1423:                                                    .getDouble("shippingDepth");
1424:                                    }
1425:                                }
1426:                            } catch (GenericEntityException e) {
1427:                                Debug.logError(e,
1428:                                        "Problem getting virtual product");
1429:                            }
1430:                        }
1431:
1432:                        if (height == null)
1433:                            height = new Double(0);
1434:                        if (width == null)
1435:                            width = new Double(0);
1436:                        if (depth == null)
1437:                            depth = new Double(0);
1438:
1439:                        // determine girth (longest field is length)
1440:                        double[] sizeInfo = { height.doubleValue(),
1441:                                width.doubleValue(), depth.doubleValue() };
1442:                        Arrays.sort(sizeInfo);
1443:
1444:                        size = (sizeInfo[0] * 2) + (sizeInfo[1] * 2)
1445:                                + sizeInfo[2];
1446:                    }
1447:                }
1448:
1449:                return size;
1450:            }
1451:
1452:            public long getItemPiecesIncluded(GenericValue item) {
1453:                GenericDelegator delegator = orderHeader.getDelegator();
1454:                long piecesIncluded = 1;
1455:
1456:                GenericValue product = null;
1457:                try {
1458:                    product = item.getRelatedOne("Product");
1459:                } catch (GenericEntityException e) {
1460:                    Debug
1461:                            .logError(
1462:                                    e,
1463:                                    "Problem getting Product from OrderItem; returning 1",
1464:                                    module);
1465:                    return 1;
1466:                }
1467:                if (product != null) {
1468:                    if (ProductWorker.shippingApplies(product)) {
1469:                        Long pieces = product.getLong("piecesIncluded");
1470:                        String isVariant = product.getString("isVariant");
1471:                        if (pieces == null && isVariant != null
1472:                                && "Y".equals(isVariant)) {
1473:                            // get the virtual product and check its weight
1474:                            GenericValue virtual = null;
1475:                            try {
1476:                                List virtuals = delegator.findByAnd(
1477:                                        "ProductAssoc", UtilMisc.toMap(
1478:                                                "productIdTo",
1479:                                                product.getString("productId"),
1480:                                                "productAssocTypeId",
1481:                                                "PRODUCT_VARIANT"), UtilMisc
1482:                                                .toList("-fromDate"));
1483:                                if (virtuals != null) {
1484:                                    virtuals = EntityUtil
1485:                                            .filterByDate(virtuals);
1486:                                }
1487:                                virtual = EntityUtil.getFirst(virtuals);
1488:                            } catch (GenericEntityException e) {
1489:                                Debug.logError(e,
1490:                                        "Problem getting virtual product");
1491:                            }
1492:                            if (virtual != null) {
1493:                                try {
1494:                                    GenericValue virtualProduct = virtual
1495:                                            .getRelatedOne("MainProduct");
1496:                                    pieces = virtualProduct
1497:                                            .getLong("piecesIncluded");
1498:                                } catch (GenericEntityException e) {
1499:                                    Debug.logError(e,
1500:                                            "Problem getting virtual product");
1501:                                }
1502:                            }
1503:                        }
1504:
1505:                        if (pieces != null) {
1506:                            piecesIncluded = pieces.longValue();
1507:                        }
1508:                    }
1509:                }
1510:
1511:                return piecesIncluded;
1512:            }
1513:
1514:            public List getShippableItemInfo(String shipGroupSeqId) {
1515:                List shippableInfo = FastList.newInstance();
1516:
1517:                List validItems = getValidOrderItems(shipGroupSeqId);
1518:                if (validItems != null) {
1519:                    Iterator i = validItems.iterator();
1520:                    while (i.hasNext()) {
1521:                        GenericValue item = (GenericValue) i.next();
1522:                        shippableInfo.add(this .getItemInfoMap(item));
1523:                    }
1524:                }
1525:
1526:                return shippableInfo;
1527:            }
1528:
1529:            public Map getItemInfoMap(GenericValue item) {
1530:                Map itemInfo = FastMap.newInstance();
1531:                itemInfo.put("productId", item.getString("productId"));
1532:                itemInfo.put("quantity", getOrderItemQuantity(item));
1533:                itemInfo.put("weight", new Double(this .getItemWeight(item)));
1534:                itemInfo.put("size", new Double(this .getItemSize(item)));
1535:                itemInfo.put("piecesIncluded", new Long(this 
1536:                        .getItemPiecesIncluded(item)));
1537:                itemInfo.put("featureSet", this .getItemFeatureSet(item));
1538:                return itemInfo;
1539:            }
1540:
1541:            public String getOrderEmailString() {
1542:                GenericDelegator delegator = orderHeader.getDelegator();
1543:                // get the email addresses from the order contact mech(s)
1544:                List orderContactMechs = null;
1545:                try {
1546:                    Map ocFields = UtilMisc.toMap("orderId", orderHeader
1547:                            .get("orderId"), "contactMechPurposeTypeId",
1548:                            "ORDER_EMAIL");
1549:                    orderContactMechs = delegator.findByAnd("OrderContactMech",
1550:                            ocFields);
1551:                } catch (GenericEntityException e) {
1552:                    Debug.logWarning(e, "Problems getting order contact mechs",
1553:                            module);
1554:                }
1555:
1556:                StringBuffer emails = new StringBuffer();
1557:                if (orderContactMechs != null) {
1558:                    Iterator oci = orderContactMechs.iterator();
1559:                    while (oci.hasNext()) {
1560:                        try {
1561:                            GenericValue orderContactMech = (GenericValue) oci
1562:                                    .next();
1563:                            GenericValue contactMech = orderContactMech
1564:                                    .getRelatedOne("ContactMech");
1565:                            emails
1566:                                    .append(emails.length() > 0 ? "," : "")
1567:                                    .append(contactMech.getString("infoString"));
1568:                        } catch (GenericEntityException e) {
1569:                            Debug
1570:                                    .logWarning(
1571:                                            e,
1572:                                            "Problems getting contact mech from order contact mech",
1573:                                            module);
1574:                        }
1575:                    }
1576:                }
1577:                return emails.toString();
1578:            }
1579:
1580:            public BigDecimal getOrderGrandTotalBd() {
1581:                if (totalPrice == null) {
1582:                    totalPrice = getOrderGrandTotalBd(getValidOrderItems(),
1583:                            getAdjustments());
1584:                }// else already set
1585:                return totalPrice;
1586:            }
1587:
1588:            /** @deprecated Use getOrderGrandTotalBd() instead */
1589:            public double getOrderGrandTotal() {
1590:                return getOrderGrandTotalBd().doubleValue();
1591:            }
1592:
1593:            /**
1594:             * Gets the amount open on the order that is not covered by the relevant OrderPaymentPreferences.
1595:             * This works by adding up the amount allocated to each unprocessed OrderPaymentPreference and the
1596:             * amounts received and refunded as payments for the settled ones.
1597:             */
1598:            public double getOrderOpenAmount() throws GenericEntityException {
1599:                GenericDelegator delegator = orderHeader.getDelegator();
1600:                double total = getOrderGrandTotal();
1601:                double openAmount = 0;
1602:                List prefs = getPaymentPreferences();
1603:
1604:                // add up the covered amount, but skip preferences which are declined or cancelled
1605:                for (Iterator iter = prefs.iterator(); iter.hasNext();) {
1606:                    GenericValue pref = (GenericValue) iter.next();
1607:                    if ("PAYMENT_CANCELLED".equals(pref.get("statusId"))
1608:                            || "PAYMENT_DECLINED".equals(pref.get("statusId"))) {
1609:                        continue;
1610:                    } else if ("PAYMENT_SETTLED".equals(pref.get("statusId"))) {
1611:                        List responses = pref.getRelatedByAnd(
1612:                                "PaymentGatewayResponse", UtilMisc.toMap(
1613:                                        "transCodeEnumId", "PGT_CAPTURE"));
1614:                        for (Iterator respIter = responses.iterator(); respIter
1615:                                .hasNext();) {
1616:                            GenericValue response = (GenericValue) respIter
1617:                                    .next();
1618:                            Double amount = response.getDouble("amount");
1619:                            if (amount != null) {
1620:                                openAmount += amount.doubleValue();
1621:                            }
1622:                        }
1623:                        responses = pref.getRelatedByAnd(
1624:                                "PaymentGatewayResponse", UtilMisc.toMap(
1625:                                        "transCodeEnumId", "PGT_REFUND"));
1626:                        for (Iterator respIter = responses.iterator(); respIter
1627:                                .hasNext();) {
1628:                            GenericValue response = (GenericValue) respIter
1629:                                    .next();
1630:                            Double amount = response.getDouble("amount");
1631:                            if (amount != null) {
1632:                                openAmount -= amount.doubleValue();
1633:                            }
1634:                        }
1635:                    } else {
1636:                        // all others are currently "unprocessed" payment preferences
1637:                        Double maxAmount = pref.getDouble("maxAmount");
1638:                        if (maxAmount != null) {
1639:                            openAmount += maxAmount.doubleValue();
1640:                        }
1641:                    }
1642:                }
1643:
1644:                // return either a positive amount or positive zero
1645:                return Math.max(total - openAmount, 0);
1646:            }
1647:
1648:            public List getOrderHeaderAdjustments() {
1649:                return getOrderHeaderAdjustments(getAdjustments(), null);
1650:            }
1651:
1652:            public List getOrderHeaderAdjustments(String shipGroupSeqId) {
1653:                return getOrderHeaderAdjustments(getAdjustments(),
1654:                        shipGroupSeqId);
1655:            }
1656:
1657:            public List getOrderHeaderAdjustmentsToShow() {
1658:                return filterOrderAdjustments(getOrderHeaderAdjustments(),
1659:                        true, false, false, false, false);
1660:            }
1661:
1662:            public List getOrderHeaderStatuses() {
1663:                return getOrderHeaderStatuses(getOrderStatuses());
1664:            }
1665:
1666:            public BigDecimal getOrderAdjustmentsTotalBd() {
1667:                return getOrderAdjustmentsTotalBd(getValidOrderItems(),
1668:                        getAdjustments());
1669:            }
1670:
1671:            /** @deprecated Use getOrderAdjustmentsTotalBd() instead */
1672:            public double getOrderAdjustmentsTotal() {
1673:                return getOrderAdjustmentsTotalBd().doubleValue();
1674:            }
1675:
1676:            public BigDecimal getOrderAdjustmentTotalBd(GenericValue adjustment) {
1677:                return calcOrderAdjustmentBd(adjustment,
1678:                        getOrderItemsSubTotalBd());
1679:            }
1680:
1681:            /** @deprecated Use getOrderAdjustmentsTotalBd() instead */
1682:            public double getOrderAdjustmentTotal(GenericValue adjustment) {
1683:                return getOrderAdjustmentTotalBd(adjustment).doubleValue();
1684:            }
1685:
1686:            public int hasSurvey() {
1687:                GenericDelegator delegator = orderHeader.getDelegator();
1688:                List surveys = null;
1689:                try {
1690:                    surveys = delegator
1691:                            .findByAnd("SurveyResponse", UtilMisc
1692:                                    .toMap("orderId", orderHeader
1693:                                            .getString("orderId")));
1694:                } catch (GenericEntityException e) {
1695:                    Debug.logError(e, module);
1696:                }
1697:                int size = 0;
1698:                if (surveys != null) {
1699:                    size = surveys.size();
1700:                }
1701:
1702:                return size;
1703:            }
1704:
1705:            // ========================================
1706:            // ========== Order Item Methods ==========
1707:            // ========================================
1708:
1709:            public List getOrderItems() {
1710:                if (orderItems == null) {
1711:                    try {
1712:                        orderItems = orderHeader.getRelated("OrderItem",
1713:                                UtilMisc.toList("orderItemSeqId"));
1714:                    } catch (GenericEntityException e) {
1715:                        Debug.logWarning(e, module);
1716:                    }
1717:                }
1718:                return orderItems;
1719:            }
1720:
1721:            public List getOrderItemAndShipGroupAssoc() {
1722:                if (orderItemAndShipGrp == null) {
1723:                    try {
1724:                        orderItemAndShipGrp = orderHeader.getDelegator()
1725:                                .findByAnd(
1726:                                        "OrderItemAndShipGroupAssoc",
1727:                                        UtilMisc.toMap("orderId", orderHeader
1728:                                                .getString("orderId")));
1729:                    } catch (GenericEntityException e) {
1730:                        Debug.logWarning(e, module);
1731:                    }
1732:                }
1733:                return orderItemAndShipGrp;
1734:            }
1735:
1736:            public List getOrderItemAndShipGroupAssoc(String shipGroupSeqId) {
1737:                List exprs = UtilMisc.toList(new EntityExpr("shipGroupSeqId",
1738:                        EntityOperator.EQUALS, shipGroupSeqId));
1739:                return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(),
1740:                        exprs);
1741:            }
1742:
1743:            public List getValidOrderItems() {
1744:                List exprs = UtilMisc.toList(new EntityExpr("statusId",
1745:                        EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
1746:                        new EntityExpr("statusId", EntityOperator.NOT_EQUAL,
1747:                                "ITEM_REJECTED"));
1748:                return EntityUtil.filterByAnd(getOrderItems(), exprs);
1749:            }
1750:
1751:            public boolean getPastEtaOrderItems(String orderId) {
1752:                /*List exprs = UtilMisc.toList(new EntityExpr("statusId", EntityOperator.EQUALS, "ITEM_APPROVED"));
1753:                List itemsApproved = EntityUtil.filterByAnd(getOrderItems(), exprs);
1754:                Iterator i = itemsApproved.iterator();
1755:                while (i.hasNext()) {
1756:                    GenericValue item = (GenericValue) i.next();
1757:                    Timestamp estimatedDeliveryDate = (Timestamp) item.get("estimatedDeliveryDate");
1758:                    if (estimatedDeliveryDate != null && UtilDateTime.nowTimestamp().after(estimatedDeliveryDate)) {
1759:                    return true;
1760:                    }            
1761:                }
1762:                return false;
1763:                }*/
1764:                GenericDelegator delegator = orderHeader.getDelegator();
1765:                GenericValue orderDeliverySchedule = null;
1766:                try {
1767:                    orderDeliverySchedule = delegator.findByPrimaryKey(
1768:                            "OrderDeliverySchedule", UtilMisc.toMap("orderId",
1769:                                    orderId, "orderItemSeqId", "_NA_"));
1770:                } catch (GenericEntityException e) {
1771:                }
1772:                Timestamp estimatedShipDate = null;
1773:                if (orderDeliverySchedule != null
1774:                        && orderDeliverySchedule.get("estimatedReadyDate") != null) {
1775:                    estimatedShipDate = orderDeliverySchedule
1776:                            .getTimestamp("estimatedReadyDate");
1777:                }
1778:                if (estimatedShipDate != null
1779:                        && UtilDateTime.nowTimestamp().after(estimatedShipDate)) {
1780:                    return true;
1781:                }
1782:                return false;
1783:            }
1784:
1785:            public boolean getRejectedOrderItems() {
1786:                List items = getOrderItems();
1787:                Iterator i = items.iterator();
1788:                while (i.hasNext()) {
1789:                    GenericValue item = (GenericValue) i.next();
1790:                    List receipts = null;
1791:                    try {
1792:                        receipts = item.getRelated("ShipmentReceipt");
1793:                    } catch (GenericEntityException e) {
1794:                        Debug.logWarning(e, module);
1795:                    }
1796:                    if (receipts != null && receipts.size() > 0) {
1797:                        Iterator recIter = receipts.iterator();
1798:                        while (recIter.hasNext()) {
1799:                            GenericValue rec = (GenericValue) recIter.next();
1800:                            Double rejected = rec.getDouble("quantityRejected");
1801:                            if (rejected != null && rejected.doubleValue() > 0) {
1802:                                return true;
1803:                            }
1804:                        }
1805:                    }
1806:                }
1807:                return false;
1808:            }
1809:
1810:            public boolean getPartiallyReceivedItems() {
1811:                /*List exprs = UtilMisc.toList(new EntityExpr("statusId", EntityOperator.EQUALS, "ITEM_APPROVED"));
1812:                List itemsApproved = EntityUtil.filterByAnd(getOrderItems(), exprs);
1813:                Iterator i = itemsApproved.iterator();
1814:                while (i.hasNext()) {
1815:                    GenericValue item = (GenericValue) i.next();            
1816:                    int shippedQuantity = (int) getItemShippedQuantity(item);            
1817:                    Double orderedQuantity = (Double) item.get("quantity");            
1818:                    if (shippedQuantity != orderedQuantity.intValue() && shippedQuantity > 0) {
1819:                    return true;
1820:                    }            
1821:                }
1822:                return false;
1823:                }*/
1824:                List items = getOrderItems();
1825:                Iterator i = items.iterator();
1826:                while (i.hasNext()) {
1827:                    GenericValue item = (GenericValue) i.next();
1828:                    List receipts = null;
1829:                    try {
1830:                        receipts = item.getRelated("ShipmentReceipt");
1831:                    } catch (GenericEntityException e) {
1832:                        Debug.logWarning(e, module);
1833:                    }
1834:                    if (receipts != null && receipts.size() > 0) {
1835:                        Iterator recIter = receipts.iterator();
1836:                        while (recIter.hasNext()) {
1837:                            GenericValue rec = (GenericValue) recIter.next();
1838:                            Double acceptedQuantity = rec
1839:                                    .getDouble("quantityAccepted");
1840:                            Double orderedQuantity = (Double) item
1841:                                    .get("quantity");
1842:                            if (acceptedQuantity.intValue() != orderedQuantity
1843:                                    .intValue()
1844:                                    && acceptedQuantity.intValue() > 0) {
1845:                                return true;
1846:                            }
1847:                        }
1848:                    }
1849:                }
1850:                return false;
1851:            }
1852:
1853:            public List getValidOrderItems(String shipGroupSeqId) {
1854:                if (shipGroupSeqId == null)
1855:                    return getValidOrderItems();
1856:                List exprs = UtilMisc.toList(new EntityExpr("statusId",
1857:                        EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
1858:                        new EntityExpr("statusId", EntityOperator.NOT_EQUAL,
1859:                                "ITEM_REJECTED"), new EntityExpr(
1860:                                "shipGroupSeqId", EntityOperator.EQUALS,
1861:                                shipGroupSeqId));
1862:                return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(),
1863:                        exprs);
1864:            }
1865:
1866:            public GenericValue getOrderItem(String orderItemSeqId) {
1867:                List exprs = UtilMisc.toList(new EntityExpr("orderItemSeqId",
1868:                        EntityOperator.EQUALS, orderItemSeqId));
1869:                return EntityUtil.getFirst(EntityUtil.filterByAnd(
1870:                        getOrderItems(), exprs));
1871:            }
1872:
1873:            public List getValidDigitalItems() {
1874:                List digitalItems = new ArrayList();
1875:                // only approved or complete items apply
1876:                List exprs = UtilMisc.toList(new EntityExpr("statusId",
1877:                        EntityOperator.EQUALS, "ITEM_APPROVED"),
1878:                        new EntityExpr("statusId", EntityOperator.EQUALS,
1879:                                "ITEM_COMPLETED"));
1880:                List items = EntityUtil.filterByOr(getOrderItems(), exprs);
1881:                Iterator i = items.iterator();
1882:                while (i.hasNext()) {
1883:                    GenericValue item = (GenericValue) i.next();
1884:                    if (item.get("productId") != null) {
1885:                        GenericValue product = null;
1886:                        try {
1887:                            product = item.getRelatedOne("Product");
1888:                        } catch (GenericEntityException e) {
1889:                            Debug.logError(e,
1890:                                    "Unable to get Product from OrderItem",
1891:                                    module);
1892:                        }
1893:                        if (product != null) {
1894:                            GenericValue productType = null;
1895:                            try {
1896:                                productType = product
1897:                                        .getRelatedOne("ProductType");
1898:                            } catch (GenericEntityException e) {
1899:                                Debug
1900:                                        .logError(
1901:                                                e,
1902:                                                "ERROR: Unable to get ProductType from Product",
1903:                                                module);
1904:                            }
1905:
1906:                            if (productType != null) {
1907:                                String isDigital = productType
1908:                                        .getString("isDigital");
1909:
1910:                                if (isDigital != null
1911:                                        && "Y".equalsIgnoreCase(isDigital)) {
1912:                                    // make sure we have an OrderItemBilling record
1913:                                    List orderItemBillings = null;
1914:                                    try {
1915:                                        orderItemBillings = item
1916:                                                .getRelated("OrderItemBilling");
1917:                                    } catch (GenericEntityException e) {
1918:                                        Debug
1919:                                                .logError(e,
1920:                                                        "Unable to get OrderItemBilling from OrderItem");
1921:                                    }
1922:
1923:                                    if (orderItemBillings != null
1924:                                            && orderItemBillings.size() > 0) {
1925:                                        // get the ProductContent records
1926:                                        List productContents = null;
1927:                                        try {
1928:                                            productContents = product
1929:                                                    .getRelated("ProductContent");
1930:                                        } catch (GenericEntityException e) {
1931:                                            Debug
1932:                                                    .logError(
1933:                                                            "Unable to get ProductContent from Product",
1934:                                                            module);
1935:                                        }
1936:                                        List cExprs = UtilMisc
1937:                                                .toList(
1938:                                                        new EntityExpr(
1939:                                                                "productContentTypeId",
1940:                                                                EntityOperator.EQUALS,
1941:                                                                "DIGITAL_DOWNLOAD"),
1942:                                                        new EntityExpr(
1943:                                                                "productContentTypeId",
1944:                                                                EntityOperator.EQUALS,
1945:                                                                "FULFILLMENT_EMAIL"),
1946:                                                        new EntityExpr(
1947:                                                                "productContentTypeId",
1948:                                                                EntityOperator.EQUALS,
1949:                                                                "FULFILLMENT_EXTERNAL"));
1950:                                        // add more as needed
1951:                                        productContents = EntityUtil
1952:                                                .filterByDate(productContents);
1953:                                        productContents = EntityUtil
1954:                                                .filterByOr(productContents,
1955:                                                        cExprs);
1956:
1957:                                        if (productContents != null
1958:                                                && productContents.size() > 0) {
1959:                                            // make sure we are still within the allowed timeframe and use limits
1960:                                            Iterator pci = productContents
1961:                                                    .iterator();
1962:                                            while (pci.hasNext()) {
1963:                                                GenericValue productContent = (GenericValue) pci
1964:                                                        .next();
1965:                                                Timestamp fromDate = productContent
1966:                                                        .getTimestamp("purchaseFromDate");
1967:                                                Timestamp thruDate = productContent
1968:                                                        .getTimestamp("purchaseThruDate");
1969:                                                if (fromDate == null
1970:                                                        || item
1971:                                                                .getTimestamp(
1972:                                                                        "orderDate")
1973:                                                                .after(fromDate)) {
1974:                                                    if (thruDate == null
1975:                                                            || item
1976:                                                                    .getTimestamp(
1977:                                                                            "orderDate")
1978:                                                                    .before(
1979:                                                                            thruDate)) {
1980:                                                        // TODO: Implement use count and days
1981:                                                        digitalItems.add(item);
1982:                                                    }
1983:                                                }
1984:                                            }
1985:                                        }
1986:                                    }
1987:                                }
1988:                            }
1989:                        }
1990:                    }
1991:                }
1992:                return digitalItems;
1993:            }
1994:
1995:            public List getOrderItemAdjustments(GenericValue orderItem) {
1996:                return getOrderItemAdjustmentList(orderItem, getAdjustments());
1997:            }
1998:
1999:            public String getCurrentOrderItemWorkEffort(GenericValue orderItem) {
2000:                GenericValue workOrderItemFulFillment;
2001:                try {
2002:                    workOrderItemFulFillment = orderItem
2003:                            .getRelatedOne("WorkOrderItemFulFillment");
2004:                } catch (GenericEntityException e) {
2005:                    return null;
2006:                }
2007:                GenericValue workEffort = null;
2008:                try {
2009:                    workEffort = workOrderItemFulFillment
2010:                            .getRelatedOne("WorkEffort");
2011:                } catch (GenericEntityException e) {
2012:                    return null;
2013:                }
2014:                return workEffort.getString("workEffortId");
2015:            }
2016:
2017:            public String getCurrentItemStatus(GenericValue orderItem) {
2018:                GenericValue statusItem = null;
2019:                try {
2020:                    statusItem = orderItem.getRelatedOne("StatusItem");
2021:                } catch (GenericEntityException e) {
2022:                    Debug.logError(e, "Trouble getting StatusItem : "
2023:                            + orderItem, module);
2024:                }
2025:                if (statusItem == null || statusItem.get("description") == null) {
2026:                    return "Not Available";
2027:                } else {
2028:                    return statusItem.getString("description");
2029:                }
2030:            }
2031:
2032:            public List getOrderItemPriceInfos(GenericValue orderItem) {
2033:                if (orderItem == null)
2034:                    return null;
2035:                if (this .orderItemPriceInfos == null) {
2036:                    GenericDelegator delegator = orderHeader.getDelegator();
2037:
2038:                    try {
2039:                        orderItemPriceInfos = delegator.findByAnd(
2040:                                "OrderItemPriceInfo", UtilMisc.toMap("orderId",
2041:                                        orderHeader.get("orderId")));
2042:                    } catch (GenericEntityException e) {
2043:                        Debug.logWarning(e, module);
2044:                    }
2045:                }
2046:                String orderItemSeqId = (String) orderItem
2047:                        .get("orderItemSeqId");
2048:
2049:                return EntityUtil.filterByAnd(this .orderItemPriceInfos,
2050:                        UtilMisc.toMap("orderItemSeqId", orderItemSeqId));
2051:            }
2052:
2053:            public List getOrderItemShipGroupAssocs(GenericValue orderItem) {
2054:                if (orderItem == null)
2055:                    return null;
2056:                try {
2057:                    return orderHeader.getDelegator().findByAnd(
2058:                            "OrderItemShipGroupAssoc",
2059:                            UtilMisc.toMap("orderId", orderItem
2060:                                    .getString("orderId"), "orderItemSeqId",
2061:                                    orderItem.getString("orderItemSeqId")),
2062:                            UtilMisc.toList("shipGroupSeqId"));
2063:                } catch (GenericEntityException e) {
2064:                    Debug.logWarning(e, module);
2065:                }
2066:                return null;
2067:            }
2068:
2069:            public List getOrderItemShipGrpInvResList(GenericValue orderItem) {
2070:                if (orderItem == null)
2071:                    return null;
2072:                if (this .orderItemShipGrpInvResList == null) {
2073:                    GenericDelegator delegator = orderItem.getDelegator();
2074:                    try {
2075:                        orderItemShipGrpInvResList = delegator.findByAnd(
2076:                                "OrderItemShipGrpInvRes", UtilMisc.toMap(
2077:                                        "orderId", orderItem.get("orderId")));
2078:                    } catch (GenericEntityException e) {
2079:                        Debug.logWarning(e,
2080:                                "Trouble getting OrderItemShipGrpInvRes List",
2081:                                module);
2082:                    }
2083:                }
2084:                return EntityUtil.filterByAnd(orderItemShipGrpInvResList,
2085:                        UtilMisc.toMap("orderItemSeqId", orderItem
2086:                                .getString("orderItemSeqId")));
2087:            }
2088:
2089:            public List getOrderItemIssuances(GenericValue orderItem) {
2090:                return this .getOrderItemIssuances(orderItem, null);
2091:            }
2092:
2093:            public List getOrderItemIssuances(GenericValue orderItem,
2094:                    String shipmentId) {
2095:                if (orderItem == null)
2096:                    return null;
2097:                if (this .orderItemIssuances == null) {
2098:                    GenericDelegator delegator = orderItem.getDelegator();
2099:
2100:                    try {
2101:                        orderItemIssuances = delegator.findByAnd(
2102:                                "ItemIssuance", UtilMisc.toMap("orderId",
2103:                                        orderItem.get("orderId")));
2104:                    } catch (GenericEntityException e) {
2105:                        Debug.logWarning(e, "Trouble getting ItemIssuance(s)",
2106:                                module);
2107:                    }
2108:                }
2109:
2110:                // filter the issuances
2111:                Map filter = UtilMisc.toMap("orderItemSeqId", orderItem
2112:                        .get("orderItemSeqId"));
2113:                if (shipmentId != null) {
2114:                    filter.put("shipmentId", shipmentId);
2115:                }
2116:                return EntityUtil.filterByAnd(orderItemIssuances, filter);
2117:            }
2118:
2119:            /** Get a set of productIds in the order. */
2120:            public Collection getOrderProductIds() {
2121:                Set productIds = new HashSet();
2122:                for (Iterator iter = getOrderItems().iterator(); iter.hasNext();) {
2123:                    productIds.add(((GenericValue) iter.next())
2124:                            .getString("productId"));
2125:                }
2126:                return productIds;
2127:            }
2128:
2129:            public List getOrderReturnItems() {
2130:                GenericDelegator delegator = orderHeader.getDelegator();
2131:                if (this .orderReturnItems == null) {
2132:                    try {
2133:                        this .orderReturnItems = delegator.findByAnd(
2134:                                "ReturnItem", UtilMisc.toMap("orderId",
2135:                                        orderHeader.getString("orderId")));
2136:                    } catch (GenericEntityException e) {
2137:                        Debug
2138:                                .logError(
2139:                                        e,
2140:                                        "Problem getting ReturnItem from order",
2141:                                        module);
2142:                        return null;
2143:                    }
2144:                }
2145:                return this .orderReturnItems;
2146:            }
2147:
2148:            /**
2149:             * Get the quantity returned per order item.
2150:             * In other words, this method will count the ReturnItems
2151:             * related to each OrderItem.
2152:             *
2153:             * @return  Map of returned quantities as Doubles keyed to the orderItemSeqId
2154:             */
2155:            public Map getOrderItemReturnedQuantities() {
2156:                List returnItems = getOrderReturnItems();
2157:
2158:                // since we don't have a handy grouped view entity, we'll have to group the return items by hand
2159:                Map returnMap = FastMap.newInstance();
2160:                for (Iterator iter = this .getValidOrderItems().iterator(); iter
2161:                        .hasNext();) {
2162:                    GenericValue orderItem = (GenericValue) iter.next();
2163:                    List group = EntityUtil.filterByAnd(returnItems, UtilMisc
2164:                            .toMap("orderId", orderItem.get("orderId"),
2165:                                    "orderItemSeqId", orderItem
2166:                                            .get("orderItemSeqId")));
2167:
2168:                    // add up the returned quantities for this group TODO: received quantity should be used eventually
2169:                    double returned = 0;
2170:                    for (Iterator groupiter = group.iterator(); groupiter
2171:                            .hasNext();) {
2172:                        GenericValue returnItem = (GenericValue) groupiter
2173:                                .next();
2174:                        if (returnItem.getDouble("returnQuantity") != null) {
2175:                            returned += (returnItem.getDouble("returnQuantity"))
2176:                                    .doubleValue();
2177:                        }
2178:                    }
2179:
2180:                    // the quantity returned per order item
2181:                    returnMap.put(orderItem.get("orderItemSeqId"), new Double(
2182:                            returned));
2183:                }
2184:                return returnMap;
2185:            }
2186:
2187:            /**
2188:             * Get the total quantity of returned items for an order. This will count
2189:             * only the ReturnItems that are directly correlated to an OrderItem.
2190:             */
2191:            public BigDecimal getOrderReturnedQuantityBd() {
2192:                List returnedItemsBase = getOrderReturnItems();
2193:                List returnedItems = new ArrayList(returnedItemsBase.size());
2194:
2195:                // filter just order items
2196:                List orderItemExprs = UtilMisc.toList(new EntityExpr(
2197:                        "returnItemTypeId", EntityOperator.EQUALS,
2198:                        "RET_PROD_ITEM"));
2199:                orderItemExprs.add(new EntityExpr("returnItemTypeId",
2200:                        EntityOperator.EQUALS, "RET_FPROD_ITEM"));
2201:                orderItemExprs.add(new EntityExpr("returnItemTypeId",
2202:                        EntityOperator.EQUALS, "RET_DPROD_ITEM"));
2203:                orderItemExprs.add(new EntityExpr("returnItemTypeId",
2204:                        EntityOperator.EQUALS, "RET_FDPROD_ITEM"));
2205:                orderItemExprs.add(new EntityExpr("returnItemTypeId",
2206:                        EntityOperator.EQUALS, "RET_PROD_FEATR_ITEM"));
2207:                orderItemExprs.add(new EntityExpr("returnItemTypeId",
2208:                        EntityOperator.EQUALS, "RET_SPROD_ITEM"));
2209:                orderItemExprs.add(new EntityExpr("returnItemTypeId",
2210:                        EntityOperator.EQUALS, "RET_WE_ITEM"));
2211:                orderItemExprs.add(new EntityExpr("returnItemTypeId",
2212:                        EntityOperator.EQUALS, "RET_TE_ITEM"));
2213:                returnedItemsBase = EntityUtil.filterByOr(returnedItemsBase,
2214:                        orderItemExprs);
2215:
2216:                // get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
2217:                returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
2218:                        UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
2219:                returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
2220:                        UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
2221:
2222:                BigDecimal returnedQuantity = ZERO;
2223:                if (returnedItems != null) {
2224:                    Iterator i = returnedItems.iterator();
2225:                    while (i.hasNext()) {
2226:                        GenericValue returnedItem = (GenericValue) i.next();
2227:                        if (returnedItem.get("returnQuantity") != null) {
2228:                            returnedQuantity = returnedQuantity.add(
2229:                                    returnedItem
2230:                                            .getBigDecimal("returnQuantity"))
2231:                                    .setScale(scale, rounding);
2232:                        }
2233:                    }
2234:                }
2235:                return returnedQuantity.setScale(scale, rounding);
2236:            }
2237:
2238:            /** @deprecated */
2239:            public double getOrderReturnedQuantity() {
2240:                return getOrderReturnedQuantityBd().doubleValue();
2241:            }
2242:
2243:            /** @deprecated */
2244:            public double getOrderReturnedTotal() {
2245:                return getOrderReturnedTotalBd().doubleValue();
2246:            }
2247:
2248:            /** @deprecated */
2249:            public double getOrderReturnedTotal(boolean includeAll) {
2250:                return getOrderReturnedTotalBd(includeAll).doubleValue();
2251:            }
2252:
2253:            /** 
2254:             * Get the returned total by return type (credit, refund, etc.).  Specify returnTypeId = null to get sum over all
2255:             * return types.  Specify includeAll = true to sum up over all return statuses except cancelled.  Specify includeAll
2256:             * = false to sum up over ACCEPTED,RECEIVED And COMPLETED returns.
2257:             */
2258:            public BigDecimal getOrderReturnedTotalByTypeBd(
2259:                    String returnTypeId, boolean includeAll) {
2260:                List returnedItemsBase = getOrderReturnItems();
2261:                if (returnTypeId != null) {
2262:                    returnedItemsBase = EntityUtil.filterByAnd(
2263:                            returnedItemsBase, UtilMisc.toMap("returnTypeId",
2264:                                    returnTypeId));
2265:                }
2266:                List returnedItems = new ArrayList(returnedItemsBase.size());
2267:
2268:                // get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
2269:                if (!includeAll) {
2270:                    returnedItems.addAll(EntityUtil.filterByAnd(
2271:                            returnedItemsBase, UtilMisc.toMap("statusId",
2272:                                    "RETURN_ACCEPTED")));
2273:                    returnedItems.addAll(EntityUtil.filterByAnd(
2274:                            returnedItemsBase, UtilMisc.toMap("statusId",
2275:                                    "RETURN_RECEIVED")));
2276:                    returnedItems.addAll(EntityUtil.filterByAnd(
2277:                            returnedItemsBase, UtilMisc.toMap("statusId",
2278:                                    "RETURN_COMPLETED")));
2279:                } else {
2280:                    // otherwise get all of them except cancelled ones
2281:                    returnedItems.addAll(EntityUtil.filterByAnd(
2282:                            returnedItemsBase, UtilMisc.toList(new EntityExpr(
2283:                                    "statusId", EntityOperator.NOT_EQUAL,
2284:                                    "RETURN_CANCELLED"))));
2285:                }
2286:                BigDecimal returnedAmount = ZERO;
2287:                Iterator i = returnedItems.iterator();
2288:                String orderId = orderHeader.getString("orderId");
2289:                List returnHeaderList = new ArrayList();
2290:                while (i.hasNext()) {
2291:                    GenericValue returnedItem = (GenericValue) i.next();
2292:                    if ((returnedItem.get("returnPrice") != null)
2293:                            && (returnedItem.get("returnQuantity") != null)) {
2294:                        returnedAmount = returnedAmount
2295:                                .add(
2296:                                        returnedItem
2297:                                                .getBigDecimal("returnPrice")
2298:                                                .multiply(
2299:                                                        returnedItem
2300:                                                                .getBigDecimal("returnQuantity")))
2301:                                .setScale(scale, rounding);
2302:                    }
2303:                    Map itemAdjustmentCondition = UtilMisc.toMap("returnId",
2304:                            returnedItem.get("returnId"), "returnItemSeqId",
2305:                            returnedItem.get("returnItemSeqId"));
2306:                    returnedAmount = returnedAmount
2307:                            .add(getReturnAdjustmentTotalBd(orderHeader
2308:                                    .getDelegator(), itemAdjustmentCondition));
2309:                    if (orderId.equals(returnedItem.getString("orderId"))
2310:                            && (!returnHeaderList.contains(returnedItem
2311:                                    .getString("returnId")))) {
2312:                        returnHeaderList
2313:                                .add(returnedItem.getString("returnId"));
2314:                    }
2315:                }
2316:                //get  returnedAmount from returnHeader adjustments whose orderId must equals to current orderHeader.orderId
2317:                Iterator returnHeaderIterator = returnHeaderList.iterator();
2318:                while (returnHeaderIterator.hasNext()) {
2319:                    String returnId = (String) returnHeaderIterator.next();
2320:                    Map returnHeaderAdjFilter = UtilMisc.toMap("returnId",
2321:                            returnId, "returnItemSeqId", "_NA_");
2322:                    returnedAmount = returnedAmount.add(
2323:                            getReturnAdjustmentTotalBd(orderHeader
2324:                                    .getDelegator(), returnHeaderAdjFilter))
2325:                            .setScale(scale, rounding);
2326:                }
2327:                return returnedAmount.setScale(scale, rounding);
2328:            }
2329:
2330:            /** Gets the total return credit for COMPLETED and RECEIVED returns. */
2331:            public BigDecimal getOrderReturnedCreditTotalBd() {
2332:                return getOrderReturnedTotalByTypeBd("RTN_CREDIT", false);
2333:            }
2334:
2335:            /** Gets the total return refunded for COMPLETED and RECEIVED returns. */
2336:            public BigDecimal getOrderReturnedRefundTotalBd() {
2337:                return getOrderReturnedTotalByTypeBd("RTN_REFUND", false);
2338:            }
2339:
2340:            /** Gets the total return amount (all return types) for COMPLETED and RECEIVED returns. */
2341:            public BigDecimal getOrderReturnedTotalBd() {
2342:                return getOrderReturnedTotalByTypeBd(null, false);
2343:            }
2344:
2345:            /** 
2346:             * Gets the total returned over all return types.  Specify true to include all return statuses
2347:             * except cancelled.  Specify false to include only COMPLETED and RECEIVED returns.
2348:             */
2349:            public BigDecimal getOrderReturnedTotalBd(boolean includeAll) {
2350:                return getOrderReturnedTotalByTypeBd(null, includeAll);
2351:            }
2352:
2353:            public BigDecimal getOrderNonReturnedTaxAndShippingBd() {
2354:                // first make a Map of orderItemSeqId key, returnQuantity value
2355:                List returnedItemsBase = getOrderReturnItems();
2356:                List returnedItems = new ArrayList(returnedItemsBase.size());
2357:
2358:                // get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
2359:                returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
2360:                        UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
2361:                returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
2362:                        UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
2363:
2364:                Map itemReturnedQuantities = FastMap.newInstance();
2365:                Iterator i = returnedItems.iterator();
2366:                while (i.hasNext()) {
2367:                    GenericValue returnedItem = (GenericValue) i.next();
2368:                    String orderItemSeqId = returnedItem
2369:                            .getString("orderItemSeqId");
2370:                    BigDecimal returnedQuantity = returnedItem
2371:                            .getBigDecimal("returnQuantity");
2372:                    if (orderItemSeqId != null && returnedQuantity != null) {
2373:                        BigDecimal existingQuantity = (BigDecimal) itemReturnedQuantities
2374:                                .get(orderItemSeqId);
2375:                        if (existingQuantity == null) {
2376:                            itemReturnedQuantities.put(orderItemSeqId,
2377:                                    returnedQuantity);
2378:                        } else {
2379:                            itemReturnedQuantities.put(orderItemSeqId,
2380:                                    returnedQuantity.add(existingQuantity));
2381:                        }
2382:                    }
2383:                }
2384:
2385:                // then go through all order items and for the quantity not returned calculate it's portion of the item, and of the entire order
2386:                BigDecimal totalSubTotalNotReturned = ZERO;
2387:                BigDecimal totalTaxNotReturned = ZERO;
2388:                BigDecimal totalShippingNotReturned = ZERO;
2389:
2390:                Iterator orderItems = this .getValidOrderItems().iterator();
2391:                while (orderItems.hasNext()) {
2392:                    GenericValue orderItem = (GenericValue) orderItems.next();
2393:
2394:                    BigDecimal itemQuantityDbl = orderItem
2395:                            .getBigDecimal("quantity");
2396:                    if (itemQuantityDbl == null
2397:                            || itemQuantityDbl.compareTo(ZERO) == 0) {
2398:                        continue;
2399:                    }
2400:                    BigDecimal itemQuantity = itemQuantityDbl;
2401:                    BigDecimal itemSubTotal = this 
2402:                            .getOrderItemSubTotalBd(orderItem);
2403:                    BigDecimal itemTaxes = this .getOrderItemTaxBd(orderItem);
2404:                    BigDecimal itemShipping = this 
2405:                            .getOrderItemShippingBd(orderItem);
2406:
2407:                    BigDecimal quantityReturnedDouble = (BigDecimal) itemReturnedQuantities
2408:                            .get(orderItem.get("orderItemSeqId"));
2409:                    BigDecimal quantityReturned = ZERO;
2410:                    if (quantityReturnedDouble != null) {
2411:                        quantityReturned = quantityReturnedDouble;
2412:                    }
2413:
2414:                    BigDecimal quantityNotReturned = itemQuantity
2415:                            .subtract(quantityReturned);
2416:
2417:                    // pro-rated factor (quantity not returned / total items ordered), which shouldn't be rounded to 2 decimals
2418:                    BigDecimal factorNotReturned = quantityNotReturned.divide(
2419:                            itemQuantity, 100, rounding);
2420:
2421:                    BigDecimal subTotalNotReturned = itemSubTotal.multiply(
2422:                            factorNotReturned).setScale(scale, rounding);
2423:
2424:                    // calculate tax and shipping adjustments for each item, add to accumulators
2425:                    BigDecimal itemTaxNotReturned = itemTaxes.multiply(
2426:                            factorNotReturned).setScale(scale, rounding);
2427:                    BigDecimal itemShippingNotReturned = itemShipping.multiply(
2428:                            factorNotReturned).setScale(scale, rounding);
2429:
2430:                    totalSubTotalNotReturned = totalSubTotalNotReturned
2431:                            .add(subTotalNotReturned);
2432:                    totalTaxNotReturned = totalTaxNotReturned
2433:                            .add(itemTaxNotReturned);
2434:                    totalShippingNotReturned = totalShippingNotReturned
2435:                            .add(itemShippingNotReturned);
2436:                }
2437:
2438:                // calculate tax and shipping adjustments for entire order, add to result
2439:                BigDecimal orderItemsSubTotal = this .getOrderItemsSubTotalBd();
2440:                BigDecimal orderFactorNotReturned = ZERO;
2441:                if (orderItemsSubTotal.signum() != 0) {
2442:                    // pro-rated factor (subtotal not returned / item subtotal), which shouldn't be rounded to 2 decimals
2443:                    orderFactorNotReturned = totalSubTotalNotReturned.divide(
2444:                            orderItemsSubTotal, 100, rounding);
2445:                }
2446:                BigDecimal orderTaxNotReturned = this .getHeaderTaxTotalBd()
2447:                        .multiply(orderFactorNotReturned).setScale(scale,
2448:                                rounding);
2449:                BigDecimal orderShippingNotReturned = this .getShippingTotalBd()
2450:                        .multiply(orderFactorNotReturned).setScale(scale,
2451:                                rounding);
2452:
2453:                return totalTaxNotReturned.add(totalShippingNotReturned).add(
2454:                        orderTaxNotReturned).add(orderShippingNotReturned)
2455:                        .setScale(scale, rounding);
2456:            }
2457:
2458:            /** Gets the total refunded to the order billing account by type.  Specify null to get total over all types. */
2459:            public BigDecimal getBillingAccountReturnedTotalByTypeBd(
2460:                    String returnTypeId) {
2461:                BigDecimal returnedAmount = ZERO;
2462:                List returnedItemsBase = getOrderReturnItems();
2463:                if (returnTypeId != null) {
2464:                    returnedItemsBase = EntityUtil.filterByAnd(
2465:                            returnedItemsBase, UtilMisc.toMap("returnTypeId",
2466:                                    returnTypeId));
2467:                }
2468:                List returnedItems = new ArrayList(returnedItemsBase.size());
2469:
2470:                // get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
2471:                returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
2472:                        UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
2473:                returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
2474:                        UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
2475:
2476:                // sum up the return items that have a return item response with a billing account defined
2477:                try {
2478:                    for (Iterator iter = returnedItems.iterator(); iter
2479:                            .hasNext();) {
2480:                        GenericValue returnItem = (GenericValue) iter.next();
2481:                        GenericValue returnItemResponse = returnItem
2482:                                .getRelatedOne("ReturnItemResponse");
2483:                        if (returnItemResponse == null)
2484:                            continue;
2485:                        if (returnItemResponse.get("billingAccountId") == null)
2486:                            continue;
2487:
2488:                        // we can just add the response amounts
2489:                        returnedAmount = returnedAmount.add(
2490:                                returnItemResponse
2491:                                        .getBigDecimal("responseAmount"))
2492:                                .setScale(scale, rounding);
2493:                    }
2494:                } catch (GenericEntityException e) {
2495:                    Debug.logError(e, e.getMessage(), module);
2496:                }
2497:                return returnedAmount;
2498:            }
2499:
2500:            /** Get the total return credited to the order billing accounts */
2501:            public BigDecimal getBillingAccountReturnedCreditTotalBd() {
2502:                return getBillingAccountReturnedTotalByTypeBd("RTN_CREDIT");
2503:            }
2504:
2505:            /** Get the total return refunded to the order billing accounts */
2506:            public BigDecimal getBillingAccountReturnedRefundTotalBd() {
2507:                return getBillingAccountReturnedTotalByTypeBd("RTN_REFUND");
2508:            }
2509:
2510:            /** Gets the total return credited amount with refunds and credits to the billing account figured in */
2511:            public BigDecimal getReturnedCreditTotalWithBillingAccountBd() {
2512:                return getOrderReturnedCreditTotalBd().add(
2513:                        getBillingAccountReturnedRefundTotalBd()).subtract(
2514:                        getBillingAccountReturnedCreditTotalBd());
2515:            }
2516:
2517:            /** Gets the total return refund amount with refunds and credits to the billing account figured in */
2518:            public BigDecimal getReturnedRefundTotalWithBillingAccountBd() {
2519:                return getOrderReturnedRefundTotalBd().add(
2520:                        getBillingAccountReturnedCreditTotalBd()).subtract(
2521:                        getBillingAccountReturnedRefundTotalBd());
2522:            }
2523:
2524:            /** @deprecated */
2525:            public double getOrderNonReturnedTaxAndShipping() {
2526:                return getOrderNonReturnedTaxAndShippingBd().doubleValue();
2527:            }
2528:
2529:            public BigDecimal getOrderBackorderQuantityBd() {
2530:                BigDecimal backorder = ZERO;
2531:                List items = this .getValidOrderItems();
2532:                if (items != null) {
2533:                    Iterator ii = items.iterator();
2534:                    while (ii.hasNext()) {
2535:                        GenericValue item = (GenericValue) ii.next();
2536:                        List reses = this .getOrderItemShipGrpInvResList(item);
2537:                        if (reses != null) {
2538:                            Iterator ri = reses.iterator();
2539:                            while (ri.hasNext()) {
2540:                                GenericValue res = (GenericValue) ri.next();
2541:                                BigDecimal nav = res
2542:                                        .getBigDecimal("quantityNotAvailable");
2543:                                if (nav != null) {
2544:                                    backorder = backorder.add(nav).setScale(
2545:                                            scale, rounding);
2546:                                }
2547:                            }
2548:                        }
2549:                    }
2550:                }
2551:                return backorder.setScale(scale, rounding);
2552:            }
2553:
2554:            /** @deprecated */
2555:            public double getOrderBackorderQuantity() {
2556:                return getOrderBackorderQuantityBd().doubleValue();
2557:            }
2558:
2559:            public BigDecimal getItemPickedQuantityBd(GenericValue orderItem) {
2560:                BigDecimal quantityPicked = ZERO;
2561:                EntityConditionList pickedConditions = new EntityConditionList(
2562:                        UtilMisc.toList(
2563:                                new EntityExpr("orderId",
2564:                                        EntityOperator.EQUALS, orderItem
2565:                                                .get("orderId")),
2566:                                new EntityExpr("orderItemSeqId",
2567:                                        EntityOperator.EQUALS, orderItem
2568:                                                .getString("orderItemSeqId")),
2569:                                new EntityExpr("statusId",
2570:                                        EntityOperator.NOT_EQUAL,
2571:                                        "PICKLIST_CANCELLED")),
2572:                        EntityOperator.AND);
2573:
2574:                List picked = null;
2575:                try {
2576:                    picked = orderHeader.getDelegator().findByCondition(
2577:                            "PicklistAndBinAndItem", pickedConditions, null,
2578:                            null);
2579:                } catch (GenericEntityException e) {
2580:                    Debug.logError(e, module);
2581:                    this .orderHeader = null;
2582:                }
2583:
2584:                if (picked != null) {
2585:                    Iterator i = picked.iterator();
2586:                    while (i.hasNext()) {
2587:                        GenericValue pickedItem = (GenericValue) i.next();
2588:                        BigDecimal issueQty = pickedItem
2589:                                .getBigDecimal("quantity");
2590:                        if (issueQty != null) {
2591:                            quantityPicked = quantityPicked.add(issueQty)
2592:                                    .setScale(scale, rounding);
2593:                        }
2594:                    }
2595:                }
2596:                return quantityPicked.setScale(scale, rounding);
2597:            }
2598:
2599:            public BigDecimal getItemShippedQuantityBd(GenericValue orderItem) {
2600:                BigDecimal quantityShipped = ZERO;
2601:                List issuance = getOrderItemIssuances(orderItem);
2602:                if (issuance != null) {
2603:                    Iterator i = issuance.iterator();
2604:                    while (i.hasNext()) {
2605:                        GenericValue issue = (GenericValue) i.next();
2606:                        BigDecimal issueQty = issue.getBigDecimal("quantity");
2607:                        if (issueQty != null) {
2608:                            quantityShipped = quantityShipped.add(issueQty)
2609:                                    .setScale(scale, rounding);
2610:                        }
2611:                    }
2612:                }
2613:                return quantityShipped.setScale(scale, rounding);
2614:            }
2615:
2616:            /** @deprecated */
2617:            public double getItemShippedQuantity(GenericValue orderItem) {
2618:                return getItemShippedQuantityBd(orderItem).doubleValue();
2619:            }
2620:
2621:            public BigDecimal getItemReservedQuantityBd(GenericValue orderItem) {
2622:                BigDecimal reserved = ZERO;
2623:
2624:                List reses = getOrderItemShipGrpInvResList(orderItem);
2625:                if (reses != null) {
2626:                    Iterator i = reses.iterator();
2627:                    while (i.hasNext()) {
2628:                        GenericValue res = (GenericValue) i.next();
2629:                        BigDecimal quantity = res.getBigDecimal("quantity");
2630:                        if (quantity != null) {
2631:                            reserved = reserved.add(quantity).setScale(scale,
2632:                                    rounding);
2633:                        }
2634:                    }
2635:                }
2636:                return reserved.setScale(scale, rounding);
2637:            }
2638:
2639:            /** @deprecated */
2640:            public double getItemReservedQuantity(GenericValue orderItem) {
2641:                return getItemReservedQuantityBd(orderItem).doubleValue();
2642:            }
2643:
2644:            public BigDecimal getItemBackorderedQuantityBd(
2645:                    GenericValue orderItem) {
2646:                BigDecimal backOrdered = ZERO;
2647:
2648:                Timestamp shipDate = orderItem
2649:                        .getTimestamp("estimatedShipDate");
2650:                Timestamp autoCancel = orderItem.getTimestamp("autoCancelDate");
2651:
2652:                List reses = getOrderItemShipGrpInvResList(orderItem);
2653:                if (reses != null) {
2654:                    Iterator i = reses.iterator();
2655:                    while (i.hasNext()) {
2656:                        GenericValue res = (GenericValue) i.next();
2657:                        Timestamp promised = res
2658:                                .getTimestamp("currentPromisedDate");
2659:                        if (promised == null) {
2660:                            promised = res.getTimestamp("promisedDatetime");
2661:                        }
2662:                        if (autoCancel != null
2663:                                || (shipDate != null && shipDate
2664:                                        .after(promised))) {
2665:                            BigDecimal resQty = res.getBigDecimal("quantity");
2666:                            if (resQty != null) {
2667:                                backOrdered = backOrdered.add(resQty).setScale(
2668:                                        scale, rounding);
2669:                            }
2670:                        }
2671:                    }
2672:                }
2673:                return backOrdered;
2674:            }
2675:
2676:            /** @deprecated */
2677:            public double getItemBackorderedQuantity(GenericValue orderItem) {
2678:                return getItemBackorderedQuantityBd(orderItem).doubleValue();
2679:            }
2680:
2681:            public BigDecimal getItemPendingShipmentQuantityBd(
2682:                    GenericValue orderItem) {
2683:                BigDecimal reservedQty = getItemReservedQuantityBd(orderItem);
2684:                BigDecimal backordered = getItemBackorderedQuantityBd(orderItem);
2685:                return reservedQty.subtract(backordered).setScale(scale,
2686:                        rounding);
2687:            }
2688:
2689:            /** @deprecated */
2690:            public double getItemPendingShipmentQuantity(GenericValue orderItem) {
2691:                return getItemPendingShipmentQuantityBd(orderItem)
2692:                        .doubleValue();
2693:            }
2694:
2695:            public double getItemCanceledQuantity(GenericValue orderItem) {
2696:                Double cancelQty = orderItem.getDouble("cancelQuantity");
2697:                if (cancelQty == null)
2698:                    cancelQty = new Double(0);
2699:                return cancelQty.doubleValue();
2700:            }
2701:
2702:            public BigDecimal getTotalOrderItemsQuantityBd() {
2703:                List orderItems = getValidOrderItems();
2704:                BigDecimal totalItems = ZERO;
2705:
2706:                for (int i = 0; i < orderItems.size(); i++) {
2707:                    GenericValue oi = (GenericValue) orderItems.get(i);
2708:
2709:                    totalItems = totalItems.add(getOrderItemQuantityBd(oi))
2710:                            .setScale(scale, rounding);
2711:                }
2712:                return totalItems.setScale(scale, rounding);
2713:            }
2714:
2715:            /** @deprecated */
2716:            public double getTotalOrderItemsQuantity() {
2717:                return getTotalOrderItemsQuantityBd().doubleValue();
2718:            }
2719:
2720:            public BigDecimal getTotalOrderItemsOrderedQuantityBd() {
2721:                List orderItems = getValidOrderItems();
2722:                BigDecimal totalItems = ZERO;
2723:
2724:                for (int i = 0; i < orderItems.size(); i++) {
2725:                    GenericValue oi = (GenericValue) orderItems.get(i);
2726:
2727:                    totalItems = totalItems.add(oi.getBigDecimal("quantity"))
2728:                            .setScale(scale, rounding);
2729:                }
2730:                return totalItems;
2731:            }
2732:
2733:            /** @deprecated */
2734:            public double getTotalOrderItemsOrderedQuantity() {
2735:                return getTotalOrderItemsOrderedQuantityBd().doubleValue();
2736:            }
2737:
2738:            public BigDecimal getOrderItemsSubTotalBd() {
2739:                return getOrderItemsSubTotalBd(getValidOrderItems(),
2740:                        getAdjustments());
2741:            }
2742:
2743:            /** @deprecated */
2744:            public double getOrderItemsSubTotal() {
2745:                return getOrderItemsSubTotalBd().doubleValue();
2746:            }
2747:
2748:            public BigDecimal getOrderItemSubTotalBd(GenericValue orderItem) {
2749:                return getOrderItemSubTotalBd(orderItem, getAdjustments());
2750:            }
2751:
2752:            /** @deprecated */
2753:            public double getOrderItemSubTotal(GenericValue orderItem) {
2754:                return getOrderItemSubTotalBd(orderItem).doubleValue();
2755:            }
2756:
2757:            public BigDecimal getOrderItemsTotalBd() {
2758:                return getOrderItemsTotalBd(getValidOrderItems(),
2759:                        getAdjustments());
2760:            }
2761:
2762:            /** @deprecated */
2763:            public double getOrderItemsTotal() {
2764:                return getOrderItemsTotalBd().doubleValue();
2765:            }
2766:
2767:            public BigDecimal getOrderItemTotalBd(GenericValue orderItem) {
2768:                return getOrderItemTotalBd(orderItem, getAdjustments());
2769:            }
2770:
2771:            /** @deprecated */
2772:            public double getOrderItemTotal(GenericValue orderItem) {
2773:                return getOrderItemTotalBd(orderItem).doubleValue();
2774:            }
2775:
2776:            public BigDecimal getOrderItemTaxBd(GenericValue orderItem) {
2777:                return getOrderItemAdjustmentsTotalBd(orderItem, false, true,
2778:                        false);
2779:            }
2780:
2781:            /** @deprecated */
2782:            public double getOrderItemTax(GenericValue orderItem) {
2783:                return getOrderItemTaxBd(orderItem).doubleValue();
2784:            }
2785:
2786:            public BigDecimal getOrderItemShippingBd(GenericValue orderItem) {
2787:                return getOrderItemAdjustmentsTotalBd(orderItem, false, false,
2788:                        true);
2789:            }
2790:
2791:            /** @deprecated */
2792:            public double getOrderItemShipping(GenericValue orderItem) {
2793:                return getOrderItemShippingBd(orderItem).doubleValue();
2794:            }
2795:
2796:            public BigDecimal getOrderItemAdjustmentsTotalBd(
2797:                    GenericValue orderItem, boolean includeOther,
2798:                    boolean includeTax, boolean includeShipping) {
2799:                return getOrderItemAdjustmentsTotalBd(orderItem,
2800:                        getAdjustments(), includeOther, includeTax,
2801:                        includeShipping);
2802:            }
2803:
2804:            /** @deprecated */
2805:            public double getOrderItemAdjustmentsTotal(GenericValue orderItem,
2806:                    boolean includeOther, boolean includeTax,
2807:                    boolean includeShipping) {
2808:                return getOrderItemAdjustmentsTotalBd(orderItem,
2809:                        getAdjustments(), includeOther, includeTax,
2810:                        includeShipping).doubleValue();
2811:            }
2812:
2813:            public BigDecimal getOrderItemAdjustmentsTotalBd(
2814:                    GenericValue orderItem) {
2815:                return getOrderItemAdjustmentsTotalBd(orderItem, true, false,
2816:                        false);
2817:            }
2818:
2819:            /** @deprecated */
2820:            public double getOrderItemAdjustmentsTotal(GenericValue orderItem) {
2821:                return getOrderItemAdjustmentsTotalBd(orderItem, true, false,
2822:                        false).doubleValue();
2823:            }
2824:
2825:            public BigDecimal getOrderItemAdjustmentTotalBd(
2826:                    GenericValue orderItem, GenericValue adjustment) {
2827:                return calcItemAdjustmentBd(adjustment, orderItem);
2828:            }
2829:
2830:            /** @deprecated */
2831:            public double getOrderItemAdjustmentTotal(GenericValue orderItem,
2832:                    GenericValue adjustment) {
2833:                return getOrderItemAdjustmentTotalBd(orderItem, adjustment)
2834:                        .doubleValue();
2835:            }
2836:
2837:            public String getAdjustmentType(GenericValue adjustment) {
2838:                GenericValue adjustmentType = null;
2839:                try {
2840:                    adjustmentType = adjustment
2841:                            .getRelatedOne("OrderAdjustmentType");
2842:                } catch (GenericEntityException e) {
2843:                    Debug.logError(e, "Problems with order adjustment", module);
2844:                }
2845:                if (adjustmentType == null
2846:                        || adjustmentType.get("description") == null) {
2847:                    return "";
2848:                } else {
2849:                    return adjustmentType.getString("description");
2850:                }
2851:            }
2852:
2853:            public List getOrderItemStatuses(GenericValue orderItem) {
2854:                return getOrderItemStatuses(orderItem, getOrderStatuses());
2855:            }
2856:
2857:            public String getCurrentItemStatusString(GenericValue orderItem) {
2858:                GenericValue statusItem = null;
2859:                try {
2860:                    statusItem = orderItem.getRelatedOneCache("StatusItem");
2861:                } catch (GenericEntityException e) {
2862:                    Debug.logError(e, module);
2863:                }
2864:                if (statusItem != null) {
2865:                    return statusItem.getString("description");
2866:                } else {
2867:                    return orderHeader.getString("statusId");
2868:                }
2869:            }
2870:
2871:            /** Fetches the set of order items with the given EntityCondition. */
2872:            public List getOrderItemsByCondition(EntityCondition entityCondition) {
2873:                return EntityUtil.filterByCondition(getOrderItems(),
2874:                        entityCondition);
2875:            }
2876:
2877:            /**
2878:             * Checks to see if this user has read permission on this order
2879:             * @param userLogin The UserLogin value object to check
2880:             * @return boolean True if we have read permission
2881:             */
2882:            public boolean hasPermission(Security security,
2883:                    GenericValue userLogin) {
2884:                return OrderReadHelper.hasPermission(security, userLogin,
2885:                        orderHeader);
2886:            }
2887:
2888:            /**
2889:             * Getter for property orderHeader.
2890:             * @return Value of property orderHeader.
2891:             */
2892:            public GenericValue getOrderHeader() {
2893:                return orderHeader;
2894:            }
2895:
2896:            // ======================================================
2897:            // =================== Static Methods ===================
2898:            // ======================================================
2899:
2900:            public static GenericValue getOrderHeader(
2901:                    GenericDelegator delegator, String orderId) {
2902:                GenericValue orderHeader = null;
2903:                if (orderId != null && delegator != null) {
2904:                    try {
2905:                        orderHeader = delegator.findByPrimaryKey("OrderHeader",
2906:                                UtilMisc.toMap("orderId", orderId));
2907:                    } catch (GenericEntityException e) {
2908:                        Debug.logError(e, "Cannot get order header", module);
2909:                    }
2910:                }
2911:                return orderHeader;
2912:            }
2913:
2914:            public static BigDecimal getOrderItemQuantityBd(
2915:                    GenericValue orderItem) {
2916:
2917:                BigDecimal cancelQty = orderItem
2918:                        .getBigDecimal("cancelQuantity");
2919:                BigDecimal orderQty = orderItem.getBigDecimal("quantity");
2920:
2921:                if (cancelQty == null)
2922:                    cancelQty = ZERO;
2923:                if (orderQty == null)
2924:                    orderQty = ZERO;
2925:
2926:                return orderQty.subtract(cancelQty).setScale(scale, rounding);
2927:            }
2928:
2929:            /** @deprecated */
2930:            public static Double getOrderItemQuantity(GenericValue orderItem) {
2931:                return new Double(getOrderItemQuantityBd(orderItem)
2932:                        .doubleValue());
2933:            }
2934:
2935:            public static Double getOrderItemShipGroupQuantity(
2936:                    GenericValue shipGroupAssoc) {
2937:                Double cancelQty = shipGroupAssoc.getDouble("cancelQuantity");
2938:                Double orderQty = shipGroupAssoc.getDouble("quantity");
2939:
2940:                if (cancelQty == null)
2941:                    cancelQty = new Double(0.0);
2942:                if (orderQty == null)
2943:                    orderQty = new Double(0.0);
2944:
2945:                return new Double(orderQty.doubleValue()
2946:                        - cancelQty.doubleValue());
2947:            }
2948:
2949:            public static GenericValue getProductStoreFromOrder(
2950:                    GenericDelegator delegator, String orderId) {
2951:                GenericValue orderHeader = getOrderHeader(delegator, orderId);
2952:                if (orderHeader == null) {
2953:                    Debug.logWarning("Could not find OrderHeader for orderId ["
2954:                            + orderId
2955:                            + "] in getProductStoreFromOrder, returning null",
2956:                            module);
2957:                }
2958:                return getProductStoreFromOrder(orderHeader);
2959:            }
2960:
2961:            public static GenericValue getProductStoreFromOrder(
2962:                    GenericValue orderHeader) {
2963:                if (orderHeader == null) {
2964:                    return null;
2965:                }
2966:                GenericDelegator delegator = orderHeader.getDelegator();
2967:                GenericValue productStore = null;
2968:                if (orderHeader != null
2969:                        && orderHeader.get("productStoreId") != null) {
2970:                    try {
2971:                        productStore = delegator.findByPrimaryKeyCache(
2972:                                "ProductStore", UtilMisc.toMap(
2973:                                        "productStoreId", orderHeader
2974:                                                .getString("productStoreId")));
2975:                    } catch (GenericEntityException e) {
2976:                        Debug.logError(e,
2977:                                "Cannot locate ProductStore from OrderHeader",
2978:                                module);
2979:                    }
2980:                } else {
2981:                    Debug.logError("Null header or productStoreId", module);
2982:                }
2983:                return productStore;
2984:            }
2985:
2986:            public static BigDecimal getOrderGrandTotalBd(List orderItems,
2987:                    List adjustments) {
2988:                BigDecimal total = getOrderItemsTotalBd(orderItems, adjustments);
2989:                BigDecimal adj = getOrderAdjustmentsTotalBd(orderItems,
2990:                        adjustments);
2991:                return total.add(adj).setScale(scale, rounding);
2992:            }
2993:
2994:            /** @deprecated */
2995:            public static double getOrderGrandTotal(List orderItems,
2996:                    List adjustments) {
2997:                return getOrderGrandTotalBd(orderItems, adjustments)
2998:                        .doubleValue();
2999:            }
3000:
3001:            public static List getOrderHeaderAdjustments(List adjustments,
3002:                    String shipGroupSeqId) {
3003:                List contraints1 = UtilMisc.toList(new EntityExpr(
3004:                        "orderItemSeqId", EntityOperator.EQUALS, null));
3005:                List contraints2 = UtilMisc.toList(new EntityExpr(
3006:                        "orderItemSeqId", EntityOperator.EQUALS,
3007:                        DataModelConstants.SEQ_ID_NA));
3008:                List contraints3 = UtilMisc.toList(new EntityExpr(
3009:                        "orderItemSeqId", EntityOperator.EQUALS, ""));
3010:                List contraints4 = FastList.newInstance();
3011:                if (shipGroupSeqId != null) {
3012:                    contraints4.add(new EntityExpr("shipGroupSeqId",
3013:                            EntityOperator.EQUALS, shipGroupSeqId));
3014:                }
3015:                List toFilter = null;
3016:                List adj = FastList.newInstance();
3017:
3018:                if (shipGroupSeqId != null) {
3019:                    toFilter = EntityUtil.filterByAnd(adjustments, contraints4);
3020:                } else {
3021:                    toFilter = adjustments;
3022:                }
3023:
3024:                adj.addAll(EntityUtil.filterByAnd(toFilter, contraints1));
3025:                adj.addAll(EntityUtil.filterByAnd(toFilter, contraints2));
3026:                adj.addAll(EntityUtil.filterByAnd(toFilter, contraints3));
3027:                return adj;
3028:            }
3029:
3030:            public static List getOrderHeaderStatuses(List orderStatuses) {
3031:                List contraints1 = UtilMisc.toList(new EntityExpr(
3032:                        "orderItemSeqId", EntityOperator.EQUALS, null));
3033:                List contraints2 = UtilMisc.toList(new EntityExpr(
3034:                        "orderItemSeqId", EntityOperator.EQUALS,
3035:                        DataModelConstants.SEQ_ID_NA));
3036:                List contraints3 = UtilMisc.toList(new EntityExpr(
3037:                        "orderItemSeqId", EntityOperator.EQUALS, ""));
3038:                List newOrderStatuses = FastList.newInstance();
3039:
3040:                newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses,
3041:                        contraints1));
3042:                newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses,
3043:                        contraints2));
3044:                newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses,
3045:                        contraints3));
3046:                newOrderStatuses = EntityUtil.orderBy(newOrderStatuses,
3047:                        UtilMisc.toList("-statusDatetime"));
3048:                return newOrderStatuses;
3049:            }
3050:
3051:            public static BigDecimal getOrderAdjustmentsTotalBd(
3052:                    List orderItems, List adjustments) {
3053:                return calcOrderAdjustmentsBd(getOrderHeaderAdjustments(
3054:                        adjustments, null), getOrderItemsSubTotalBd(orderItems,
3055:                        adjustments), true, true, true);
3056:            }
3057:
3058:            /** @deprecated */
3059:            public static double getOrderAdjustmentsTotal(List orderItems,
3060:                    List adjustments) {
3061:                return getOrderAdjustmentsTotalBd(orderItems, adjustments)
3062:                        .doubleValue();
3063:            }
3064:
3065:            public static List getOrderSurveyResponses(GenericValue orderHeader) {
3066:                GenericDelegator delegator = orderHeader.getDelegator();
3067:                String orderId = orderHeader.getString("orderId");
3068:                List responses = null;
3069:                try {
3070:                    responses = delegator.findByAnd("SurveyResponse",
3071:                            UtilMisc.toMap("orderId", orderId,
3072:                                    "orderItemSeqId", "_NA_"));
3073:                } catch (GenericEntityException e) {
3074:                    Debug.logError(e, module);
3075:                }
3076:
3077:                if (responses == null) {
3078:                    responses = FastList.newInstance();
3079:                }
3080:                return responses;
3081:            }
3082:
3083:            public static List getOrderItemSurveyResponse(GenericValue orderItem) {
3084:                GenericDelegator delegator = orderItem.getDelegator();
3085:                String orderItemSeqId = orderItem.getString("orderItemSeqId");
3086:                String orderId = orderItem.getString("orderId");
3087:                List responses = null;
3088:                try {
3089:                    responses = delegator.findByAnd("SurveyResponse", UtilMisc
3090:                            .toMap("orderId", orderId, "orderItemSeqId",
3091:                                    orderItemSeqId));
3092:                } catch (GenericEntityException e) {
3093:                    Debug.logError(e, module);
3094:                }
3095:
3096:                if (responses == null) {
3097:                    responses = FastList.newInstance();
3098:                }
3099:                return responses;
3100:            }
3101:
3102:            // ================= Order Adjustments =================
3103:
3104:            public static BigDecimal calcOrderAdjustmentsBd(
3105:                    List orderHeaderAdjustments, BigDecimal subTotal,
3106:                    boolean includeOther, boolean includeTax,
3107:                    boolean includeShipping) {
3108:                BigDecimal adjTotal = ZERO;
3109:
3110:                if (orderHeaderAdjustments != null
3111:                        && orderHeaderAdjustments.size() > 0) {
3112:                    List filteredAdjs = filterOrderAdjustments(
3113:                            orderHeaderAdjustments, includeOther, includeTax,
3114:                            includeShipping, false, false);
3115:                    Iterator adjIt = filteredAdjs.iterator();
3116:
3117:                    while (adjIt.hasNext()) {
3118:                        GenericValue orderAdjustment = (GenericValue) adjIt
3119:                                .next();
3120:
3121:                        adjTotal = adjTotal.add(
3122:                                OrderReadHelper.calcOrderAdjustmentBd(
3123:                                        orderAdjustment, subTotal)).setScale(
3124:                                scale, rounding);
3125:                    }
3126:                }
3127:                return adjTotal.setScale(scale, rounding);
3128:            }
3129:
3130:            /** @deprecated */
3131:            public static double calcOrderAdjustments(
3132:                    List orderHeaderAdjustments, double subTotal,
3133:                    boolean includeOther, boolean includeTax,
3134:                    boolean includeShipping) {
3135:                return calcOrderAdjustmentsBd(orderHeaderAdjustments,
3136:                        new BigDecimal(subTotal), includeOther, includeTax,
3137:                        includeShipping).doubleValue();
3138:            }
3139:
3140:            public static BigDecimal calcOrderAdjustmentBd(
3141:                    GenericValue orderAdjustment, BigDecimal orderSubTotal) {
3142:                BigDecimal adjustment = ZERO;
3143:
3144:                if (orderAdjustment.get("amount") != null) {
3145:                    // round amount to best precision (taxCalcScale) because db value of 0.825 is pulled as 0.8249999...
3146:                    BigDecimal amount = orderAdjustment.getBigDecimal("amount")
3147:                            .setScale(taxCalcScale, taxRounding);
3148:                    adjustment = adjustment.add(amount);
3149:                } else if (orderAdjustment.get("sourcePercentage") != null) {
3150:                    // round amount to best precision (taxCalcScale) because db value of 0.825 is pulled as 0.8249999...
3151:                    BigDecimal percent = orderAdjustment.getBigDecimal(
3152:                            "sourcePercentage").setScale(taxCalcScale,
3153:                            taxRounding);
3154:                    BigDecimal amount = orderSubTotal.multiply(percent)
3155:                            .multiply(percentage).setScale(taxCalcScale,
3156:                                    taxRounding);
3157:                    adjustment = adjustment.add(amount);
3158:                }
3159:                return adjustment.setScale(scale, rounding);
3160:            }
3161:
3162:            /** @deprecated */
3163:            public static double calcOrderAdjustment(
3164:                    GenericValue orderAdjustment, double orderSubTotal) {
3165:                return calcOrderAdjustmentBd(orderAdjustment,
3166:                        new BigDecimal(orderSubTotal)).doubleValue();
3167:            }
3168:
3169:            // ================= Order Item Adjustments =================
3170:            public static BigDecimal getOrderItemsSubTotalBd(List orderItems,
3171:                    List adjustments) {
3172:                return getOrderItemsSubTotalBd(orderItems, adjustments, null);
3173:            }
3174:
3175:            /** @deprecated */
3176:            public static double getOrderItemsSubTotal(List orderItems,
3177:                    List adjustments) {
3178:                return getOrderItemsSubTotalBd(orderItems, adjustments)
3179:                        .doubleValue();
3180:            }
3181:
3182:            public static BigDecimal getOrderItemsSubTotalBd(List orderItems,
3183:                    List adjustments, List workEfforts) {
3184:                BigDecimal result = ZERO;
3185:                Iterator itemIter = UtilMisc.toIterator(orderItems);
3186:
3187:                while (itemIter != null && itemIter.hasNext()) {
3188:                    GenericValue orderItem = (GenericValue) itemIter.next();
3189:                    BigDecimal itemTotal = getOrderItemSubTotalBd(orderItem,
3190:                            adjustments);
3191:                    // Debug.log("Item : " + orderItem.getString("orderId") + " / " + orderItem.getString("orderItemSeqId") + " = " + itemTotal, module);
3192:
3193:                    if (workEfforts != null
3194:                            && orderItem.getString("orderItemTypeId")
3195:                                    .compareTo("RENTAL_ORDER_ITEM") == 0) {
3196:                        Iterator weIter = UtilMisc.toIterator(workEfforts);
3197:                        while (weIter != null && weIter.hasNext()) {
3198:                            GenericValue workEffort = (GenericValue) weIter
3199:                                    .next();
3200:                            if (workEffort.getString("workEffortId").compareTo(
3201:                                    orderItem.getString("orderItemSeqId")) == 0) {
3202:                                itemTotal = itemTotal
3203:                                        .multiply(
3204:                                                getWorkEffortRentalQuantityBd(workEffort))
3205:                                        .setScale(scale, rounding);
3206:                                break;
3207:                            }
3208:                            //                    Debug.log("Item : " + orderItem.getString("orderId") + " / " + orderItem.getString("orderItemSeqId") + " = " + itemTotal, module);
3209:                        }
3210:                    }
3211:                    result = result.add(itemTotal).setScale(scale, rounding);
3212:
3213:                }
3214:                return result.setScale(scale, rounding);
3215:            }
3216:
3217:            /** @deprecated */
3218:            public static double getOrderItemsSubTotal(List orderItems,
3219:                    List adjustments, List workEfforts) {
3220:                return getOrderItemsSubTotalBd(orderItems, adjustments,
3221:                        workEfforts).doubleValue();
3222:            }
3223:
3224:            /** The passed adjustments can be all adjustments for the order, ie for all line items */
3225:            public static BigDecimal getOrderItemSubTotalBd(
3226:                    GenericValue orderItem, List adjustments) {
3227:                return getOrderItemSubTotalBd(orderItem, adjustments, false,
3228:                        false);
3229:            }
3230:
3231:            /** @deprecated */
3232:            public static double getOrderItemSubTotal(GenericValue orderItem,
3233:                    List adjustments) {
3234:                return getOrderItemSubTotalBd(orderItem, adjustments)
3235:                        .doubleValue();
3236:            }
3237:
3238:            /** The passed adjustments can be all adjustments for the order, ie for all line items */
3239:            public static BigDecimal getOrderItemSubTotalBd(
3240:                    GenericValue orderItem, List adjustments, boolean forTax,
3241:                    boolean forShipping) {
3242:                BigDecimal unitPrice = orderItem.getBigDecimal("unitPrice");
3243:                BigDecimal quantity = getOrderItemQuantityBd(orderItem);
3244:                BigDecimal result = ZERO;
3245:
3246:                if (unitPrice == null || quantity == null) {
3247:                    Debug
3248:                            .logWarning(
3249:                                    "[getOrderItemTotal] unitPrice or quantity are null, using 0 for the item base price",
3250:                                    module);
3251:                } else {
3252:                    if (Debug.verboseOn())
3253:                        Debug.logVerbose("Unit Price : " + unitPrice + " / "
3254:                                + "Quantity : " + quantity, module);
3255:                    result = unitPrice.multiply(quantity);
3256:
3257:                    if ("RENTAL_ORDER_ITEM".equals(orderItem
3258:                            .getString("orderItemTypeId"))) { // retrieve related work effort when required.
3259:                        List WorkOrderItemFulfillments = null;
3260:                        try {
3261:                            WorkOrderItemFulfillments = orderItem
3262:                                    .getDelegator()
3263:                                    .findByAndCache(
3264:                                            "WorkOrderItemFulfillment",
3265:                                            UtilMisc
3266:                                                    .toMap(
3267:                                                            "orderId",
3268:                                                            orderItem
3269:                                                                    .getString("orderId"),
3270:                                                            "orderItemSeqId",
3271:                                                            orderItem
3272:                                                                    .getString("orderItemSeqId")));
3273:                        } catch (GenericEntityException e) {
3274:                        }
3275:                        Iterator iter = WorkOrderItemFulfillments.iterator();
3276:                        if (iter.hasNext()) {
3277:                            GenericValue WorkOrderItemFulfillment = (GenericValue) iter
3278:                                    .next();
3279:                            GenericValue workEffort = null;
3280:                            try {
3281:                                workEffort = WorkOrderItemFulfillment
3282:                                        .getRelatedOneCache("WorkEffort");
3283:                            } catch (GenericEntityException e) {
3284:                            }
3285:                            result = result
3286:                                    .multiply(getWorkEffortRentalQuantityBd(workEffort));
3287:                        }
3288:                    }
3289:                }
3290:
3291:                // subtotal also includes non tax and shipping adjustments; tax and shipping will be calculated using this adjusted value
3292:                result = result.add(getOrderItemAdjustmentsTotalBd(orderItem,
3293:                        adjustments, true, false, false, forTax, forShipping));
3294:
3295:                return result.setScale(scale, rounding);
3296:            }
3297:
3298:            /** @deprecated */
3299:            public static double getOrderItemSubTotal(GenericValue orderItem,
3300:                    List adjustments, boolean forTax, boolean forShipping) {
3301:                return getOrderItemSubTotalBd(orderItem, adjustments, forTax,
3302:                        forShipping).doubleValue();
3303:            }
3304:
3305:            public static BigDecimal getOrderItemsTotalBd(List orderItems,
3306:                    List adjustments) {
3307:                BigDecimal result = ZERO;
3308:                Iterator itemIter = UtilMisc.toIterator(orderItems);
3309:
3310:                while (itemIter != null && itemIter.hasNext()) {
3311:                    result = result.add(getOrderItemTotalBd(
3312:                            (GenericValue) itemIter.next(), adjustments));
3313:                }
3314:                return result.setScale(scale, rounding);
3315:            }
3316:
3317:            /** @deprecated */
3318:            public static double getOrderItemsTotal(List orderItems,
3319:                    List adjustments) {
3320:                return getOrderItemsTotalBd(orderItems, adjustments)
3321:                        .doubleValue();
3322:            }
3323:
3324:            public static BigDecimal getOrderItemTotalBd(
3325:                    GenericValue orderItem, List adjustments) {
3326:                // add tax and shipping to subtotal
3327:                return getOrderItemSubTotalBd(orderItem, adjustments).add(
3328:                        getOrderItemAdjustmentsTotalBd(orderItem, adjustments,
3329:                                false, true, true));
3330:            }
3331:
3332:            /** @deprecated */
3333:            public static double getOrderItemTotal(GenericValue orderItem,
3334:                    List adjustments) {
3335:                return getOrderItemTotalBd(orderItem, adjustments)
3336:                        .doubleValue();
3337:            }
3338:
3339:            public static BigDecimal getWorkEffortRentalQuantityBd(
3340:                    GenericValue workEffort) {
3341:                BigDecimal persons = new BigDecimal(1);
3342:                if (workEffort.get("reservPersons") != null)
3343:                    persons = workEffort.getBigDecimal("reservPersons");
3344:                BigDecimal secondPersonPerc = ZERO;
3345:                if (workEffort.get("reserv2ndPPPerc") != null)
3346:                    secondPersonPerc = workEffort
3347:                            .getBigDecimal("reserv2ndPPPerc");
3348:                BigDecimal nthPersonPerc = ZERO;
3349:                if (workEffort.get("reservNthPPPerc") != null)
3350:                    nthPersonPerc = workEffort.getBigDecimal("reservNthPPPerc");
3351:                long length = 1;
3352:                if (workEffort.get("estimatedStartDate") != null
3353:                        && workEffort.get("estimatedCompletionDate") != null)
3354:                    length = (workEffort
3355:                            .getTimestamp("estimatedCompletionDate").getTime() - workEffort
3356:                            .getTimestamp("estimatedStartDate").getTime()) / 86400000;
3357:
3358:                BigDecimal rentalAdjustment = ZERO;
3359:                if (persons.compareTo(new BigDecimal(1)) == 1) {
3360:                    if (persons.compareTo(new BigDecimal(2)) == 1) {
3361:                        persons = persons.subtract(new BigDecimal(2));
3362:                        if (nthPersonPerc.signum() == 1)
3363:                            rentalAdjustment = persons.multiply(nthPersonPerc);
3364:                        else
3365:                            rentalAdjustment = persons
3366:                                    .multiply(secondPersonPerc);
3367:                        persons = new BigDecimal("2");
3368:                    }
3369:                    if (persons.compareTo(new BigDecimal("2")) == 0)
3370:                        rentalAdjustment = rentalAdjustment
3371:                                .add(secondPersonPerc);
3372:                }
3373:                rentalAdjustment = rentalAdjustment.add(new BigDecimal(100)); // add final 100 percent for first person
3374:                rentalAdjustment = rentalAdjustment.divide(new BigDecimal(100),
3375:                        scale, rounding).multiply(
3376:                        new BigDecimal(String.valueOf(length)));
3377:                //        Debug.logInfo("rental parameters....Nbr of persons:" + persons + " extra% 2nd person:" + secondPersonPerc + " extra% Nth person:" + nthPersonPerc + " Length: " + length + "  total rental adjustment:" + rentalAdjustment ,module);
3378:                return rentalAdjustment; // return total rental adjustment
3379:            }
3380:
3381:            /** @deprecated */
3382:            public static double getWorkEffortRentalQuantity(
3383:                    GenericValue workEffort) {
3384:                return getWorkEffortRentalQuantityBd(workEffort).doubleValue();
3385:            }
3386:
3387:            public static BigDecimal getAllOrderItemsAdjustmentsTotalBd(
3388:                    List orderItems, List adjustments, boolean includeOther,
3389:                    boolean includeTax, boolean includeShipping) {
3390:                BigDecimal result = ZERO;
3391:                Iterator itemIter = UtilMisc.toIterator(orderItems);
3392:
3393:                while (itemIter != null && itemIter.hasNext()) {
3394:                    result = result.add(getOrderItemAdjustmentsTotalBd(
3395:                            (GenericValue) itemIter.next(), adjustments,
3396:                            includeOther, includeTax, includeShipping));
3397:
3398:                }
3399:                return result.setScale(scale, rounding);
3400:            }
3401:
3402:            /** @deprecated */
3403:            public static double getAllOrderItemsAdjustmentsTotal(
3404:                    List orderItems, List adjustments, boolean includeOther,
3405:                    boolean includeTax, boolean includeShipping) {
3406:                return getAllOrderItemsAdjustmentsTotalBd(orderItems,
3407:                        adjustments, includeOther, includeTax, includeShipping)
3408:                        .doubleValue();
3409:            }
3410:
3411:            /** The passed adjustments can be all adjustments for the order, ie for all line items */
3412:            public static BigDecimal getOrderItemAdjustmentsTotalBd(
3413:                    GenericValue orderItem, List adjustments,
3414:                    boolean includeOther, boolean includeTax,
3415:                    boolean includeShipping) {
3416:                return getOrderItemAdjustmentsTotalBd(orderItem, adjustments,
3417:                        includeOther, includeTax, includeShipping, false, false);
3418:            }
3419:
3420:            /** @deprecated */
3421:            public static double getOrderItemAdjustmentsTotal(
3422:                    GenericValue orderItem, List adjustments,
3423:                    boolean includeOther, boolean includeTax,
3424:                    boolean includeShipping) {
3425:                return getOrderItemAdjustmentsTotalBd(orderItem, adjustments,
3426:                        includeOther, includeTax, includeShipping, false, false)
3427:                        .doubleValue();
3428:            }
3429:
3430:            /** The passed adjustments can be all adjustments for the order, ie for all line items */
3431:            public static BigDecimal getOrderItemAdjustmentsTotalBd(
3432:                    GenericValue orderItem, List adjustments,
3433:                    boolean includeOther, boolean includeTax,
3434:                    boolean includeShipping, boolean forTax, boolean forShipping) {
3435:                return calcItemAdjustmentsBd(getOrderItemQuantityBd(orderItem),
3436:                        orderItem.getBigDecimal("unitPrice"),
3437:                        getOrderItemAdjustmentList(orderItem, adjustments),
3438:                        includeOther, includeTax, includeShipping, forTax,
3439:                        forShipping);
3440:            }
3441:
3442:            /** @deprecated */
3443:            public double getOrderItemAdjustmentsTotal(GenericValue orderItem,
3444:                    List adjustments, boolean includeOther, boolean includeTax,
3445:                    boolean includeShipping, boolean forTax, boolean forShipping) {
3446:                return getOrderItemAdjustmentsTotalBd(orderItem, adjustments,
3447:                        includeOther, includeTax, includeShipping, forTax,
3448:                        forShipping).doubleValue();
3449:            }
3450:
3451:            public static List getOrderItemAdjustmentList(
3452:                    GenericValue orderItem, List adjustments) {
3453:                return EntityUtil.filterByAnd(adjustments, UtilMisc.toMap(
3454:                        "orderItemSeqId", orderItem.get("orderItemSeqId")));
3455:            }
3456:
3457:            public static List getOrderItemStatuses(GenericValue orderItem,
3458:                    List orderStatuses) {
3459:                return EntityUtil.orderBy(EntityUtil.filterByAnd(orderStatuses,
3460:                        UtilMisc.toMap("orderItemSeqId", orderItem
3461:                                .get("orderItemSeqId"))), UtilMisc
3462:                        .toList("-statusDatetime"));
3463:            }
3464:
3465:            // Order Item Adjs Utility Methods
3466:
3467:            public static BigDecimal calcItemAdjustmentsBd(BigDecimal quantity,
3468:                    BigDecimal unitPrice, List adjustments,
3469:                    boolean includeOther, boolean includeTax,
3470:                    boolean includeShipping, boolean forTax, boolean forShipping) {
3471:                BigDecimal adjTotal = ZERO;
3472:
3473:                if (adjustments != null && adjustments.size() > 0) {
3474:                    List filteredAdjs = filterOrderAdjustments(adjustments,
3475:                            includeOther, includeTax, includeShipping, forTax,
3476:                            forShipping);
3477:                    Iterator adjIt = filteredAdjs.iterator();
3478:
3479:                    while (adjIt.hasNext()) {
3480:                        GenericValue orderAdjustment = (GenericValue) adjIt
3481:                                .next();
3482:
3483:                        adjTotal = adjTotal.add(OrderReadHelper
3484:                                .calcItemAdjustmentBd(orderAdjustment,
3485:                                        quantity, unitPrice));
3486:                    }
3487:                }
3488:                return adjTotal;
3489:            }
3490:
3491:            public static BigDecimal calcItemAdjustmentsRecurringBd(
3492:                    BigDecimal quantity, BigDecimal unitPrice,
3493:                    List adjustments, boolean includeOther, boolean includeTax,
3494:                    boolean includeShipping, boolean forTax, boolean forShipping) {
3495:                BigDecimal adjTotal = ZERO;
3496:
3497:                if (adjustments != null && adjustments.size() > 0) {
3498:                    List filteredAdjs = filterOrderAdjustments(adjustments,
3499:                            includeOther, includeTax, includeShipping, forTax,
3500:                            forShipping);
3501:                    Iterator adjIt = filteredAdjs.iterator();
3502:
3503:                    while (adjIt.hasNext()) {
3504:                        GenericValue orderAdjustment = (GenericValue) adjIt
3505:                                .next();
3506:
3507:                        adjTotal = adjTotal.add(
3508:                                OrderReadHelper.calcItemAdjustmentRecurringBd(
3509:                                        orderAdjustment, quantity, unitPrice))
3510:                                .setScale(scale, rounding);
3511:                    }
3512:                }
3513:                return adjTotal;
3514:            }
3515:
3516:            /** @deprecated */
3517:            public static double calcItemAdjustments(Double quantity,
3518:                    Double unitPrice, List adjustments, boolean includeOther,
3519:                    boolean includeTax, boolean includeShipping,
3520:                    boolean forTax, boolean forShipping) {
3521:                return calcItemAdjustmentsBd(
3522:                        new BigDecimal(quantity.doubleValue()),
3523:                        new BigDecimal(unitPrice.doubleValue()), adjustments,
3524:                        includeOther, includeTax, includeShipping, forTax,
3525:                        forShipping).doubleValue();
3526:            }
3527:
3528:            public static BigDecimal calcItemAdjustmentBd(
3529:                    GenericValue itemAdjustment, GenericValue item) {
3530:                return calcItemAdjustmentBd(itemAdjustment,
3531:                        getOrderItemQuantityBd(item), item
3532:                                .getBigDecimal("unitPrice"));
3533:            }
3534:
3535:            /** @deprecated */
3536:            public static double calcItemAdjustment(
3537:                    GenericValue itemAdjustment, GenericValue item) {
3538:                return calcItemAdjustmentBd(itemAdjustment, item).doubleValue();
3539:            }
3540:
3541:            public static BigDecimal calcItemAdjustmentBd(
3542:                    GenericValue itemAdjustment, BigDecimal quantity,
3543:                    BigDecimal unitPrice) {
3544:                BigDecimal adjustment = ZERO;
3545:                if (itemAdjustment.get("amount") != null) {
3546:                    adjustment = adjustment.add(setScaleByType(
3547:                            "SALES_TAX".equals(itemAdjustment
3548:                                    .get("orderAdjustmentTypeId")),
3549:                            itemAdjustment.getBigDecimal("amount")));
3550:                } else if (itemAdjustment.get("sourcePercentage") != null) {
3551:                    adjustment = adjustment.add(setScaleByType(
3552:                            "SALES_TAX".equals(itemAdjustment
3553:                                    .get("orderAdjustmentTypeId")),
3554:                            itemAdjustment.getBigDecimal("sourcePercentage")
3555:                                    .multiply(quantity).multiply(unitPrice)
3556:                                    .multiply(percentage)));
3557:                }
3558:                if (Debug.verboseOn())
3559:                    Debug.logVerbose("calcItemAdjustment: " + itemAdjustment
3560:                            + ", quantity=" + quantity + ", unitPrice="
3561:                            + unitPrice + ", adjustment=" + adjustment, module);
3562:                return adjustment;
3563:            }
3564:
3565:            public static BigDecimal calcItemAdjustmentRecurringBd(
3566:                    GenericValue itemAdjustment, BigDecimal quantity,
3567:                    BigDecimal unitPrice) {
3568:                BigDecimal adjustmentRecurring = ZERO;
3569:                if (itemAdjustment.get("recurringAmount") != null) {
3570:                    adjustmentRecurring = adjustmentRecurring
3571:                            .add(setScaleByType("SALES_TAX"
3572:                                    .equals(itemAdjustment
3573:                                            .get("orderAdjustmentTypeId")),
3574:                                    itemAdjustment
3575:                                            .getBigDecimal("recurringAmount")));
3576:                }
3577:                if (Debug.verboseOn())
3578:                    Debug.logVerbose("calcItemAdjustmentRecurring: "
3579:                            + itemAdjustment + ", quantity=" + quantity
3580:                            + ", unitPrice=" + unitPrice
3581:                            + ", adjustmentRecurring=" + adjustmentRecurring,
3582:                            module);
3583:                return adjustmentRecurring.setScale(scale, rounding);
3584:            }
3585:
3586:            /** @deprecated */
3587:            public static double calcItemAdjustment(
3588:                    GenericValue itemAdjustment, Double quantity,
3589:                    Double unitPrice) {
3590:                return calcItemAdjustmentBd(itemAdjustment,
3591:                        new BigDecimal(quantity.doubleValue()),
3592:                        new BigDecimal(unitPrice.doubleValue())).doubleValue();
3593:            }
3594:
3595:            public static List filterOrderAdjustments(List adjustments,
3596:                    boolean includeOther, boolean includeTax,
3597:                    boolean includeShipping, boolean forTax, boolean forShipping) {
3598:                List newOrderAdjustmentsList = FastList.newInstance();
3599:
3600:                if (adjustments != null && adjustments.size() > 0) {
3601:                    Iterator adjIt = adjustments.iterator();
3602:
3603:                    while (adjIt.hasNext()) {
3604:                        GenericValue orderAdjustment = (GenericValue) adjIt
3605:                                .next();
3606:
3607:                        boolean includeAdjustment = false;
3608:
3609:                        if ("SALES_TAX".equals(orderAdjustment
3610:                                .getString("orderAdjustmentTypeId"))) {
3611:                            if (includeTax)
3612:                                includeAdjustment = true;
3613:                        } else if ("SHIPPING_CHARGES".equals(orderAdjustment
3614:                                .getString("orderAdjustmentTypeId"))) {
3615:                            if (includeShipping)
3616:                                includeAdjustment = true;
3617:                        } else {
3618:                            if (includeOther)
3619:                                includeAdjustment = true;
3620:                        }
3621:
3622:                        // 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
3623:                        if (forTax
3624:                                && "N".equals(orderAdjustment
3625:                                        .getString("includeInTax"))) {
3626:                            includeAdjustment = false;
3627:                        }
3628:
3629:                        // 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
3630:                        if (forShipping
3631:                                && "N".equals(orderAdjustment
3632:                                        .getString("includeInShipping"))) {
3633:                            includeAdjustment = false;
3634:                        }
3635:
3636:                        if (includeAdjustment) {
3637:                            newOrderAdjustmentsList.add(orderAdjustment);
3638:                        }
3639:                    }
3640:                }
3641:                return newOrderAdjustmentsList;
3642:            }
3643:
3644:            public static double getQuantityOnOrder(GenericDelegator delegator,
3645:                    String productId) {
3646:                double quantity = 0.0;
3647:
3648:                // first find all open purchase orders
3649:                List openOrdersExprs = UtilMisc
3650:                        .toList(new EntityExpr("orderTypeId",
3651:                                EntityOperator.EQUALS, "PURCHASE_ORDER"));
3652:                openOrdersExprs.add(new EntityExpr("itemStatusId",
3653:                        EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"));
3654:                openOrdersExprs.add(new EntityExpr("itemStatusId",
3655:                        EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
3656:                openOrdersExprs.add(new EntityExpr("itemStatusId",
3657:                        EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"));
3658:                openOrdersExprs.add(new EntityExpr("productId",
3659:                        EntityOperator.EQUALS, productId));
3660:                EntityCondition openOrdersCond = new EntityConditionList(
3661:                        openOrdersExprs, EntityOperator.AND);
3662:                List openOrders = null;
3663:                try {
3664:                    openOrders = delegator.findByCondition(
3665:                            "OrderHeaderAndItems", openOrdersCond, null, null);
3666:                } catch (GenericEntityException e) {
3667:                    Debug.logError(e, module);
3668:                }
3669:
3670:                if (openOrders != null && openOrders.size() > 0) {
3671:                    Iterator i = openOrders.iterator();
3672:                    while (i.hasNext()) {
3673:                        GenericValue order = (GenericValue) i.next();
3674:                        Double this Qty = order.getDouble("quantity");
3675:                        if (this Qty == null) {
3676:                            this Qty = new Double(0);
3677:                        }
3678:                        quantity += this Qty.doubleValue();
3679:                    }
3680:                }
3681:
3682:                return quantity;
3683:            }
3684:
3685:            /**
3686:             * Checks to see if this user has read permission on the specified order
3687:             * @param userLogin The UserLogin value object to check
3688:             * @param orderHeader The OrderHeader for the specified order
3689:             * @return boolean True if we have read permission
3690:             */
3691:            public static boolean hasPermission(Security security,
3692:                    GenericValue userLogin, GenericValue orderHeader) {
3693:                if (userLogin == null || orderHeader == null)
3694:                    return false;
3695:
3696:                if (security
3697:                        .hasEntityPermission("ORDERMGR", "_VIEW", userLogin)) {
3698:                    return true;
3699:                } else if (security.hasEntityPermission("ORDERMGR",
3700:                        "_ROLEVIEW", userLogin)) {
3701:                    List orderRoles = null;
3702:                    try {
3703:                        orderRoles = orderHeader.getRelatedByAnd("OrderRole",
3704:                                UtilMisc.toMap("partyId", userLogin
3705:                                        .getString("partyId")));
3706:                    } catch (GenericEntityException e) {
3707:                        Debug
3708:                                .logError(
3709:                                        e,
3710:                                        "Cannot get OrderRole from OrderHeader",
3711:                                        module);
3712:                    }
3713:
3714:                    if (orderRoles.size() > 0) {
3715:                        // we are in at least one role
3716:                        return true;
3717:                    }
3718:                }
3719:
3720:                return false;
3721:            }
3722:
3723:            public static OrderReadHelper getHelper(GenericValue orderHeader) {
3724:                return new OrderReadHelper(orderHeader);
3725:            }
3726:
3727:            /**
3728:             * Get orderAdjustments that have no corresponding returnAdjustment
3729:             * @return orderAdjustmentList
3730:             */
3731:            public List getAvailableOrderHeaderAdjustments() {
3732:                List orderHeaderAdjustments = this .getOrderHeaderAdjustments();
3733:                List filteredAdjustments = new ArrayList();
3734:                if (orderHeaderAdjustments != null) {
3735:                    Iterator orderAdjIterator = orderHeaderAdjustments
3736:                            .iterator();
3737:                    while (orderAdjIterator.hasNext()) {
3738:                        GenericValue orderAdjustment = (GenericValue) orderAdjIterator
3739:                                .next();
3740:                        long count = 0;
3741:                        try {
3742:                            count = orderHeader.getDelegator().findCountByAnd(
3743:                                    "ReturnAdjustment",
3744:                                    UtilMisc.toMap("orderAdjustmentId",
3745:                                            orderAdjustment
3746:                                                    .get("orderAdjustmentId")));
3747:                        } catch (GenericEntityException e) {
3748:                            Debug.logError(e, module);
3749:                        }
3750:                        if (count == 0) {
3751:                            filteredAdjustments.add(orderAdjustment);
3752:                        }
3753:                    }
3754:                }
3755:                return filteredAdjustments;
3756:            }
3757:
3758:            /**
3759:             * Get the total return adjustments for a set of key -> value condition pairs.  Done for code efficiency.
3760:             * @param delegator
3761:             * @param condition
3762:             * @return
3763:             */
3764:            public static BigDecimal getReturnAdjustmentTotalBd(
3765:                    GenericDelegator delegator, Map condition) {
3766:                BigDecimal total = ZERO;
3767:                List adjustments;
3768:                try {
3769:                    // TODO: find on a view-entity with a sum is probably more efficient
3770:                    adjustments = delegator.findByAnd("ReturnAdjustment",
3771:                            condition);
3772:                    if (adjustments != null) {
3773:                        Iterator adjustmentIterator = adjustments.iterator();
3774:                        while (adjustmentIterator.hasNext()) {
3775:                            GenericValue returnAdjustment = (GenericValue) adjustmentIterator
3776:                                    .next();
3777:                            total = total
3778:                                    .add(
3779:                                            setScaleByType(
3780:                                                    "RET_SALES_TAX_ADJ"
3781:                                                            .equals(returnAdjustment
3782:                                                                    .get("returnAdjustmentTypeId")),
3783:                                                    returnAdjustment
3784:                                                            .getBigDecimal("amount")))
3785:                                    .setScale(scale, rounding);
3786:                        }
3787:                    }
3788:                } catch (GenericEntityException e) {
3789:                    Debug.logError(e, OrderReturnServices.module);
3790:                }
3791:                return total.setScale(scale, rounding);
3792:            }
3793:
3794:            /** @deprecated */
3795:            public static double getReturnAdjustmentTotal(
3796:                    GenericDelegator delegator, Map condition) {
3797:                return getReturnAdjustmentTotalBd(delegator, condition)
3798:                        .doubleValue();
3799:            }
3800:
3801:            // little helper method to set the scale according to tax type
3802:            public static BigDecimal setScaleByType(boolean isTax,
3803:                    BigDecimal value) {
3804:                return isTax ? value.setScale(taxCalcScale, taxRounding)
3805:                        : value.setScale(scale, rounding);
3806:            }
3807:
3808:            /** Get the quantity of order items that have been invoiced */
3809:            public static double getOrderItemInvoicedQuantity(
3810:                    GenericValue orderItem) {
3811:                double invoiced = 0;
3812:                try {
3813:                    // this is simply the sum of quantity billed in all related OrderItemBillings
3814:                    List billings = orderItem.getRelated("OrderItemBilling");
3815:                    for (Iterator iter = billings.iterator(); iter.hasNext();) {
3816:                        GenericValue billing = (GenericValue) iter.next();
3817:                        Double quantity = billing.getDouble("quantity");
3818:                        if (quantity != null) {
3819:                            invoiced += quantity.doubleValue();
3820:                        }
3821:                    }
3822:                } catch (GenericEntityException e) {
3823:                    Debug.logError(e, e.getMessage(), module);
3824:                }
3825:                return invoiced;
3826:            }
3827:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.