You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ofbiz.apache.org by le...@apache.org on 2009/09/12 12:19:11 UTC

svn commit: r814130 [2/2] - /ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java

Modified: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java?rev=814130&r1=814129&r2=814130&view=diff
==============================================================================
--- ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java (original)
+++ ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/invoice/InvoiceServices.java Sat Sep 12 10:19:11 2009
@@ -21,25 +21,23 @@
 import java.math.BigDecimal;
 import java.sql.Timestamp;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.Iterator;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
-import javolution.util.FastList;
 
+import javolution.util.FastList;
 import javolution.util.FastMap;
 
 import org.apache.commons.collections.CollectionUtils;
-import org.ofbiz.accounting.payment.BillingAccountWorker;
-import org.ofbiz.accounting.payment.PaymentWorker;
 import org.ofbiz.accounting.payment.PaymentGatewayServices;
+import org.ofbiz.accounting.payment.PaymentWorker;
 import org.ofbiz.accounting.util.UtilAccounting;
 import org.ofbiz.base.util.Debug;
 import org.ofbiz.base.util.UtilDateTime;
 import org.ofbiz.base.util.UtilFormatOut;
+import org.ofbiz.base.util.UtilGenerics;
 import org.ofbiz.base.util.UtilMisc;
 import org.ofbiz.base.util.UtilNumber;
 import org.ofbiz.base.util.UtilProperties;
@@ -47,12 +45,11 @@
 import org.ofbiz.entity.GenericDelegator;
 import org.ofbiz.entity.GenericEntityException;
 import org.ofbiz.entity.GenericValue;
-import org.ofbiz.entity.util.EntityFindOptions;
-import org.ofbiz.entity.util.EntityUtil;
 import org.ofbiz.entity.condition.EntityCondition;
-import org.ofbiz.entity.condition.EntityOperator;
 import org.ofbiz.entity.condition.EntityExpr;
-import org.ofbiz.entity.condition.EntityConditionList;
+import org.ofbiz.entity.condition.EntityOperator;
+import org.ofbiz.entity.util.EntityFindOptions;
+import org.ofbiz.entity.util.EntityUtil;
 import org.ofbiz.order.order.OrderReadHelper;
 import org.ofbiz.product.product.ProductWorker;
 import org.ofbiz.service.DispatchContext;
@@ -102,22 +99,22 @@
     public static String module = InvoiceServices.class.getName();
 
     // set some BigDecimal properties
-    private static BigDecimal ZERO = BigDecimal.ZERO;
-    private static int decimals = UtilNumber.getBigDecimalScale("invoice.decimals");
-    private static int rounding = UtilNumber.getBigDecimalRoundingMode("invoice.rounding");
-    private static int taxDecimals = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
-    private static int taxRounding = UtilNumber.getBigDecimalRoundingMode("salestax.rounding");
-    public static final int taxCalcScale = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
+    private static final BigDecimal ZERO = BigDecimal.ZERO;
+    private static final int DECIMALS = UtilNumber.getBigDecimalScale("invoice.decimals");
+    private static final int ROUNDING = UtilNumber.getBigDecimalRoundingMode("invoice.rounding");
+    private static final int TAX_DECIMALS = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
+    private static final int TAX_ROUNDING = UtilNumber.getBigDecimalRoundingMode("salestax.rounding");
+    public static final int TAX_CALC_SCALE = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
     private static final int INVOICE_ITEM_SEQUENCE_ID_DIGITS = 5; // this is the number of digits used for invoiceItemSeqId: 00001, 00002...
 
     public static final String resource = "AccountingUiLabels";
 
     // service to create an invoice for a complete order by the system userid
-    public static Map createInvoiceForOrderAllItems(DispatchContext dctx, Map context) {
+    public static Map<String, Object> createInvoiceForOrderAllItems(DispatchContext dctx, Map<String, Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         try {
-            List orderItems = delegator.findByAnd("OrderItem", UtilMisc.toMap("orderId", (String) context.get("orderId")));
+            List<GenericValue> orderItems = delegator.findByAnd("OrderItem", UtilMisc.toMap("orderId", (String) context.get("orderId")));
             if (orderItems.size() > 0) {
                 context.put("billItems", orderItems);
             }
@@ -141,22 +138,23 @@
     }
 
     /* Service to create an invoice for an order */
-    public static Map createInvoiceForOrder(DispatchContext dctx, Map context) {
+    public static Map<String, Object> createInvoiceForOrder(DispatchContext dctx, Map<String, Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
 
-        if (decimals == -1 || rounding == -1) {
+        if (DECIMALS == -1 || ROUNDING == -1) {
             return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingAritmeticPropertiesNotConfigured",locale));
         }
 
         String orderId = (String) context.get("orderId");
-        List billItems = (List) context.get("billItems");
+        List<GenericValue> billItems = UtilGenerics.checkList(context.get("billItems"));
         String invoiceId = (String) context.get("invoiceId");
+        // FIXME: This variable is never read, what is its purpose?
         boolean previousInvoiceFound = false;
 
-        if (billItems == null || billItems.size() == 0) {
+        if (UtilValidate.isEmpty(billItems)) {
             Debug.logVerbose("No order items to invoice; not creating invoice; returning success", module);
             return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource,"AccountingNoOrderItemsToInvoice",locale));
         }
@@ -201,7 +199,7 @@
 
             // Set the precision depending on the type of invoice
             int invoiceTypeDecimals = UtilNumber.getBigDecimalScale("invoice." + invoiceType + ".decimals");
-            if (invoiceTypeDecimals == -1) invoiceTypeDecimals = decimals;
+            if (invoiceTypeDecimals == -1) invoiceTypeDecimals = DECIMALS;
 
             // Make an order read helper from the order
             OrderReadHelper orh = new OrderReadHelper(orderHeader);
@@ -248,7 +246,7 @@
 
             // create the invoice record
             if (UtilValidate.isEmpty(invoiceId)) {
-                Map createInvoiceContext = FastMap.newInstance();
+                Map<String, Object> createInvoiceContext = FastMap.newInstance();
                 createInvoiceContext.put("partyId", billToCustomerPartyId);
                 createInvoiceContext.put("partyIdFrom", billFromVendorPartyId);
                 createInvoiceContext.put("billingAccountId", billingAccountId);
@@ -261,7 +259,7 @@
                 createInvoiceContext.put("userLogin", userLogin);
 
                 // store the invoice first
-                Map createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceContext);
+                Map<String, Object> createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceContext);
                 if (ServiceUtil.isError(createInvoiceResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceFromOrder",locale), null, null, createInvoiceResult);
                 }
@@ -271,30 +269,26 @@
             }
 
             // order roles to invoice roles
-            List orderRoles = orderHeader.getRelated("OrderRole");
-            if (orderRoles != null) {
-                Iterator orderRolesIt = orderRoles.iterator();
-                Map createInvoiceRoleContext = FastMap.newInstance();
-                createInvoiceRoleContext.put("invoiceId", invoiceId);
-                createInvoiceRoleContext.put("userLogin", userLogin);
-                while (orderRolesIt.hasNext()) {
-                    GenericValue orderRole = (GenericValue)orderRolesIt.next();
-                    createInvoiceRoleContext.put("partyId", orderRole.getString("partyId"));
-                    createInvoiceRoleContext.put("roleTypeId", orderRole.getString("roleTypeId"));
-                    Map createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext);
-                    if (ServiceUtil.isError(createInvoiceRoleResult)) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceFromOrder",locale), null, null, createInvoiceRoleResult);
-                    }
+            List<GenericValue> orderRoles = orderHeader.getRelated("OrderRole");
+            Map<String, Object> createInvoiceRoleContext = FastMap.newInstance();
+            createInvoiceRoleContext.put("invoiceId", invoiceId);
+            createInvoiceRoleContext.put("userLogin", userLogin);
+            for (GenericValue orderRole : orderRoles) {
+                createInvoiceRoleContext.put("partyId", orderRole.getString("partyId"));
+                createInvoiceRoleContext.put("roleTypeId", orderRole.getString("roleTypeId"));
+                Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext);
+                if (ServiceUtil.isError(createInvoiceRoleResult)) {
+                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceFromOrder",locale), null, null, createInvoiceRoleResult);
                 }
             }
 
             // order terms to invoice terms.
             // TODO: it might be nice to filter OrderTerms to only copy over financial terms.
-            List orderTerms = orh.getOrderTerms();
+            List<GenericValue> orderTerms = orh.getOrderTerms();
             createInvoiceTerms(delegator, dispatcher, invoiceId, orderTerms, userLogin, locale);
 
             // billing accounts
-            List billingAccountTerms = null;
+            // List billingAccountTerms = null;
             // for billing accounts we will use related information
             if (billingAccount != null) {
                 /*
@@ -307,14 +301,12 @@
                 createInvoiceTerms(delegator, dispatcher, invoiceId, billingAccountTerms, userLogin, locale);
                 */
                 // set the invoice bill_to_customer from the billing account
-                List billToRoles = billingAccount.getRelated("BillingAccountRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), null);
-                Iterator billToIter = billToRoles.iterator();
-                while (billToIter.hasNext()) {
-                    GenericValue billToRole = (GenericValue) billToIter.next();
+                List<GenericValue> billToRoles = billingAccount.getRelated("BillingAccountRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), null);
+                for (GenericValue billToRole : billToRoles) {
                     if (!(billToRole.getString("partyId").equals(billToCustomerPartyId))) {
-                        Map createInvoiceRoleContext = UtilMisc.toMap("invoiceId", invoiceId, "partyId", billToRole.get("partyId"),
+                        createInvoiceRoleContext = UtilMisc.toMap("invoiceId", invoiceId, "partyId", billToRole.get("partyId"),
                                                                            "roleTypeId", "BILL_TO_CUSTOMER", "userLogin", userLogin);
-                        Map createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext);
+                        Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext);
                         if (ServiceUtil.isError(createInvoiceRoleResult)) {
                             return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceRoleFromOrder",locale), null, null, createInvoiceRoleResult);
                         }
@@ -323,22 +315,20 @@
 
                 // set the bill-to contact mech as the contact mech of the billing account
                 if (UtilValidate.isNotEmpty(billingAccount.getString("contactMechId"))) {
-                    Map createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", billingAccount.getString("contactMechId"),
+                    Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", billingAccount.getString("contactMechId"),
                                                                        "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin);
-                    Map createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext);
+                    Map<String, Object> createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext);
                     if (ServiceUtil.isError(createBillToContactMechResult)) {
                         return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceContactMechFromOrder",locale), null, null, createBillToContactMechResult);
                     }
                 }
             } else {
-                List billingLocations = orh.getBillingLocations();
+                List<GenericValue> billingLocations = orh.getBillingLocations();
                 if (UtilValidate.isNotEmpty(billingLocations)) {
-                    Iterator bli = billingLocations.iterator();
-                    while (bli.hasNext()) {
-                        GenericValue ocm = (GenericValue) bli.next();
-                        Map createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString("contactMechId"),
+                    for (GenericValue ocm : billingLocations) {
+                        Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString("contactMechId"),
                                                                            "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin);
-                        Map createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext);
+                        Map<String, Object> createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext);
                         if (ServiceUtil.isError(createBillToContactMechResult)) {
                             return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceContactMechFromOrder",locale), null, null, createBillToContactMechResult);
                         }
@@ -357,7 +347,7 @@
                 // for purchase orders, the pay to address is the BILLING_LOCATION of the vendor
                 GenericValue billFromVendor = orh.getPartyFromRole("BILL_FROM_VENDOR");
                 if (billFromVendor != null) {
-                    List billingContactMechs = billFromVendor.getRelatedOne("Party").getRelatedByAnd("PartyContactMechPurpose",
+                    List<GenericValue> billingContactMechs = billFromVendor.getRelatedOne("Party").getRelatedByAnd("PartyContactMechPurpose",
                             UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"));
                     if ((billingContactMechs != null) && (billingContactMechs.size() > 0)) {
                         payToAddress = (GenericValue) billingContactMechs.get(0);
@@ -368,9 +358,9 @@
                 payToAddress = PaymentWorker.getPaymentAddress(delegator, productStore.getString("payToPartyId"));
             }
             if (payToAddress != null) {
-                Map createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString("contactMechId"),
+                Map<String, Object> createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString("contactMechId"),
                                                                    "contactMechPurposeTypeId", "PAYMENT_LOCATION", "userLogin", userLogin);
-                Map createPayToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createPayToContactMechContext);
+                Map<String, Object> createPayToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createPayToContactMechContext);
                 if (ServiceUtil.isError(createPayToContactMechResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceContactMechFromOrder",locale), null, null, createPayToContactMechResult);
                 }
@@ -381,289 +371,281 @@
             String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
 
             // create the item records
-            if (billItems != null) {
-                Iterator itemIter = billItems.iterator();
-                while (itemIter.hasNext()) {
-                    GenericValue itemIssuance = null;
-                    GenericValue orderItem = null;
-                    GenericValue shipmentReceipt = null;
-                    GenericValue currentValue = (GenericValue) itemIter.next();
-                    if ("ItemIssuance".equals(currentValue.getEntityName())) {
-                        itemIssuance = currentValue;
-                    } else if ("OrderItem".equals(currentValue.getEntityName())) {
-                        orderItem = currentValue;
-                    } else if ("ShipmentReceipt".equals(currentValue.getEntityName())) {
-                        shipmentReceipt = currentValue;
-                    } else {
-                        Debug.logError("Unexpected entity " + currentValue + " of type " + currentValue.getEntityName(), module);
-                    }
+            for (GenericValue currentValue : billItems) {
+                GenericValue itemIssuance = null;
+                GenericValue orderItem = null;
+                GenericValue shipmentReceipt = null;
+                if ("ItemIssuance".equals(currentValue.getEntityName())) {
+                    itemIssuance = currentValue;
+                } else if ("OrderItem".equals(currentValue.getEntityName())) {
+                    orderItem = currentValue;
+                } else if ("ShipmentReceipt".equals(currentValue.getEntityName())) {
+                    shipmentReceipt = currentValue;
+                } else {
+                    Debug.logError("Unexpected entity " + currentValue + " of type " + currentValue.getEntityName(), module);
+                }
 
-                    if (orderItem == null && itemIssuance != null) {
-                        orderItem = itemIssuance.getRelatedOne("OrderItem");
-                    } else if ((orderItem == null) && (shipmentReceipt != null)) {
-                        orderItem = shipmentReceipt.getRelatedOne("OrderItem");
-                    } else if ((orderItem == null) && (itemIssuance == null) && (shipmentReceipt == null)) {
-                        Debug.logError("Cannot create invoice when orderItem, itemIssuance, and shipmentReceipt are all null", module);
-                        return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingIllegalValuesPassedToCreateInvoiceService",locale));
-                    }
-                    GenericValue product = null;
-                    if (orderItem.get("productId") != null) {
-                        product = orderItem.getRelatedOne("Product");
-                    }
-
-                    // get some quantities
-                    BigDecimal orderedQuantity = orderItem.getBigDecimal("quantity");
-                    BigDecimal billingQuantity = null;
-                    if (itemIssuance != null) {
-                        billingQuantity = itemIssuance.getBigDecimal("quantity");
-                        BigDecimal cancelQty = itemIssuance.getBigDecimal("cancelQuantity");
-                        if (cancelQty == null) {
-                            cancelQty = ZERO;
-                        }
-                        billingQuantity = billingQuantity.subtract(cancelQty).setScale(decimals, rounding);
-                    } else if (shipmentReceipt != null) {
-                        billingQuantity = shipmentReceipt.getBigDecimal("quantityAccepted");
-                    } else {
-                        billingQuantity = orderedQuantity;
-                    }
-                    if (orderedQuantity == null) orderedQuantity = ZERO;
-                    if (billingQuantity == null) billingQuantity = ZERO;
+                if (orderItem == null && itemIssuance != null) {
+                    orderItem = itemIssuance.getRelatedOne("OrderItem");
+                } else if ((orderItem == null) && (shipmentReceipt != null)) {
+                    orderItem = shipmentReceipt.getRelatedOne("OrderItem");
+                } else if ((orderItem == null) && (itemIssuance == null) && (shipmentReceipt == null)) {
+                    Debug.logError("Cannot create invoice when orderItem, itemIssuance, and shipmentReceipt are all null", module);
+                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingIllegalValuesPassedToCreateInvoiceService",locale));
+                }
+                GenericValue product = null;
+                if (orderItem.get("productId") != null) {
+                    product = orderItem.getRelatedOne("Product");
+                }
+
+                // get some quantities
+                BigDecimal orderedQuantity = orderItem.getBigDecimal("quantity");
+                BigDecimal billingQuantity = null;
+                if (itemIssuance != null) {
+                    billingQuantity = itemIssuance.getBigDecimal("quantity");
+                    BigDecimal cancelQty = itemIssuance.getBigDecimal("cancelQuantity");
+                    if (cancelQty == null) {
+                        cancelQty = ZERO;
+                    }
+                    billingQuantity = billingQuantity.subtract(cancelQty).setScale(DECIMALS, ROUNDING);
+                } else if (shipmentReceipt != null) {
+                    billingQuantity = shipmentReceipt.getBigDecimal("quantityAccepted");
+                } else {
+                    billingQuantity = orderedQuantity;
+                }
+                if (orderedQuantity == null) orderedQuantity = ZERO;
+                if (billingQuantity == null) billingQuantity = ZERO;
 
-                    // check if shipping applies to this item.  Shipping is calculated for sales invoices, not purchase invoices.
-                    boolean shippingApplies = false;
-                    if ((product != null) && (ProductWorker.shippingApplies(product)) && (invoiceType.equals("SALES_INVOICE"))) {
-                        shippingApplies = true;
-                    }
+                // check if shipping applies to this item.  Shipping is calculated for sales invoices, not purchase invoices.
+                boolean shippingApplies = false;
+                if ((product != null) && (ProductWorker.shippingApplies(product)) && (invoiceType.equals("SALES_INVOICE"))) {
+                    shippingApplies = true;
+                }
 
-                    BigDecimal billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, rounding);
+                BigDecimal billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, ROUNDING);
 
-                    Map createInvoiceItemContext = FastMap.newInstance();
-                    createInvoiceItemContext.put("invoiceId", invoiceId);
-                    createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                    createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, (orderItem.getString("orderItemTypeId")), (product == null ? null : product.getString("productTypeId")), invoiceType, "INV_FPROD_ITEM"));
-                    createInvoiceItemContext.put("description", orderItem.get("itemDescription"));
-                    createInvoiceItemContext.put("quantity", billingQuantity);
-                    createInvoiceItemContext.put("amount", billingAmount);
-                    createInvoiceItemContext.put("productId", orderItem.get("productId"));
-                    createInvoiceItemContext.put("productFeatureId", orderItem.get("productFeatureId"));
-                    createInvoiceItemContext.put("overrideGlAccountId", orderItem.get("overrideGlAccountId"));
-                    //createInvoiceItemContext.put("uomId", "");
-                    createInvoiceItemContext.put("userLogin", userLogin);
+                Map<String, Object> createInvoiceItemContext = FastMap.newInstance();
+                createInvoiceItemContext.put("invoiceId", invoiceId);
+                createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
+                createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, (orderItem.getString("orderItemTypeId")), (product == null ? null : product.getString("productTypeId")), invoiceType, "INV_FPROD_ITEM"));
+                createInvoiceItemContext.put("description", orderItem.get("itemDescription"));
+                createInvoiceItemContext.put("quantity", billingQuantity);
+                createInvoiceItemContext.put("amount", billingAmount);
+                createInvoiceItemContext.put("productId", orderItem.get("productId"));
+                createInvoiceItemContext.put("productFeatureId", orderItem.get("productFeatureId"));
+                createInvoiceItemContext.put("overrideGlAccountId", orderItem.get("overrideGlAccountId"));
+                //createInvoiceItemContext.put("uomId", "");
+                createInvoiceItemContext.put("userLogin", userLogin);
 
-                    String itemIssuanceId = null;
-                    if (itemIssuance != null && itemIssuance.get("inventoryItemId") != null) {
-                        itemIssuanceId = itemIssuance.getString("itemIssuanceId");
-                        createInvoiceItemContext.put("inventoryItemId", itemIssuance.get("inventoryItemId"));
-                    }
-                    // similarly, tax only for purchase invoices
-                    if ((product != null) && (invoiceType.equals("SALES_INVOICE"))) {
-                        createInvoiceItemContext.put("taxableFlag", product.get("taxable"));
-                    }
+                String itemIssuanceId = null;
+                if (itemIssuance != null && itemIssuance.get("inventoryItemId") != null) {
+                    itemIssuanceId = itemIssuance.getString("itemIssuanceId");
+                    createInvoiceItemContext.put("inventoryItemId", itemIssuance.get("inventoryItemId"));
+                }
+                // similarly, tax only for purchase invoices
+                if ((product != null) && (invoiceType.equals("SALES_INVOICE"))) {
+                    createInvoiceItemContext.put("taxableFlag", product.get("taxable"));
+                }
 
-                    Map createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext);
-                    if (ServiceUtil.isError(createInvoiceItemResult)) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceItemFromOrder",locale), null, null, createInvoiceItemResult);
-                    }
+                Map<String, Object> createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext);
+                if (ServiceUtil.isError(createInvoiceItemResult)) {
+                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceItemFromOrder",locale), null, null, createInvoiceItemResult);
+                }
 
-                    // this item total
-                    BigDecimal thisAmount = billingAmount.multiply(billingQuantity).setScale(invoiceTypeDecimals, rounding);
+                // this item total
+                BigDecimal thisAmount = billingAmount.multiply(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING);
 
-                    // add to the ship amount only if it applies to this item
-                    if (shippingApplies) {
-                        invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAmount).setScale(invoiceTypeDecimals, rounding);
-                    }
+                // add to the ship amount only if it applies to this item
+                if (shippingApplies) {
+                    invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAmount).setScale(invoiceTypeDecimals, ROUNDING);
+                }
 
-                    // increment the invoice subtotal
-                    invoiceSubTotal = invoiceSubTotal.add(thisAmount).setScale(100, rounding);
+                // increment the invoice subtotal
+                invoiceSubTotal = invoiceSubTotal.add(thisAmount).setScale(100, ROUNDING);
 
-                    // increment the invoice quantity
-                    invoiceQuantity = invoiceQuantity.add(billingQuantity).setScale(invoiceTypeDecimals, rounding);
+                // increment the invoice quantity
+                invoiceQuantity = invoiceQuantity.add(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING);
 
-                    // create the OrderItemBilling record
-                    Map createOrderItemBillingContext = FastMap.newInstance();
-                    createOrderItemBillingContext.put("invoiceId", invoiceId);
-                    createOrderItemBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                    createOrderItemBillingContext.put("orderId", orderItem.get("orderId"));
-                    createOrderItemBillingContext.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
-                    createOrderItemBillingContext.put("itemIssuanceId", itemIssuanceId);
-                    createOrderItemBillingContext.put("quantity", billingQuantity);
-                    createOrderItemBillingContext.put("amount", billingAmount);
-                    createOrderItemBillingContext.put("userLogin", userLogin);
-                    if ((shipmentReceipt != null) && (shipmentReceipt.getString("receiptId") != null)) {
-                        createOrderItemBillingContext.put("shipmentReceiptId", shipmentReceipt.getString("receiptId"));
-                    }
+                // create the OrderItemBilling record
+                Map<String, Object> createOrderItemBillingContext = FastMap.newInstance();
+                createOrderItemBillingContext.put("invoiceId", invoiceId);
+                createOrderItemBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
+                createOrderItemBillingContext.put("orderId", orderItem.get("orderId"));
+                createOrderItemBillingContext.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
+                createOrderItemBillingContext.put("itemIssuanceId", itemIssuanceId);
+                createOrderItemBillingContext.put("quantity", billingQuantity);
+                createOrderItemBillingContext.put("amount", billingAmount);
+                createOrderItemBillingContext.put("userLogin", userLogin);
+                if ((shipmentReceipt != null) && (shipmentReceipt.getString("receiptId") != null)) {
+                    createOrderItemBillingContext.put("shipmentReceiptId", shipmentReceipt.getString("receiptId"));
+                }
 
-                    Map createOrderItemBillingResult = dispatcher.runSync("createOrderItemBilling", createOrderItemBillingContext);
-                    if (ServiceUtil.isError(createOrderItemBillingResult)) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingOrderItemBillingFromOrder",locale), null, null, createOrderItemBillingResult);
-                    }
+                Map<String, Object> createOrderItemBillingResult = dispatcher.runSync("createOrderItemBilling", createOrderItemBillingContext);
+                if (ServiceUtil.isError(createOrderItemBillingResult)) {
+                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingOrderItemBillingFromOrder",locale), null, null, createOrderItemBillingResult);
+                }
 
-                    if ("ItemIssuance".equals(currentValue.getEntityName())) {
-                        List<GenericValue> shipmentItemBillings = delegator.findByAnd("ShipmentItemBilling", UtilMisc.toMap("shipmentId", currentValue.get("shipmentId")));
-                        if (UtilValidate.isEmpty(shipmentItemBillings)) {
+                if ("ItemIssuance".equals(currentValue.getEntityName())) {
+                    List<GenericValue> shipmentItemBillings = delegator.findByAnd("ShipmentItemBilling", UtilMisc.toMap("shipmentId", currentValue.get("shipmentId")));
+                    if (UtilValidate.isEmpty(shipmentItemBillings)) {
 
-                            // create the ShipmentItemBilling record
-                            GenericValue shipmentItemBilling = delegator.makeValue("ShipmentItemBilling", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId));
-                            shipmentItemBilling.put("shipmentId", currentValue.get("shipmentId"));
-                            shipmentItemBilling.put("shipmentItemSeqId", currentValue.get("shipmentItemSeqId"));
-                            shipmentItemBilling.create();
-                        }
+                        // create the ShipmentItemBilling record
+                        GenericValue shipmentItemBilling = delegator.makeValue("ShipmentItemBilling", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId));
+                        shipmentItemBilling.put("shipmentId", currentValue.get("shipmentId"));
+                        shipmentItemBilling.put("shipmentItemSeqId", currentValue.get("shipmentItemSeqId"));
+                        shipmentItemBilling.create();
                     }
+                }
 
-                    String parentInvoiceItemSeqId = invoiceItemSeqId;
-                    // increment the counter
-                    invoiceItemSeqNum++;
-                    invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
+                String parentInvoiceItemSeqId = invoiceItemSeqId;
+                // increment the counter
+                invoiceItemSeqNum++;
+                invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
 
-                    // Get the original order item from the DB, in case the quantity has been overridden
-                    GenericValue originalOrderItem = delegator.findByPrimaryKey("OrderItem", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.getString("orderItemSeqId")));
+                // Get the original order item from the DB, in case the quantity has been overridden
+                GenericValue originalOrderItem = delegator.findByPrimaryKey("OrderItem", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.getString("orderItemSeqId")));
 
-                    // create the item adjustment as line items
-                    List itemAdjustments = OrderReadHelper.getOrderItemAdjustmentList(orderItem, orh.getAdjustments());
-                    Iterator itemAdjIter = itemAdjustments.iterator();
-                    while (itemAdjIter.hasNext()) {
-                        GenericValue adj = (GenericValue) itemAdjIter.next();
+                // create the item adjustment as line items
+                List<GenericValue> itemAdjustments = OrderReadHelper.getOrderItemAdjustmentList(orderItem, orh.getAdjustments());
+                for (GenericValue adj : itemAdjustments) {
 
-                        // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced
-                        BigDecimal adjAlreadyInvoicedAmount = null;
-                        try {
-                            Map checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj));
-                            adjAlreadyInvoicedAmount = (BigDecimal) checkResult.get("invoicedTotal");
-                        } catch (GenericServiceException e) {
-                            String errMsg = UtilProperties.getMessage(resource, "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale);
-                            Debug.logError(e, errMsg, module);
-                            return ServiceUtil.returnError(errMsg);
-                        }
+                    // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced
+                    BigDecimal adjAlreadyInvoicedAmount = null;
+                    try {
+                        Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj));
+                        adjAlreadyInvoicedAmount = (BigDecimal) checkResult.get("invoicedTotal");
+                    } catch (GenericServiceException e) {
+                        String errMsg = UtilProperties.getMessage(resource, "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale);
+                        Debug.logError(e, errMsg, module);
+                        return ServiceUtil.returnError(errMsg);
+                    }
 
-                        // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced,
-                        //  so skip this adjustment
-                        if (adj.get("amount") == null) { // JLR 17/4/7 : fix a bug coming from POS in case of use of a discount (on item(s) or sale, item(s) here) and a cash amount higher than total (hence issuing change)
-                            continue;
+                    // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced,
+                    //  so skip this adjustment
+                    if (adj.get("amount") == null) { // JLR 17/4/7 : fix a bug coming from POS in case of use of a discount (on item(s) or sale, item(s) here) and a cash amount higher than total (hence issuing change)
+                        continue;
+                    }
+                    if (adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) {
+                        continue;
+                    }
+
+                    BigDecimal amount = ZERO;
+                    if (adj.get("amount") != null) {
+                        // pro-rate the amount
+                        // set decimals = 100 means we don't round this intermediate value, which is very important
+                        amount = adj.getBigDecimal("amount").divide(originalOrderItem.getBigDecimal("quantity"), 100, ROUNDING);
+                        amount = amount.multiply(billingQuantity);
+                        // Tax needs to be rounded differently from other order adjustments
+                        if (adj.getString("orderAdjustmentTypeId").equals("SALES_TAX")) {
+                            amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING);
+                        } else {
+                            amount = amount.setScale(invoiceTypeDecimals, ROUNDING);
                         }
-                        if (adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, rounding).abs()) > 0) {
-                            continue;
+                    } else if (adj.get("sourcePercentage") != null) {
+                        // pro-rate the amount
+                        // set decimals = 100 means we don't round this intermediate value, which is very important
+                        BigDecimal percent = adj.getBigDecimal("sourcePercentage");
+                        percent = percent.divide(new BigDecimal(100), 100, ROUNDING);
+                        amount = billingAmount.multiply(percent);
+                        amount = amount.divide(originalOrderItem.getBigDecimal("quantity"), 100, ROUNDING);
+                        amount = amount.multiply(billingQuantity);
+                        amount = amount.setScale(invoiceTypeDecimals, ROUNDING);
+                    }
+                    if (amount.signum() != 0) {
+                        Map<String, Object> createInvoiceItemAdjContext = FastMap.newInstance();
+                        createInvoiceItemAdjContext.put("invoiceId", invoiceId);
+                        createInvoiceItemAdjContext.put("invoiceItemSeqId", invoiceItemSeqId);
+                        createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceType, "INVOICE_ITM_ADJ"));
+                        createInvoiceItemAdjContext.put("quantity", BigDecimal.ONE);
+                        createInvoiceItemAdjContext.put("amount", amount);
+                        createInvoiceItemAdjContext.put("productId", orderItem.get("productId"));
+                        createInvoiceItemAdjContext.put("productFeatureId", orderItem.get("productFeatureId"));
+                        createInvoiceItemAdjContext.put("overrideGlAccountId", adj.get("overrideGlAccountId"));
+                        createInvoiceItemAdjContext.put("parentInvoiceId", invoiceId);
+                        createInvoiceItemAdjContext.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId);
+                        //createInvoiceItemAdjContext.put("uomId", "");
+                        createInvoiceItemAdjContext.put("userLogin", userLogin);
+                        createInvoiceItemAdjContext.put("taxAuthPartyId", adj.get("taxAuthPartyId"));
+                        createInvoiceItemAdjContext.put("taxAuthGeoId", adj.get("taxAuthGeoId"));
+                        createInvoiceItemAdjContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));
+
+                        // some adjustments fill out the comments field instead
+                        String description = (UtilValidate.isEmpty(adj.getString("description")) ? adj.getString("comments") : adj.getString("description"));
+                        createInvoiceItemAdjContext.put("description", description);
+
+                        // invoice items for sales tax are not taxable themselves
+                        // TODO: This is not an ideal solution. Instead, we need to use OrderAdjustment.includeInTax when it is implemented
+                        if (!(adj.getString("orderAdjustmentTypeId").equals("SALES_TAX"))) {
+                            createInvoiceItemAdjContext.put("taxableFlag", product.get("taxable"));
+                        }
+
+                        // If the OrderAdjustment is associated to a ProductPromo,
+                        // and the field ProductPromo.overrideOrgPartyId is set,
+                        // copy the value to InvoiceItem.overrideOrgPartyId: this
+                        // represent an organization override for the payToPartyId
+                        if (UtilValidate.isNotEmpty(adj.getString("productPromoId"))) {
+                            try {
+                                GenericValue productPromo = adj.getRelatedOne("ProductPromo");
+                                if (UtilValidate.isNotEmpty(productPromo.getString("overrideOrgPartyId"))) {
+                                    createInvoiceItemAdjContext.put("overrideOrgPartyId", productPromo.getString("overrideOrgPartyId"));
+                                }
+                            } catch (GenericEntityException e) {
+                                Debug.logError(e, "Error looking up ProductPromo with id [" + adj.getString("productPromoId") + "]", module);
+                            }
                         }
 
-                        BigDecimal amount = ZERO;
-                        if (adj.get("amount") != null) {
-                            // pro-rate the amount
-                            // set decimals = 100 means we don't round this intermediate value, which is very important
-                            amount = adj.getBigDecimal("amount").divide(originalOrderItem.getBigDecimal("quantity"), 100, rounding);
-                            amount = amount.multiply(billingQuantity);
-                            // Tax needs to be rounded differently from other order adjustments
-                            if (adj.getString("orderAdjustmentTypeId").equals("SALES_TAX")) {
-                                amount = amount.setScale(taxDecimals, taxRounding);
-                            } else {
-                                amount = amount.setScale(invoiceTypeDecimals, rounding);
-                            }
-                        } else if (adj.get("sourcePercentage") != null) {
-                            // pro-rate the amount
-                            // set decimals = 100 means we don't round this intermediate value, which is very important
-                            BigDecimal percent = adj.getBigDecimal("sourcePercentage");
-                            percent = percent.divide(new BigDecimal(100), 100, rounding);
-                            amount = billingAmount.multiply(percent);
-                            amount = amount.divide(originalOrderItem.getBigDecimal("quantity"), 100, rounding);
-                            amount = amount.multiply(billingQuantity);
-                            amount = amount.setScale(invoiceTypeDecimals, rounding);
-                        }
-                        if (amount.signum() != 0) {
-                            Map createInvoiceItemAdjContext = FastMap.newInstance();
-                            createInvoiceItemAdjContext.put("invoiceId", invoiceId);
-                            createInvoiceItemAdjContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                            createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceType, "INVOICE_ITM_ADJ"));
-                            createInvoiceItemAdjContext.put("quantity", BigDecimal.ONE);
-                            createInvoiceItemAdjContext.put("amount", amount);
-                            createInvoiceItemAdjContext.put("productId", orderItem.get("productId"));
-                            createInvoiceItemAdjContext.put("productFeatureId", orderItem.get("productFeatureId"));
-                            createInvoiceItemAdjContext.put("overrideGlAccountId", adj.get("overrideGlAccountId"));
-                            createInvoiceItemAdjContext.put("parentInvoiceId", invoiceId);
-                            createInvoiceItemAdjContext.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId);
-                            //createInvoiceItemAdjContext.put("uomId", "");
-                            createInvoiceItemAdjContext.put("userLogin", userLogin);
-                            createInvoiceItemAdjContext.put("taxAuthPartyId", adj.get("taxAuthPartyId"));
-                            createInvoiceItemAdjContext.put("taxAuthGeoId", adj.get("taxAuthGeoId"));
-                            createInvoiceItemAdjContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));
-
-                            // some adjustments fill out the comments field instead
-                            String description = (UtilValidate.isEmpty(adj.getString("description")) ? adj.getString("comments") : adj.getString("description"));
-                            createInvoiceItemAdjContext.put("description", description);
-
-                            // invoice items for sales tax are not taxable themselves
-                            // TODO: This is not an ideal solution. Instead, we need to use OrderAdjustment.includeInTax when it is implemented
-                            if (!(adj.getString("orderAdjustmentTypeId").equals("SALES_TAX"))) {
-                                createInvoiceItemAdjContext.put("taxableFlag", product.get("taxable"));
-                            }
+                        Map<String, Object> createInvoiceItemAdjResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemAdjContext);
+                        if (ServiceUtil.isError(createInvoiceItemAdjResult)) {
+                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceItemFromOrder",locale), null, null, createInvoiceItemAdjResult);
+                        }
 
-                            // If the OrderAdjustment is associated to a ProductPromo,
-                            // and the field ProductPromo.overrideOrgPartyId is set,
-                            // copy the value to InvoiceItem.overrideOrgPartyId: this
-                            // represent an organization override for the payToPartyId
-                            if (UtilValidate.isNotEmpty(adj.getString("productPromoId"))) {
-                                try {
-                                    GenericValue productPromo = adj.getRelatedOne("ProductPromo");
-                                    if (UtilValidate.isNotEmpty(productPromo.getString("overrideOrgPartyId"))) {
-                                        createInvoiceItemAdjContext.put("overrideOrgPartyId", productPromo.getString("overrideOrgPartyId"));
-                                    }
-                                } catch (GenericEntityException e) {
-                                    Debug.logError(e, "Error looking up ProductPromo with id [" + adj.getString("productPromoId") + "]", module);
-                                }
-                            }
+                        // Create the OrderAdjustmentBilling record
+                        Map<String, Object> createOrderAdjustmentBillingContext = FastMap.newInstance();
+                        createOrderAdjustmentBillingContext.put("orderAdjustmentId", adj.getString("orderAdjustmentId"));
+                        createOrderAdjustmentBillingContext.put("invoiceId", invoiceId);
+                        createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
+                        createOrderAdjustmentBillingContext.put("amount", amount);
+                        createOrderAdjustmentBillingContext.put("userLogin", userLogin);
 
-                            Map createInvoiceItemAdjResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemAdjContext);
-                            if (ServiceUtil.isError(createInvoiceItemAdjResult)) {
-                                return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceItemFromOrder",locale), null, null, createInvoiceItemAdjResult);
-                            }
+                        Map<String, Object> createOrderAdjustmentBillingResult = dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
+                        if (ServiceUtil.isError(createOrderAdjustmentBillingResult)) {
+                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingOrderAdjustmentBillingFromOrder",locale), null, null, createOrderAdjustmentBillingContext);
+                        }
 
-                            // Create the OrderAdjustmentBilling record
-                            Map createOrderAdjustmentBillingContext = FastMap.newInstance();
-                            createOrderAdjustmentBillingContext.put("orderAdjustmentId", adj.getString("orderAdjustmentId"));
-                            createOrderAdjustmentBillingContext.put("invoiceId", invoiceId);
-                            createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                            createOrderAdjustmentBillingContext.put("amount", amount);
-                            createOrderAdjustmentBillingContext.put("userLogin", userLogin);
-
-                            Map createOrderAdjustmentBillingResult = dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
-                            if (ServiceUtil.isError(createOrderAdjustmentBillingResult)) {
-                                return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingOrderAdjustmentBillingFromOrder",locale), null, null, createOrderAdjustmentBillingContext);
-                            }
+                        // this adjustment amount
+                        BigDecimal thisAdjAmount = amount;
 
-                            // this adjustment amount
-                            BigDecimal thisAdjAmount = amount;
+                        // adjustments only apply to totals when they are not tax or shipping adjustments
+                        if (!"SALES_TAX".equals(adj.getString("orderAdjustmentTypeId")) &&
+                                !"SHIPPING_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) {
+                            // increment the invoice subtotal
+                            invoiceSubTotal = invoiceSubTotal.add(thisAdjAmount).setScale(100, ROUNDING);
 
-                            // adjustments only apply to totals when they are not tax or shipping adjustments
-                            if (!"SALES_TAX".equals(adj.getString("orderAdjustmentTypeId")) &&
-                                    !"SHIPPING_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) {
-                                // increment the invoice subtotal
-                                invoiceSubTotal = invoiceSubTotal.add(thisAdjAmount).setScale(100, rounding);
-
-                                // add to the ship amount only if it applies to this item
-                                if (shippingApplies) {
-                                    invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAdjAmount).setScale(invoiceTypeDecimals, rounding);
-                                }
+                            // add to the ship amount only if it applies to this item
+                            if (shippingApplies) {
+                                invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAdjAmount).setScale(invoiceTypeDecimals, ROUNDING);
                             }
-
-                            // increment the counter
-                            invoiceItemSeqNum++;
-                            invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
                         }
+
+                        // increment the counter
+                        invoiceItemSeqNum++;
+                        invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
                     }
                 }
             }
 
             // create header adjustments as line items -- always to tax/shipping last
-            Map shipAdjustments = new HashMap();
-            Map taxAdjustments = new HashMap();
+            Map<GenericValue, BigDecimal> shipAdjustments = FastMap.newInstance();
+            Map<GenericValue, BigDecimal> taxAdjustments = FastMap.newInstance();
 
-            List headerAdjustments = orh.getOrderHeaderAdjustments();
-            Iterator headerAdjIter = headerAdjustments.iterator();
-            while (headerAdjIter.hasNext()) {
-                GenericValue adj = (GenericValue) headerAdjIter.next();
+            List<GenericValue> headerAdjustments = orh.getOrderHeaderAdjustments();
+            for (GenericValue adj : headerAdjustments) {
 
                 // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced
                 BigDecimal adjAlreadyInvoicedAmount = null;
                 try {
-                    Map checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj));
-                    adjAlreadyInvoicedAmount = ((BigDecimal) checkResult.get("invoicedTotal")).setScale(invoiceTypeDecimals, rounding);
+                    Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj));
+                    adjAlreadyInvoicedAmount = ((BigDecimal) checkResult.get("invoicedTotal")).setScale(invoiceTypeDecimals, ROUNDING);
                 } catch (GenericServiceException e) {
                     String errMsg = UtilProperties.getMessage(resource, "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale);
                     Debug.logError(e, errMsg, module);
@@ -675,7 +657,7 @@
                 if (null == adj.get("amount")) { // JLR 17/4/7 : fix a bug coming from POS in case of use of a discount (on item(s) or sale, sale here) and a cash amount higher than total (hence issuing change)
                     continue;
                 }
-                if (adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, rounding).abs()) > 0) {
+                if (adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) {
                     continue;
                 }
 
@@ -687,7 +669,7 @@
                     // these will effect the shipping pro-rate (unless commented)
                     // other adjustment type
                     BigDecimal adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId,
-                            orderSubTotal, invoiceSubTotal, adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, rounding), invoiceTypeDecimals, rounding, userLogin, dispatcher, locale);
+                            orderSubTotal, invoiceSubTotal, adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING), invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
                     // invoiceShipProRateAmount += adjAmount;
                     // do adjustments compound or are they based off subtotal? Here we will (unless commented)
                     // invoiceSubTotal += adjAmount;
@@ -700,9 +682,7 @@
 
             // next do the shipping adjustments.  Note that we do not want to add these to the invoiceSubTotal or orderSubTotal for pro-rating tax later, as that would cause
             // numerator/denominator problems when the shipping is not pro-rated but rather charged all on the first invoice
-            Iterator shipAdjIter = shipAdjustments.keySet().iterator();
-            while (shipAdjIter.hasNext()) {
-                GenericValue adj = (GenericValue) shipAdjIter.next();
+            for (GenericValue adj : shipAdjustments.keySet()) {
                 BigDecimal adjAlreadyInvoicedAmount = (BigDecimal) shipAdjustments.get(adj);
 
                 if ("N".equalsIgnoreCase(prorateShipping)) {
@@ -713,9 +693,9 @@
 
                     // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since
                     //  it won't be prorated
-                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, rounding).subtract(adjAlreadyInvoicedAmount);
+                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).subtract(adjAlreadyInvoicedAmount);
                     BigDecimal adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId,
-                            divisor, multiplier, baseAmount, invoiceTypeDecimals, rounding, userLogin, dispatcher, locale);
+                            divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
                 } else {
 
                     // Pro-rate the shipping amount based on shippable information
@@ -723,9 +703,9 @@
                     BigDecimal multiplier = invoiceShipProRateAmount;
 
                     // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount
-                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, rounding);
+                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING);
                     BigDecimal adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId,
-                            divisor, multiplier, baseAmount, invoiceTypeDecimals, rounding, userLogin, dispatcher, locale);
+                            divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
                 }
 
                 // Increment the counter
@@ -738,9 +718,7 @@
             if (prorateTaxes == null) {
                 prorateTaxes = "Y";
             }
-            Iterator taxAdjIter = taxAdjustments.keySet().iterator();
-            while (taxAdjIter.hasNext()) {
-                GenericValue adj = (GenericValue) taxAdjIter.next();
+            for (GenericValue adj : taxAdjustments.keySet()) {
                 BigDecimal adjAlreadyInvoicedAmount = (BigDecimal) taxAdjustments.get(adj);
                 BigDecimal adjAmount = null;
 
@@ -753,9 +731,9 @@
                     // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since
                     //  it won't be prorated
                     //  Note this should use invoice decimals & rounding instead of taxDecimals and taxRounding for tax adjustments, because it will be added to the invoice
-                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, rounding).subtract(adjAlreadyInvoicedAmount);
+                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).subtract(adjAlreadyInvoicedAmount);
                     adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId,
-                             divisor, multiplier, baseAmount, invoiceTypeDecimals, rounding, userLogin, dispatcher, locale);
+                             divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
                 } else {
 
                     // Pro-rate the tax amount based on shippable information
@@ -764,11 +742,11 @@
 
                     // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount
                     //  Note this should use invoice decimals & rounding instead of taxDecimals and taxRounding for tax adjustments, because it will be added to the invoice
-                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, rounding);
+                    BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING);
                     adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId,
-                            divisor, multiplier, baseAmount, invoiceTypeDecimals, rounding, userLogin, dispatcher, locale);
+                            divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
                 }
-                invoiceSubTotal = invoiceSubTotal.add(adjAmount).setScale(invoiceTypeDecimals, rounding);
+                invoiceSubTotal = invoiceSubTotal.add(adjAmount).setScale(invoiceTypeDecimals, ROUNDING);
 
                 // Increment the counter
                 invoiceItemSeqNum++;
@@ -776,31 +754,25 @@
             }
 
             // check for previous order payments
-            List orderPaymentPrefs = delegator.findByAnd("OrderPaymentPreference", UtilMisc.toMap("orderId", orderId));
-            List currentPayments = FastList.newInstance();
-            Iterator opi = orderPaymentPrefs.iterator();
-            while (opi.hasNext()) {
-                GenericValue paymentPref = (GenericValue) opi.next();
-                List payments = paymentPref.getRelated("Payment");
+            List<GenericValue> orderPaymentPrefs = delegator.findByAnd("OrderPaymentPreference", UtilMisc.toMap("orderId", orderId));
+            List<GenericValue> currentPayments = FastList.newInstance();
+            for (GenericValue paymentPref : orderPaymentPrefs) {
+                List<GenericValue> payments = paymentPref.getRelated("Payment");
                 currentPayments.addAll(payments);
             }
-            if (currentPayments.size() > 0) {
-                // apply these payments to the invoice if they have any remaining amount to apply
-                Iterator cpi = currentPayments.iterator();
-                while (cpi.hasNext()) {
-                    GenericValue payment = (GenericValue) cpi.next();
-                    BigDecimal notApplied = PaymentWorker.getPaymentNotApplied(payment);
-                    if (notApplied.signum() > 0) {
-                        Map appl = new HashMap();
-                        appl.put("paymentId", payment.get("paymentId"));
-                        appl.put("invoiceId", invoiceId);
-                        appl.put("billingAccountId", billingAccountId);
-                        appl.put("amountApplied", notApplied);
-                        appl.put("userLogin", userLogin);
-                        Map createPayApplResult = dispatcher.runSync("createPaymentApplication", appl);
-                        if (ServiceUtil.isError(createPayApplResult)) {
-                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceFromOrder",locale), null, null, createPayApplResult);
-                        }
+            // apply these payments to the invoice if they have any remaining amount to apply
+            for (GenericValue payment : currentPayments) {
+                BigDecimal notApplied = PaymentWorker.getPaymentNotApplied(payment);
+                if (notApplied.signum() > 0) {
+                    Map<String, Object> appl = FastMap.newInstance();
+                    appl.put("paymentId", payment.get("paymentId"));
+                    appl.put("invoiceId", invoiceId);
+                    appl.put("billingAccountId", billingAccountId);
+                    appl.put("amountApplied", notApplied);
+                    appl.put("userLogin", userLogin);
+                    Map<String, Object> createPayApplResult = dispatcher.runSync("createPaymentApplication", appl);
+                    if (ServiceUtil.isError(createPayApplResult)) {
+                        return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceFromOrder",locale), null, null, createPayApplResult);
                     }
                 }
             }
@@ -809,50 +781,50 @@
             String autoApproveInvoice = productStore != null ? productStore.getString("autoApproveInvoice") : "Y";
             if (!"N".equals(autoApproveInvoice)) {
                 String nextStatusId = "PURCHASE_INVOICE".equals(invoiceType) ? "INVOICE_IN_PROCESS" : "INVOICE_READY";
-                Map setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
+                Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
                 if (ServiceUtil.isError(setInvoiceStatusResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingErrorCreatingInvoiceFromOrder",locale), null, null, setInvoiceStatusResult);
                 }
             }
 
-            Map resp = ServiceUtil.returnSuccess();
+            Map<String, Object> resp = ServiceUtil.returnSuccess();
             resp.put("invoiceId", invoiceId);
             resp.put("invoiceTypeId", invoiceType);
             return resp;
         } catch (GenericEntityException e) {
-            String errMsg = UtilProperties.getMessage(resource,"AccountingEntityDataProblemCreatingInvoiceFromOrderItems",UtilMisc.toMap("reason",e.toString()),locale);
+            String errMsg = UtilProperties.getMessage(resource, "AccountingEntityDataProblemCreatingInvoiceFromOrderItems", UtilMisc.toMap("reason", e.toString()), locale);
             Debug.logError(e, errMsg, module);
             return ServiceUtil.returnError(errMsg);
         } catch (GenericServiceException e) {
-            String errMsg = UtilProperties.getMessage(resource,"AccountingServiceOtherProblemCreatingInvoiceFromOrderItems",UtilMisc.toMap("reason",e.toString()),locale);
+            String errMsg = UtilProperties.getMessage(resource, "AccountingServiceOtherProblemCreatingInvoiceFromOrderItems", UtilMisc.toMap("reason", e.toString()), locale);
             Debug.logError(e, errMsg, module);
             return ServiceUtil.returnError(errMsg);
         }
     }
 
     // Service for creating commission invoices
-    public static Map createCommissionInvoices(DispatchContext dctx, Map context) {
+    public static Map<String, Object> createCommissionInvoices(DispatchContext dctx, Map<String, Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
-        List<String> salesInvoiceIds = (List) context.get("invoiceIds");
-        List<Map> invoicesCreated = FastList.newInstance();
-        Map commissionParties = FastMap.newInstance();
+        List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds"));
+        List<Map<String, String>> invoicesCreated = FastList.newInstance();
+        Map<String, List<Map<String, Object>>> commissionParties = FastMap.newInstance();
         for (String salesInvoiceId : salesInvoiceIds) {
-            List<String> salesRepPartyIds = (List) context.get("partyIds");
+            List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds"));
             BigDecimal amountTotal =  InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId);
             if (amountTotal.signum() == 0) {
                 Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal + "], so no commission invoice will be created", module);
                 return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingInvoiceCommissionZeroInvoiceAmount",locale));
             }
-            BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, rounding);
+            BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING);
             GenericValue invoice = null;
             boolean isReturn = false;
             List<String> billFromVendorInvoiceRoles = new ArrayList<String>();
             List<GenericValue> invoiceItems = new ArrayList<GenericValue>();
             try {
-                List invoiceRoleConds = UtilMisc.toList(
+                List<EntityExpr> invoiceRoleConds = UtilMisc.toList(
                         EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId),
                         EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR"));
                 billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(delegator.findList("InvoiceRole", EntityCondition.makeCondition(invoiceRoleConds, EntityOperator.AND), null, null, null, false), "partyId", true);
@@ -868,7 +840,7 @@
                 } else {
                     List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(delegator.findList("InvoiceRole", EntityCondition.makeCondition(invoiceRoleConds, EntityOperator.AND), null, null, null, false), "partyId", true);
                     if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) {
-                        salesRepPartyIds = (List) CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds);
+                        salesRepPartyIds = UtilGenerics.checkList(CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds));
                     } 
                 }
                 invoice = delegator.findOne("Invoice", UtilMisc.toMap("invoiceId", salesInvoiceId), false);
@@ -896,7 +868,7 @@
                 String invoiceId = invoiceItem.getString("invoiceId");
                 // Determine commission parties for this invoiceItem
                 if (productId != null && productId.length() > 0) {
-                    Map resultMap = null;
+                    Map<String, Object> resultMap = null;
                     try {
                         resultMap = dispatcher.runSync("getCommissionForProduct", UtilMisc.<String, Object>toMap(
                                 "productId", productId,
@@ -911,9 +883,9 @@
                     }
                     // build a Map of partyIds (both to and from) in a commission and the amounts
                     // Note that getCommissionForProduct returns a List of Maps with a lot values.  See services.xml definition for reference.
-                    List<Map> itemCommissions = (List) resultMap.get("commissions");
+                    List<Map<String, Object>> itemCommissions = UtilGenerics.checkList(resultMap.get("commissions"));
                     if (UtilValidate.isNotEmpty(itemCommissions)) {
-                        for (Map commissionMap : itemCommissions) {
+                        for (Map<String, Object> commissionMap : itemCommissions) {
                             commissionMap.put("invoice", invoice);
                             commissionMap.put("appliedFraction", appliedFraction);
                             if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom")) || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) {
@@ -923,7 +895,7 @@
                             if (!commissionParties.containsKey(partyIdFromTo)) {
                                 commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap));
                             } else {
-                                ((List)commissionParties.get(partyIdFromTo)).add(commissionMap);
+                                (commissionParties.get(partyIdFromTo)).add(commissionMap);
                             }
                         }
                     }
@@ -932,10 +904,9 @@
         }
         Timestamp now = UtilDateTime.nowTimestamp();
         // Create invoice for each commission receiving party
-        for (Object commissionParty : commissionParties.entrySet()) {
-            Map.Entry pair = (Map.Entry)commissionParty;
-            List toStore = FastList.newInstance();
-            List<Map> commList = (List)pair.getValue();
+        for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) {
+            List<GenericValue> toStore = FastList.newInstance();
+            List<Map<String, Object>> commList = commissionParty.getValue();
             // get the billing parties
             if (UtilValidate.isEmpty(commList)) {
                 continue;
@@ -948,7 +919,7 @@
             Long days = (Long) (commList.get(0)).get("days");
             // create the invoice record
             // To and From are in commission's sense, opposite for invoice
-            Map createInvoiceMap = FastMap.newInstance();
+            Map<String, Object> createInvoiceMap = FastMap.newInstance();
             createInvoiceMap.put("partyId", partyIdBillTo);
             createInvoiceMap.put("partyIdFrom", partyIdBillFrom);
             createInvoiceMap.put("invoiceDate", now);
@@ -962,7 +933,7 @@
             createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId"));
             createInvoiceMap.put("userLogin", userLogin);
             // store the invoice first
-            Map createInvoiceResult = null;
+            Map<String, Object> createInvoiceResult = null;
             try {
                 createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap);
             } catch (GenericServiceException e) {
@@ -970,7 +941,7 @@
             }
             String invoiceId = (String) createInvoiceResult.get("invoiceId");
             // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store
-            List partyContactMechPurposeConds = UtilMisc.toList(
+            List<EntityExpr> partyContactMechPurposeConds = UtilMisc.toList(
                     EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyIdBillTo),
                     EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.EQUALS, "BILLING_LOCATION"));
             List<GenericValue> partyContactMechPurposes = new ArrayList<GenericValue>();
@@ -1006,14 +977,14 @@
                 toStore.add(invoiceContactMech);
             }
             // create the item records
-            for (Map commissionMap : commList) {
+            for (Map<String, Object> commissionMap : commList) {
                 BigDecimal elemAmount = ((BigDecimal)commissionMap.get("commission")).multiply(appliedFraction);
                 BigDecimal quantity = (BigDecimal)commissionMap.get("quantity");
                 String invoiceIdFrom = (String)commissionMap.get("invoiceId");
                 String invoiceItemSeqIdFrom = (String)commissionMap.get("invoiceItemSeqId");
-                elemAmount = elemAmount.setScale(decimals, rounding);
-                Map resMap = null;
-                Map invoiceItemAssocResultMap = null;
+                elemAmount = elemAmount.setScale(DECIMALS, ROUNDING);
+                Map<String, Object> resMap = null;
+                Map<String, Object> invoiceItemAssocResultMap = null;
                 try {
                     resMap = dispatcher.runSync("createInvoiceItem", UtilMisc.toMap(
                             "invoiceId", invoiceId,
@@ -1051,24 +1022,22 @@
             }
             invoicesCreated.add(UtilMisc.toMap("commissionInvoiceId",invoiceId, "salesRepresentative ",partyIdBillFrom));
         }
-        Map result = ServiceUtil.returnSuccess("Created Commission invoices for each commission receiving parties " + invoicesCreated);
+        Map<String, Object> result = ServiceUtil.returnSuccess("Created Commission invoices for each commission receiving parties " + invoicesCreated);
         Debug.logInfo("Created Commission invoices for each commission receiving parties " + invoicesCreated, module);
         result.put("invoicesCreated", invoicesCreated);
         return result;
     }
 
-    public static Map readyInvoices(DispatchContext dctx, Map context) {
+    public static Map<String, Object> readyInvoices(DispatchContext dctx, Map<String, Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
         // Get invoices to make ready
-        List invoicesCreated = (List) context.get("invoicesCreated");
+        List<String> invoicesCreated = UtilGenerics.checkList(context.get("invoicesCreated"));
         String nextStatusId = "INVOICE_READY";
-        Iterator it = invoicesCreated.iterator();
         try {
-            while (it.hasNext()) {
-                String invoiceId = (String) it.next();
-                Map setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
+            for (String invoiceId : invoicesCreated) {
+                Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
                 if (ServiceUtil.isError(setInvoiceStatusResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingInvoiceCommissionError",locale), null, null, setInvoiceStatusResult);
                 }
@@ -1081,27 +1050,27 @@
         return ServiceUtil.returnSuccess();
     }
 
-    public static Map createInvoicesFromShipment(DispatchContext dctx, Map context) {
+    public static Map<String, Object> createInvoicesFromShipment(DispatchContext dctx, Map<String, Object> context) {
         //GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         String shipmentId = (String) context.get("shipmentId");
         Locale locale = (Locale) context.get("locale");
-        List invoicesCreated = new ArrayList();
+        List<String> invoicesCreated = FastList.newInstance();
 
-        Map serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "eventDate", context.get("eventDate"), "userLogin", context.get("userLogin"));
+        Map<String, Object> serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "eventDate", context.get("eventDate"), "userLogin", context.get("userLogin"));
         try {
-            Map result = dispatcher.runSync("createInvoicesFromShipments", serviceContext);
-            invoicesCreated = (List) result.get("invoicesCreated");
+            Map<String, Object> result = dispatcher.runSync("createInvoicesFromShipments", serviceContext);
+            invoicesCreated = UtilGenerics.checkList(result.get("invoicesCreated"));
         } catch (GenericServiceException e) {
             Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment [" + shipmentId + "]", module);
             return ServiceUtil.returnError(UtilProperties.getMessage(resource,"AccountingTroubleCallingCreateInvoicesFromShipmentService",UtilMisc.toMap("shipmentId",shipmentId),locale));
         }
-        Map response = ServiceUtil.returnSuccess();
+        Map<String, Object> response = ServiceUtil.returnSuccess();
         response.put("invoicesCreated", invoicesCreated);
         return response;
     }
 
-    public static Map setInvoicesToReadyFromShipment(DispatchContext dctx, Map context) {
+    public static Map<String, Object> setInvoicesToReadyFromShipment(DispatchContext dctx, Map<String, Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         String shipmentId = (String) context.get("shipmentId");
@@ -1139,14 +1108,14 @@
         // The orders can now be placed in separate groups, each for
         // 1. The group of orders for which payment is already captured. No grouping and action required. 
         // 2. The group of orders for which invoice is IN-Process status.
-        Map ordersWithInProcessInvoice = FastMap.newInstance();
+        Map<String, Object> ordersWithInProcessInvoice = FastMap.newInstance();
 
         for (GenericValue itemIssuance : itemIssuances) {
             String orderId = itemIssuance.getString("orderId");
-            Map billFields = FastMap.newInstance();
+            Map<String, Object> billFields = FastMap.newInstance();
             billFields.put("orderId", orderId);
 
-            List orderItemBillings = FastList.newInstance();
+            List<GenericValue> orderItemBillings = FastList.newInstance();
             try {
                 orderItemBillings = delegator.findByAnd("OrderItemBilling", billFields);
             } catch (GenericEntityException e) {
@@ -1174,13 +1143,11 @@
         }
 
      // For In-Process invoice, move the status to ready and capture the payment
-        Set invoicesInProcess = ordersWithInProcessInvoice.keySet();
-        Iterator iter = invoicesInProcess.iterator();
-        while (iter.hasNext()) {
-            String orderId = (String) iter.next();
+        Set<String> invoicesInProcess = ordersWithInProcessInvoice.keySet();
+        for (String orderId : invoicesInProcess) {
             GenericValue invoice = (GenericValue) ordersWithInProcessInvoice.get(orderId);
             String invoiceId = invoice.getString("invoiceId");
-            Map setInvoiceStatusResult = FastMap.newInstance();
+            Map<String, Object> setInvoiceStatusResult = FastMap.newInstance();
             try {
                 setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", "INVOICE_READY", "userLogin", userLogin));
             } catch (GenericServiceException e) {
@@ -1194,14 +1161,14 @@
         return ServiceUtil.returnSuccess();
     }
 
-    public static Map createSalesInvoicesFromDropShipment(DispatchContext dctx, Map context) {
+    public static Map<String, Object> createSalesInvoicesFromDropShipment(DispatchContext dctx, Map<String, Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         String shipmentId = (String) context.get("shipmentId");
         Locale locale = (Locale) context.get("locale");
 
-        Map serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "createSalesInvoicesForDropShipments", Boolean.TRUE, "userLogin", context.get("userLogin"));
+        Map<String, Object> serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "createSalesInvoicesForDropShipments", Boolean.TRUE, "userLogin", context.get("userLogin"));
 
-        Map serviceResult;
+        Map<String, Object> serviceResult;
         try {
             serviceResult = dispatcher.runSync("createInvoicesFromShipments", serviceContext);
         } catch (GenericServiceException e) {
@@ -1213,10 +1180,10 @@
         return serviceResult;
     }
 
-    public static Map createInvoicesFromShipments(DispatchContext dctx, Map context) {
+    public static Map<String, Object> createInvoicesFromShipments(DispatchContext dctx, Map context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        List shipmentIds = (List) context.get("shipmentIds");
+        List<String> shipmentIds = UtilGenerics.checkList(context.get("shipmentIds"));
         Locale locale = (Locale) context.get("locale");
         Boolean createSalesInvoicesForDropShipments = (Boolean) context.get("createSalesInvoicesForDropShipments");
         if (UtilValidate.isEmpty(createSalesInvoicesForDropShipments)) createSalesInvoicesForDropShipments = Boolean.FALSE;
@@ -1225,11 +1192,10 @@
         boolean purchaseShipmentFound = false;
         boolean dropShipmentFound = false;
 
-        List invoicesCreated = new ArrayList();
+        List<String> invoicesCreated = FastList.newInstance();
 
         //DEJ20060520: not used? planned to be used? List shipmentIdList = new LinkedList();
-        for (int i = 0; i < shipmentIds.size(); i++) {
-            String tmpShipmentId = (String)shipmentIds.get(i);
+        for (String tmpShipmentId : shipmentIds) {
             try {
                 GenericValue shipment = delegator.findByPrimaryKey("Shipment", UtilMisc.toMap("shipmentId", tmpShipmentId));
                 if ((shipment.getString("shipmentTypeId") != null) && (shipment.getString("shipmentTypeId").equals("PURCHASE_SHIPMENT"))) {
@@ -1253,13 +1219,13 @@
 
         // get the items of the shipment.  They can come from ItemIssuance if the shipment were from a sales order, ShipmentReceipt
         // if it were a purchase order or from the order items of the (possibly linked) orders if the shipment is a drop shipment
-        List items = null;
-        List orderItemAssocs = null;
+        List<GenericValue> items = null;
+        List<GenericValue> orderItemAssocs = null;
         try {
             if (purchaseShipmentFound) {
                 items = delegator.findList("ShipmentReceipt", shipmentIdsCond, null, UtilMisc.toList("shipmentId"), null, false);
                 // filter out items which have been received but are not actually owned by an internal organization, so they should not be on a purchase invoice
-                Iterator itemsIter = items.iterator();
+                Iterator<GenericValue> itemsIter = items.iterator();
                 while (itemsIter.hasNext()) {
                     GenericValue item = (GenericValue) itemsIter.next();
                     GenericValue inventoryItem = item.getRelatedOne("InventoryItem");
@@ -1270,10 +1236,10 @@
                 }
             } else if (dropShipmentFound) {
 
-                List shipments = delegator.findList("Shipment", shipmentIdsCond, null, null, null, false);
+                List<GenericValue> shipments = delegator.findList("Shipment", shipmentIdsCond, null, null, null, false);
 
                 // Get the list of purchase order IDs related to the shipments
-                List purchaseOrderIds = EntityUtil.getFieldListFromEntityList(shipments, "primaryOrderId", true);

[... 1078 lines stripped ...]