[OFBiz] SVN: r6136 - in trunk/applications: accounting/script/org/ofbiz/accounting/tax accounting/servicedef accounting/src/org/ofbiz/accounting accounting/src/org/ofbiz/accounting/tax ecommerce/data order/script/org/ofbiz/order/order order/servicedef order/src/org/ofbiz/order/order

jonesde at svn.ofbiz.org jonesde at svn.ofbiz.org
Thu Nov 17 03:09:21 EST 2005


Author: jonesde
Date: 2005-11-17 02:09:01 -0600 (Thu, 17 Nov 2005)
New Revision: 6136

Added:
   trunk/applications/accounting/script/org/ofbiz/accounting/tax/TaxRateServices.xml
   trunk/applications/accounting/src/org/ofbiz/accounting/tax/
   trunk/applications/accounting/src/org/ofbiz/accounting/tax/SimpleTaxServices.java
   trunk/applications/accounting/src/org/ofbiz/accounting/tax/TaxAuthorityServices.java
Removed:
   trunk/applications/order/script/org/ofbiz/order/order/TaxRateServices.xml
Modified:
   trunk/applications/accounting/servicedef/services_tax.xml
   trunk/applications/ecommerce/data/DemoProduct.xml
   trunk/applications/ecommerce/data/DemoTaxAuthority.xml
   trunk/applications/order/servicedef/services.xml
   trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java
Log:
Some reorganization and cleanup of tax stuff, started coding of tax authority based tax calc services for the order and for the price with tax included display, still a fair amount of work to do on those new ones

Copied: trunk/applications/accounting/script/org/ofbiz/accounting/tax/TaxRateServices.xml (from rev 6134, trunk/applications/order/script/org/ofbiz/order/order/TaxRateServices.xml)

Modified: trunk/applications/accounting/servicedef/services_tax.xml
===================================================================
--- trunk/applications/accounting/servicedef/services_tax.xml	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/accounting/servicedef/services_tax.xml	2005-11-17 08:09:01 UTC (rev 6136)
@@ -27,6 +27,44 @@
     <vendor>OFBiz</vendor>
     <version>1.0</version>
     
+    <!-- Tax Calc Interfaces -->
+    <service name="calcTaxInterface" engine="interface" location="" invoke="">
+        <description>Tax Calc Service Interface</description>
+        <attribute name="productStoreId" type="String" mode="IN"/>
+        <attribute name="billToPartyId" type="String" mode="IN" optional="true"/> <!-- would like to have this not-optional, but in some circumstances may need a tax estimate without knowing who the customer is -->
+        <attribute name="itemProductList" type="java.util.List" mode="IN"/>
+        <attribute name="itemAmountList" type="java.util.List" mode="IN"/>
+        <attribute name="itemPriceList" type="java.util.List" mode="IN"/>
+        <attribute name="itemShippingList" type="java.util.List" mode="IN" optional="true"/>
+        <attribute name="orderShippingAmount" type="Double" mode="IN" optional="true"/>
+        <attribute name="shippingAddress" type="org.ofbiz.entity.GenericValue" mode="IN" optional="true"/>
+        <attribute name="orderAdjustments" type="java.util.List" mode="OUT"/>
+        <attribute name="itemAdjustments" type="java.util.List" mode="OUT"/>
+    </service>
+    <service name="calcTaxTotalForDisplayInterface" engine="interface" location="" invoke="">
+        <description>Tax Calc Total For Display Service Interface</description>
+        <attribute name="productStoreId" type="String" mode="IN" optional="false"><!-- this will be used to get the taxAuthPartyId and taxAuthGeoId to use for the rate lookup --></attribute> 
+        <attribute name="billToPartyId" type="String" mode="IN" optional="true"/> <!-- would like to have this not-optional, but in some circumstances may need a tax estimate without knowing who the customer is -->
+        <attribute name="productId" type="String" mode="IN"/>
+        <attribute name="amount" type="Long" mode="IN"/>
+        <attribute name="basePrice" type="Double" mode="IN"/>
+        <attribute name="shippingPrice" type="Double" mode="IN" optional="true"/>
+        <attribute name="taxTotal" type="Double" mode="OUT"/>
+        <attribute name="priceWithTax" type="Double" mode="OUT"/>
+    </service>
+    
+    <!-- Tax Authority Calc Services -->
+    <service name="rateProductTaxCalc" engine="java"
+        location="org.ofbiz.accounting.tax.TaxAuthorityServices" invoke="rateProductTaxCalc">
+        <description>Tax Authority Rate Product Calc Service</description>
+        <implements service="calcTaxInterface"/>
+    </service>
+    <service name="rateProductTaxCalcForDisplay" engine="java"
+        location="org.ofbiz.accounting.tax.TaxAuthorityServices" invoke="rateProductTaxCalcForDisplay">
+        <description>Tax Authority Rate Product Calc Service</description>
+        <implements service="calcTaxTotalForDisplayInterface"/>
+    </service>
+    
     <!-- TaxAuthority -->
     <service name="createTaxAuthority" default-entity-name="TaxAuthority" engine="simple" auth="true"
         location="org/ofbiz/accounting/tax/TaxAuthorityServices.xml" invoke="createTaxAuthority">
@@ -142,4 +180,52 @@
         <auto-attributes include="pk" mode="IN" optional="false"/>
         <auto-attributes include="nonpk" mode="IN" optional="true"/>
     </service>
+
+    <!-- Simple Tax Rate Services (SimpleSalesTaxLookup) -->
+    <service name="calcTax" engine="java"
+        location="org.ofbiz.accounting.tax.SimpleTaxServices" invoke="simpleTaxCalc">
+        <description>Simple Calc Tax Service</description>
+        <implements service="calcTaxInterface"/>
+    </service>
+    
+    <service name="createTaxRate" engine="simple"
+        location="org/ofbiz/accounting/tax/TaxRateServices.xml" invoke="createTaxRate">
+        <description>Create a Tax Rate entry</description>
+        <attribute name="productStoreId" type="String" mode="IN" optional="false"/>
+        <attribute name="countryGeoId" type="String" mode="IN" optional="false"/>
+        <attribute name="stateProvinceGeoId" type="String" mode="IN" optional="false"/>
+        <attribute name="taxCategory" type="String" mode="IN" optional="true"/>
+        <attribute name="taxShipping" type="String" mode="IN" optional="false"/>
+        <attribute name="minItemPrice" type="Double" mode="IN" optional="false"/>
+        <attribute name="minPurchase" type="Double" mode="IN" optional="false"/>
+        <attribute name="description" type="String" mode="IN" optional="true"/>
+        <attribute name="salesTaxPercentage" type="Double" mode="IN" optional="false"/>
+        <attribute name="fromDate" type="Timestamp" mode="IN" optional="true"/>
+        <attribute name="thruDate" type="Timestamp" mode="IN" optional="true"/>
+    </service>
+    <service name="removeTaxRate" engine="simple"
+        location="org/ofbiz/accounting/tax/TaxRateServices.xml" invoke="removeTaxRate">
+        <description>Remove a Tax Rate entry</description>
+        <attribute name="productStoreId" type="String" mode="IN" optional="false"/>
+        <attribute name="countryGeoId" type="String" mode="IN" optional="false"/>
+        <attribute name="stateProvinceGeoId" type="String" mode="IN" optional="false"/>
+        <attribute name="taxCategory" type="String" mode="IN" optional="false"/>
+        <attribute name="minItemPrice" type="Double" mode="IN" optional="false"/>
+        <attribute name="minPurchase" type="Double" mode="IN" optional="false"/>
+        <attribute name="fromDate" type="Timestamp" mode="IN" optional="false"/>
+    </service>
+    
+    <!-- ZipSales Tax Services -->
+    <service name="importZipSalesTaxData" engine="java" transaction-timout="7200"
+        location="org.ofbiz.order.thirdparty.zipsales.ZipSalesServices" invoke="importFlatTable">
+        <description>Import ZipSales Flat File</description>
+        <attribute name="taxFileLocation" type="String" mode="IN" optional="false"/>
+        <attribute name="ruleFileLocation" type="String" mode="IN" optional="false"/>
+    </service>
+    
+    <service name="_calcTax" engine="java"
+        location="org.ofbiz.order.thirdparty.zipsales.ZipSalesServices" invoke="flatTaxCalc">
+        <description>Zip Sales Calc Tax Service - change this to calcTax to run</description>
+        <implements service="calcTaxInterface"/>
+    </service>
 </services>

Added: trunk/applications/accounting/src/org/ofbiz/accounting/tax/SimpleTaxServices.java
===================================================================
--- trunk/applications/accounting/src/org/ofbiz/accounting/tax/SimpleTaxServices.java	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/accounting/src/org/ofbiz/accounting/tax/SimpleTaxServices.java	2005-11-17 08:09:01 UTC (rev 6136)
@@ -0,0 +1,267 @@
+/*
+ * $Id: OrderServices.java 6133 2005-11-17 03:56:16Z jaz $
+ *
+ *  Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
+ *
+ *  Permission is hereby granted, free of charge, to any person obtaining a
+ *  copy of this software and associated documentation files (the "Software"),
+ *  to deal in the Software without restriction, including without limitation
+ *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ *  and/or sell copies of the Software, and to permit persons to whom the
+ *  Software is furnished to do so, subject to the following conditions:
+ *
+ *  The above copyright notice and this permission notice shall be included
+ *  in all copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ *  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
+ *  OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
+ *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+package org.ofbiz.accounting.tax;
+
+import java.sql.Timestamp;
+import java.text.DecimalFormat;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javolution.util.FastSet;
+
+import org.ofbiz.base.util.Debug;
+import org.ofbiz.base.util.GeneralException;
+import org.ofbiz.base.util.UtilDateTime;
+import org.ofbiz.base.util.UtilMisc;
+import org.ofbiz.base.util.UtilProperties;
+import org.ofbiz.base.util.UtilValidate;
+import org.ofbiz.entity.GenericDelegator;
+import org.ofbiz.entity.GenericEntityException;
+import org.ofbiz.entity.GenericValue;
+import org.ofbiz.entity.condition.EntityCondition;
+import org.ofbiz.entity.condition.EntityConditionList;
+import org.ofbiz.entity.condition.EntityExpr;
+import org.ofbiz.entity.condition.EntityOperator;
+import org.ofbiz.entity.util.EntityUtil;
+import org.ofbiz.service.DispatchContext;
+
+/**
+ * Order Processing Services
+ *
+ * @author     <a href="mailto:jaz at ofbiz.org">Andy Zeneski</a>
+ * @author     <a href="mailto:jonesde at ofbiz.org">David E. Jones</a>
+ * @version    $Rev$
+ * @since      2.0
+ */
+
+public class SimpleTaxServices {
+
+    public static final String module = SimpleTaxServices.class.getName();
+
+    /** Null tax calc service. */
+    public static Map nullTaxCalc(DispatchContext dctx, Map context) {
+        return UtilMisc.toMap("orderAdjustments", UtilMisc.toList(null), "itemAdjustments", UtilMisc.toList(null));
+    }
+
+    /** Simple tax calc service. */
+    public static Map simpleTaxCalc(DispatchContext dctx, Map context) {
+        GenericDelegator delegator = dctx.getDelegator();
+        String productStoreId = (String) context.get("productStoreId");
+        String billToPartyId = (String) context.get("billToPartyId");
+        List itemProductList = (List) context.get("itemProductList");
+        List itemAmountList = (List) context.get("itemAmountList");
+        List itemPriceList = (List) context.get("itemPriceList");
+        List itemShippingList = (List) context.get("itemShippingList");
+        Double orderShippingAmount = (Double) context.get("orderShippingAmount");
+        GenericValue shippingAddress = (GenericValue) context.get("shippingAddress");
+        //GenericValue userLogin = (GenericValue) context.get("userLogin");
+        //Locale locale = (Locale) context.get("locale");
+
+        // Simple Tax Calc only uses the state from the address and the SalesTaxLookup entity.
+
+        String countryCode = null;
+        String stateCode = null;
+
+        if (shippingAddress != null) {
+            countryCode = shippingAddress.getString("countryGeoId");
+            stateCode = shippingAddress.getString("stateProvinceGeoId");
+        }
+
+        // Setup the return lists.
+        List orderAdjustments = new ArrayList();
+        List itemAdjustments = new ArrayList();
+
+        // Loop through the products; get the taxCategory; and lookup each in the cache.
+        for (int i = 0; i < itemProductList.size(); i++) {
+            GenericValue product = (GenericValue) itemProductList.get(i);
+            Double itemAmount = (Double) itemAmountList.get(i);
+            Double itemPrice = (Double) itemPriceList.get(i);
+            Double shippingAmount = (Double) itemShippingList.get(i);
+            List taxList = null;
+            if (shippingAddress != null) {
+                taxList = getTaxAmount(delegator, product, productStoreId, billToPartyId, countryCode, stateCode, itemPrice.doubleValue(), itemAmount.doubleValue(), shippingAmount.doubleValue());
+            }
+            itemAdjustments.add(taxList);
+        }
+        if (orderShippingAmount.doubleValue() > 0) {
+            List taxList = getTaxAmount(delegator, null, productStoreId, billToPartyId, countryCode, stateCode, 0.00, 0.00, orderShippingAmount.doubleValue());
+            orderAdjustments.addAll(taxList);
+        }
+
+        Map result = UtilMisc.toMap("orderAdjustments", orderAdjustments, "itemAdjustments", itemAdjustments);
+
+        return result;
+    }
+
+    private static List getTaxAmount(GenericDelegator delegator, GenericValue item, String productStoreId, String billToPartyId, String countryCode, String stateCode, double itemPrice, double itemAmount, double shippingAmount) {
+        Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
+        List adjustments = new ArrayList();
+
+        // store expr
+        EntityCondition storeCond = new EntityExpr("productStoreId", EntityOperator.EQUALS, productStoreId);
+
+        // build the country expressions
+        List countryExprs = UtilMisc.toList(new EntityExpr("countryGeoId", EntityOperator.EQUALS, countryCode), new EntityExpr("countryGeoId", EntityOperator.EQUALS, "_NA_"));
+        EntityCondition countryCond = new EntityConditionList(countryExprs, EntityOperator.OR);
+
+        // build the state expression
+        List stateExprs = UtilMisc.toList(new EntityExpr("stateProvinceGeoId", EntityOperator.EQUALS, stateCode), new EntityExpr("stateProvinceGeoId", EntityOperator.EQUALS, "_NA_"));
+        EntityCondition stateCond = new EntityConditionList(stateExprs, EntityOperator.OR);
+
+        // build the tax cat expression
+        List taxCatExprs = UtilMisc.toList(new EntityExpr("taxCategory", EntityOperator.EQUALS, "_NA_"));
+        if (item != null && item.get("taxCategory") != null) {
+            taxCatExprs.add(new EntityExpr("taxCategory", EntityOperator.EQUALS, item.getString("taxCategory")));
+        }
+        EntityCondition taxCatCond = new EntityConditionList(taxCatExprs, EntityOperator.OR);
+
+        // build the main condition clause
+        List mainExprs = UtilMisc.toList(storeCond, countryCond, stateCond);
+        if (taxCatExprs.size() > 1) {
+            mainExprs.add(taxCatCond);
+        } else {
+            mainExprs.add(taxCatExprs.get(0));
+        }
+        EntityCondition mainCondition = new EntityConditionList(mainExprs, EntityOperator.AND);
+
+        // create the orderby clause
+        List orderList = UtilMisc.toList("minItemPrice", "minPurchase", "fromDate");
+
+        try {
+            List lookupList = delegator.findByCondition("SimpleSalesTaxLookup", mainCondition, null, orderList);
+            List filteredList = EntityUtil.filterByDate(lookupList);
+
+            if (filteredList.size() == 0) {
+                Debug.logWarning("SimpleTaxCalc: No State/TaxCategory pair found (with or without taxCat).", module);
+                return adjustments;
+            }
+
+            // find the right entry(s) based on purchase amount
+            Iterator flIt = filteredList.iterator();
+            while (flIt.hasNext()) {
+                GenericValue taxLookup = (GenericValue) flIt.next();
+                double minPrice = taxLookup.get("minItemPrice") != null ? taxLookup.getDouble("minItemPrice").doubleValue() : 0.00;
+                double minAmount = taxLookup.get("minPurchase") != null ? taxLookup.getDouble("minPurchase").doubleValue() : 0.00;
+
+                // DEJ20050528 not sure why this is done like this, could put this condition in the query sent to the database, though perhaps it is this way because of issues with that of some sort?
+                if (itemPrice >= minPrice && itemAmount >= minAmount) {
+                    double taxRate = taxLookup.get("salesTaxPercentage") != null ? taxLookup.getDouble("salesTaxPercentage").doubleValue() : 0;
+                    double taxable = 0.00;
+
+                    if (item != null && (item.get("taxable") == null || (item.get("taxable") != null && item.getBoolean("taxable").booleanValue()))) {
+                        taxable += itemAmount;
+                    }
+                    if (taxLookup != null && (taxLookup.get("taxShipping") == null || (taxLookup.get("taxShipping") != null && taxLookup.getBoolean("taxShipping").booleanValue()))) {
+                        taxable += shippingAmount;
+                    }
+
+                    // TODO: DEJ20050528 this is an interesting way to round the number, according to the JavaDoc
+                    //this uses the "ROUND_HALF_EVEN" method (as defined in the BigDecimal class, see JavaDoc
+                    //of that for details); it seems we might want to use the ROUND_HALF_UP method...
+                    String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00");
+                    DecimalFormat formatter = new DecimalFormat(currencyFormat);
+                    double taxTotal = taxable * taxRate;
+                    String amountStr = formatter.format(taxTotal);
+                    Double taxAmount = null;
+                    try {
+                        taxAmount = new Double(formatter.parse(amountStr).doubleValue());
+                    } catch (ParseException e) {
+                        throw new GeneralException("Problem getting parsed amount from string", e);
+                    }
+
+                    String primaryGeoId = taxLookup.getString("stateProvinceGeoId");
+                    String secondaryGeoId = taxLookup.getString("countryGeoId");
+                    String taxAuthPartyId = taxLookup.getString("taxAuthPartyId");
+                    String taxAuthGlAccountId = taxLookup.getString("taxAuthGlAccountId");
+
+                    // if no state/province, the country is the primary
+                    if (primaryGeoId == null || "_NA_".equals(primaryGeoId)) {
+                        primaryGeoId = secondaryGeoId;
+                        secondaryGeoId = null;
+                    }
+
+                    Map adjMap = new HashMap();
+                    adjMap.put("amount", taxAmount);
+                    adjMap.put("sourcePercentage", new Double(taxRate));
+                    adjMap.put("orderAdjustmentTypeId", "SALES_TAX");
+                    // the primary Geo should be the main jurisdiction that the tax is for, and the secondary would just be to define a parent or wrapping jurisdiction of the primary
+                    adjMap.put("primaryGeoId", primaryGeoId);
+                    if (secondaryGeoId != null) adjMap.put("secondaryGeoId", secondaryGeoId);
+                    adjMap.put("comments", taxLookup.getString("description"));
+                    if (taxAuthPartyId != null) adjMap.put("taxAuthPartyId", taxAuthPartyId);
+                    if (taxAuthGlAccountId != null) adjMap.put("overrideGlAccountId", taxAuthGlAccountId);
+                    if (primaryGeoId != null) adjMap.put("taxAuthGeoId", primaryGeoId);
+
+                    // check to see if this party has a tax ID for this, and if the party is tax exempt in the primary (most-local) jurisdiction
+                    if (UtilValidate.isNotEmpty(billToPartyId) && primaryGeoId != null) {
+                        // see if partyId is a member of any groups , if so honor their tax exemptions
+                        // look for PartyRelationship with partyRelationshipTypeId=GROUP_ROLLUP, the partyIdTo is the group member, so the partyIdFrom is the groupPartyId
+                        Set billToPartyIdSet = FastSet.newInstance();
+                        billToPartyIdSet.add(billToPartyId);
+                        List partyRelationshipList = EntityUtil.filterByDate(delegator.findByAndCache("PartyRelationship", UtilMisc.toMap("partyIdTo", billToPartyId, "partyRelationshipTypeId", "GROUP_ROLLUP")), true);
+                        Iterator partyRelationshipIter = partyRelationshipList.iterator();
+                        while (partyRelationshipIter.hasNext()) {
+                            GenericValue partyRelationship = (GenericValue) partyRelationshipIter.next();
+                            billToPartyIdSet.add(partyRelationship.get("partyIdFrom"));
+                        }
+
+                        List ptiConditionList = UtilMisc.toList(
+                                new EntityExpr("partyId", EntityOperator.IN, billToPartyIdSet),
+                                new EntityExpr("geoId", EntityOperator.EQUALS, primaryGeoId));
+                        ptiConditionList.add(new EntityExpr("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp));
+                        ptiConditionList.add(new EntityExpr(new EntityExpr("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, new EntityExpr("thruDate", EntityOperator.GREATER_THAN, nowTimestamp)));
+                        EntityCondition ptiCondition = new EntityConditionList(ptiConditionList, EntityOperator.AND);
+                        // sort by -fromDate to get the newest (largest) first, just in case there is more than one, we only want the most recent valid one, should only be one per jurisdiction...
+                        List partyTaxInfos = delegator.findByCondition("PartyTaxInfo", ptiCondition, null, UtilMisc.toList("-fromDate"));
+                        if (partyTaxInfos.size() > 0) {
+                            GenericValue partyTaxInfo = (GenericValue) partyTaxInfos.get(0);
+                            adjMap.put("customerReferenceId", partyTaxInfo.get("partyTaxId"));
+                            if ("Y".equals(partyTaxInfo.getString("isExempt"))) {
+                                adjMap.put("amount", new Double(0));
+                                adjMap.put("exemptAmount", taxAmount);
+                            }
+                        }
+                    } else {
+                        Debug.logInfo("NOTE: A tax calculation was done without a billToPartyId or primaryGeoId, so no tax exemptions or tax IDs considered; billToPartyId=[" + billToPartyId + "] primaryGeoId=[" + primaryGeoId + "]", module);
+                    }
+
+                    adjustments.add(delegator.makeValue("OrderAdjustment", adjMap));
+                }
+            }
+        } catch (GenericEntityException e) {
+            Debug.logError(e, "Problems looking up tax rates", module);
+            return new ArrayList();
+        } catch (GeneralException e) {
+            Debug.logError(e, "Problems looking up tax rates", module);
+            return new ArrayList();
+        }
+
+        return adjustments;
+    }
+}


Property changes on: trunk/applications/accounting/src/org/ofbiz/accounting/tax/SimpleTaxServices.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain
Name: svn:keywords
   + "Id Rev Author"
Name: svn:eol-style
   + native

Added: trunk/applications/accounting/src/org/ofbiz/accounting/tax/TaxAuthorityServices.java
===================================================================
--- trunk/applications/accounting/src/org/ofbiz/accounting/tax/TaxAuthorityServices.java	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/accounting/src/org/ofbiz/accounting/tax/TaxAuthorityServices.java	2005-11-17 08:09:01 UTC (rev 6136)
@@ -0,0 +1,280 @@
+/*
+ * $Id: OrderServices.java 6133 2005-11-17 03:56:16Z jaz $
+ *
+ *  Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
+ *
+ *  Permission is hereby granted, free of charge, to any person obtaining a
+ *  copy of this software and associated documentation files (the "Software"),
+ *  to deal in the Software without restriction, including without limitation
+ *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ *  and/or sell copies of the Software, and to permit persons to whom the
+ *  Software is furnished to do so, subject to the following conditions:
+ *
+ *  The above copyright notice and this permission notice shall be included
+ *  in all copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ *  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
+ *  OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
+ *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+package org.ofbiz.accounting.tax;
+
+import java.sql.Timestamp;
+import java.text.DecimalFormat;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javolution.util.FastList;
+import javolution.util.FastSet;
+
+import org.ofbiz.base.util.Debug;
+import org.ofbiz.base.util.GeneralException;
+import org.ofbiz.base.util.UtilDateTime;
+import org.ofbiz.base.util.UtilMisc;
+import org.ofbiz.base.util.UtilProperties;
+import org.ofbiz.base.util.UtilValidate;
+import org.ofbiz.entity.GenericDelegator;
+import org.ofbiz.entity.GenericEntityException;
+import org.ofbiz.entity.GenericValue;
+import org.ofbiz.entity.condition.EntityCondition;
+import org.ofbiz.entity.condition.EntityConditionList;
+import org.ofbiz.entity.condition.EntityExpr;
+import org.ofbiz.entity.condition.EntityOperator;
+import org.ofbiz.entity.util.EntityUtil;
+import org.ofbiz.service.DispatchContext;
+import org.ofbiz.service.ServiceUtil;
+
+/**
+ * Order Processing Services
+ *
+ * @author     <a href="mailto:jaz at ofbiz.org">Andy Zeneski</a>
+ * @author     <a href="mailto:jonesde at ofbiz.org">David E. Jones</a>
+ * @version    $Rev$
+ * @since      2.0
+ */
+
+public class TaxAuthorityServices {
+
+    public static final String module = TaxAuthorityServices.class.getName();
+
+    public static Map rateProductTaxCalcForDisplay(DispatchContext dctx, Map context) {
+        
+        Map result = ServiceUtil.returnSuccess();
+        return result;
+    }
+    
+    public static Map rateProductTaxCalc(DispatchContext dctx, Map context) {
+        GenericDelegator delegator = dctx.getDelegator();
+        String productStoreId = (String) context.get("productStoreId");
+        String billToPartyId = (String) context.get("billToPartyId");
+        List itemProductList = (List) context.get("itemProductList");
+        List itemAmountList = (List) context.get("itemAmountList");
+        List itemPriceList = (List) context.get("itemPriceList");
+        List itemShippingList = (List) context.get("itemShippingList");
+        Double orderShippingAmount = (Double) context.get("orderShippingAmount");
+        GenericValue shippingAddress = (GenericValue) context.get("shippingAddress");
+
+        Set geoIdSet = FastSet.newInstance();
+        if (shippingAddress != null) {
+            geoIdSet.add(shippingAddress.getString("countryGeoId"));
+            geoIdSet.add(shippingAddress.getString("stateProvinceGeoId"));
+        }
+        
+        // TODO: get the most granular, or all available, geoIds and then find parents by GeoAssoc with geoAssocTypeId="REGIONS" and geoIdTo=<granular geoId> and find the GeoAssoc.geoId
+
+        // without knowing the TaxAuthority parties, just find all TaxAuthories for the set of IDs...
+        Set taxAuthoritySet = FastSet.newInstance();
+        try {
+            List taxAuthorityRawList = delegator.findByConditionCache("TaxAuthority", new EntityExpr("taxAuthGeoId", EntityOperator.IN, geoIdSet), null, null);
+            taxAuthoritySet.addAll(taxAuthorityRawList);
+        } catch (GenericEntityException e) {
+            String errMsg = "Data error getting tax settings: " + e.toString();
+            Debug.logError(e, errMsg, module);
+            return ServiceUtil.returnError(errMsg);
+        }
+        
+        
+        // Setup the return lists.
+        List orderAdjustments = new ArrayList();
+        List itemAdjustments = new ArrayList();
+
+        // Loop through the products; get the taxCategory; and lookup each in the cache.
+        for (int i = 0; i < itemProductList.size(); i++) {
+            GenericValue product = (GenericValue) itemProductList.get(i);
+            Double itemAmount = (Double) itemAmountList.get(i);
+            Double itemPrice = (Double) itemPriceList.get(i);
+            Double shippingAmount = (Double) itemShippingList.get(i);
+            List taxList = null;
+            if (shippingAddress != null) {
+                taxList = getTaxAmount(delegator, product, productStoreId, billToPartyId, taxAuthoritySet, itemPrice.doubleValue(), itemAmount.doubleValue(), shippingAmount.doubleValue());
+            }
+            itemAdjustments.add(taxList);
+        }
+        if (orderShippingAmount.doubleValue() > 0) {
+            List taxList = getTaxAmount(delegator, null, productStoreId, billToPartyId, taxAuthoritySet, 0.00, 0.00, orderShippingAmount.doubleValue());
+            orderAdjustments.addAll(taxList);
+        }
+
+        Map result = ServiceUtil.returnSuccess();
+        result.put("orderAdjustments", orderAdjustments);
+        result.put("itemAdjustments", itemAdjustments);
+
+        return result;
+    }
+
+    private static List getTaxAmount(GenericDelegator delegator, GenericValue item, String productStoreId, String billToPartyId, Set taxAuthoritySet, double itemPrice, double itemAmount, double shippingAmount) {
+        Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
+        List adjustments = FastList.newInstance();
+
+        // store expr
+        EntityCondition storeCond = new EntityExpr("productStoreId", EntityOperator.EQUALS, productStoreId);
+
+        // build the TaxAuthority expressions (taxAuthGeoId, taxAuthPartyId)
+        List taxAuthCondOrList = FastList.newInstance();
+        // start with the _NA_ TaxAuthority...
+        taxAuthCondOrList.add(new EntityExpr(
+                new EntityExpr("taxAuthPartyId", EntityOperator.EQUALS, "_NA_"), 
+                EntityOperator.AND, 
+                new EntityExpr("taxAuthGeoId", EntityOperator.EQUALS, "_NA_")));
+        
+        Iterator taxAuthorityIter = taxAuthoritySet.iterator();
+        while (taxAuthorityIter.hasNext()) {
+            GenericValue taxAuthority = (GenericValue) taxAuthorityIter.next();
+            EntityCondition taxAuthCond = new EntityExpr(
+                    new EntityExpr("taxAuthPartyId", EntityOperator.EQUALS, taxAuthority.getString("taxAuthPartyId")), 
+                    EntityOperator.AND, 
+                    new EntityExpr("taxAuthGeoId", EntityOperator.EQUALS, taxAuthority.getString("taxAuthGeoId")));
+            taxAuthCondOrList.add(taxAuthCond);
+        }
+        EntityCondition taxAuthoritiesCond = new EntityConditionList(taxAuthCondOrList, EntityOperator.OR);
+
+        // TODO: find the tax categories associated with the product and filter by those, with an IN clause or some such
+
+        // build the main condition clause
+        List mainExprs = UtilMisc.toList(storeCond, taxAuthoritiesCond);
+        EntityCondition mainCondition = new EntityConditionList(mainExprs, EntityOperator.AND);
+
+        // create the orderby clause
+        List orderList = UtilMisc.toList("minItemPrice", "minPurchase", "fromDate");
+
+        try {
+            List lookupList = delegator.findByCondition("TaxAuthorityRateProduct", mainCondition, null, orderList);
+            List filteredList = EntityUtil.filterByDate(lookupList);
+
+            if (filteredList.size() == 0) {
+                Debug.logWarning("SimpleTaxCalc: No State/TaxCategory pair found (with or without taxCat).", module);
+                return adjustments;
+            }
+
+            // find the right entry(s) based on purchase amount
+            Iterator flIt = filteredList.iterator();
+            while (flIt.hasNext()) {
+                GenericValue taxLookup = (GenericValue) flIt.next();
+                double minPrice = taxLookup.get("minItemPrice") != null ? taxLookup.getDouble("minItemPrice").doubleValue() : 0.00;
+                double minAmount = taxLookup.get("minPurchase") != null ? taxLookup.getDouble("minPurchase").doubleValue() : 0.00;
+
+                // DEJ20050528 not sure why this is done like this, could put this condition in the query sent to the database, though perhaps it is this way because of issues with that of some sort?
+                if (itemPrice >= minPrice && itemAmount >= minAmount) {
+                    double taxRate = taxLookup.get("salesTaxPercentage") != null ? taxLookup.getDouble("salesTaxPercentage").doubleValue() : 0;
+                    double taxable = 0.00;
+
+                    if (item != null && (item.get("taxable") == null || (item.get("taxable") != null && item.getBoolean("taxable").booleanValue()))) {
+                        taxable += itemAmount;
+                    }
+                    if (taxLookup != null && (taxLookup.get("taxShipping") == null || (taxLookup.get("taxShipping") != null && taxLookup.getBoolean("taxShipping").booleanValue()))) {
+                        taxable += shippingAmount;
+                    }
+
+                    // TODO: DEJ20050528 this is an interesting way to round the number, according to the JavaDoc
+                    //this uses the "ROUND_HALF_EVEN" method (as defined in the BigDecimal class, see JavaDoc
+                    //of that for details); it seems we might want to use the ROUND_HALF_UP method...
+                    String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00");
+                    DecimalFormat formatter = new DecimalFormat(currencyFormat);
+                    double taxTotal = taxable * taxRate;
+                    String amountStr = formatter.format(taxTotal);
+                    Double taxAmount = null;
+                    try {
+                        taxAmount = new Double(formatter.parse(amountStr).doubleValue());
+                    } catch (ParseException e) {
+                        throw new GeneralException("Problem getting parsed amount from string", e);
+                    }
+
+                    String primaryGeoId = taxLookup.getString("stateProvinceGeoId");
+                    String secondaryGeoId = taxLookup.getString("countryGeoId");
+                    String taxAuthPartyId = taxLookup.getString("taxAuthPartyId");
+                    String taxAuthGlAccountId = taxLookup.getString("taxAuthGlAccountId");
+
+                    // if no state/province, the country is the primary
+                    if (primaryGeoId == null || "_NA_".equals(primaryGeoId)) {
+                        primaryGeoId = secondaryGeoId;
+                        secondaryGeoId = null;
+                    }
+
+                    Map adjMap = new HashMap();
+                    adjMap.put("amount", taxAmount);
+                    adjMap.put("sourcePercentage", new Double(taxRate));
+                    adjMap.put("orderAdjustmentTypeId", "SALES_TAX");
+                    // the primary Geo should be the main jurisdiction that the tax is for, and the secondary would just be to define a parent or wrapping jurisdiction of the primary
+                    adjMap.put("primaryGeoId", primaryGeoId);
+                    if (secondaryGeoId != null) adjMap.put("secondaryGeoId", secondaryGeoId);
+                    adjMap.put("comments", taxLookup.getString("description"));
+                    if (taxAuthPartyId != null) adjMap.put("taxAuthPartyId", taxAuthPartyId);
+                    if (taxAuthGlAccountId != null) adjMap.put("overrideGlAccountId", taxAuthGlAccountId);
+                    if (primaryGeoId != null) adjMap.put("taxAuthGeoId", primaryGeoId);
+
+                    // check to see if this party has a tax ID for this, and if the party is tax exempt in the primary (most-local) jurisdiction
+                    if (UtilValidate.isNotEmpty(billToPartyId) && primaryGeoId != null) {
+                        // see if partyId is a member of any groups , if so honor their tax exemptions
+                        // look for PartyRelationship with partyRelationshipTypeId=GROUP_ROLLUP, the partyIdTo is the group member, so the partyIdFrom is the groupPartyId
+                        Set billToPartyIdSet = FastSet.newInstance();
+                        billToPartyIdSet.add(billToPartyId);
+                        List partyRelationshipList = EntityUtil.filterByDate(delegator.findByAndCache("PartyRelationship", UtilMisc.toMap("partyIdTo", billToPartyId, "partyRelationshipTypeId", "GROUP_ROLLUP")), true);
+                        Iterator partyRelationshipIter = partyRelationshipList.iterator();
+                        while (partyRelationshipIter.hasNext()) {
+                            GenericValue partyRelationship = (GenericValue) partyRelationshipIter.next();
+                            billToPartyIdSet.add(partyRelationship.get("partyIdFrom"));
+                        }
+
+                        List ptiConditionList = UtilMisc.toList(
+                                new EntityExpr("partyId", EntityOperator.IN, billToPartyIdSet),
+                                new EntityExpr("geoId", EntityOperator.EQUALS, primaryGeoId));
+                        ptiConditionList.add(new EntityExpr("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp));
+                        ptiConditionList.add(new EntityExpr(new EntityExpr("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, new EntityExpr("thruDate", EntityOperator.GREATER_THAN, nowTimestamp)));
+                        EntityCondition ptiCondition = new EntityConditionList(ptiConditionList, EntityOperator.AND);
+                        // sort by -fromDate to get the newest (largest) first, just in case there is more than one, we only want the most recent valid one, should only be one per jurisdiction...
+                        List partyTaxInfos = delegator.findByCondition("PartyTaxInfo", ptiCondition, null, UtilMisc.toList("-fromDate"));
+                        if (partyTaxInfos.size() > 0) {
+                            GenericValue partyTaxInfo = (GenericValue) partyTaxInfos.get(0);
+                            adjMap.put("customerReferenceId", partyTaxInfo.get("partyTaxId"));
+                            if ("Y".equals(partyTaxInfo.getString("isExempt"))) {
+                                adjMap.put("amount", new Double(0));
+                                adjMap.put("exemptAmount", taxAmount);
+                            }
+                        }
+                    } else {
+                        Debug.logInfo("NOTE: A tax calculation was done without a billToPartyId or primaryGeoId, so no tax exemptions or tax IDs considered; billToPartyId=[" + billToPartyId + "] primaryGeoId=[" + primaryGeoId + "]", module);
+                    }
+
+                    adjustments.add(delegator.makeValue("OrderAdjustment", adjMap));
+                }
+            }
+        } catch (GenericEntityException e) {
+            Debug.logError(e, "Problems looking up tax rates", module);
+            return new ArrayList();
+        } catch (GeneralException e) {
+            Debug.logError(e, "Problems looking up tax rates", module);
+            return new ArrayList();
+        }
+
+        return adjustments;
+    }
+}


Property changes on: trunk/applications/accounting/src/org/ofbiz/accounting/tax/TaxAuthorityServices.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain
Name: svn:keywords
   + "Id Rev Author"
Name: svn:eol-style
   + native

Modified: trunk/applications/ecommerce/data/DemoProduct.xml
===================================================================
--- trunk/applications/ecommerce/data/DemoProduct.xml	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/ecommerce/data/DemoProduct.xml	2005-11-17 08:09:01 UTC (rev 6136)
@@ -68,15 +68,6 @@
     <ProductStoreRole partyId="admin" roleTypeId="SALES_REP" productStoreId="9000" fromDate="2001-05-13 12:00:00.0"/>
     <ProductStoreKeywordOvrd productStoreId="9000" keyword="gizmo" fromDate="2001-05-13 12:00:00.0" target="100" targetTypeEnumId="KOTT_PRODCAT"/>
 
-    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="_NA_" stateProvinceGeoId="_NA_" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="1% OFB Tax" minItemPrice="25.00" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.01" taxAuthPartyId="OFBIZ_TAX" taxAuthGlAccountId="224000"/>
-    
-    <!-- some interesting information at: http://www.taxadmin.org/fta/rate/tax_stru.html -->
-    <!-- note that these rates are for the given Geo only and do not include local taxes (county, city) -->
-     <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="CA" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="California State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0625" taxAuthPartyId="CA_BOE" taxAuthGlAccountId="224100"/>
-     <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="NY" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="New York State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0425" taxAuthPartyId="NY_DTF" taxAuthGlAccountId="224200"/>
-    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="TX" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="Texas State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0625" taxAuthPartyId="TX_TAXMAN" taxAuthGlAccountId="224000"/>
-    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="UT" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="Utah State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0475" taxAuthPartyId="UT_TAXMAN" taxAuthGlAccountId="224000"/>
-    
     <WebSite webSiteId="WebStore" siteName="eCommerce Web Site" productStoreId="9000"/>
     <WebSite webSiteId="OrderEntry" siteName="Order Entry Web Site" productStoreId="9000"/>
 

Modified: trunk/applications/ecommerce/data/DemoTaxAuthority.xml
===================================================================
--- trunk/applications/ecommerce/data/DemoTaxAuthority.xml	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/ecommerce/data/DemoTaxAuthority.xml	2005-11-17 08:09:01 UTC (rev 6136)
@@ -24,13 +24,19 @@
   <Party partyId="UT_TAXMAN" partyTypeId="PARTY_GROUP"/>
   <PartyGroup partyId="UT_TAXMAN" groupName="Utah Sales Tax Authority"/>
 
-  <Party partyId="OFBIZ_TAX" partyTypeId="PARTY_GROUP"/>
-  <PartyGroup partyId="OFBIZ_TAX" groupName="Ofbiz Tax"/>
-  
-  <TaxAuthority taxAuthGeoId="CA" taxAuthPartyId="CA_BOE" requireTaxIdForOrder="N" includeTaxInPrice="N"/>
-  <TaxAuthority taxAuthGeoId="NY" taxAuthPartyId="NY_DTF" requireTaxIdForOrder="N" includeTaxInPrice="N"/>
-  <TaxAuthority taxAuthGeoId="TX" taxAuthPartyId="TX_TAXMAN" requireTaxIdForOrder="N" includeTaxInPrice="N"/>
-  <TaxAuthority taxAuthGeoId="UT" taxAuthPartyId="UT_TAXMAN" requireTaxIdForOrder="N" includeTaxInPrice="N"/>
-  <TaxAuthority taxAuthGeoId="_NA_" taxAuthPartyId="OFBIZ_TAX" requireTaxIdForOrder="N" includeTaxInPrice="N"/>
+  <TaxAuthority taxAuthGeoId="CA" taxAuthPartyId="CA_BOE" includeTaxInPrice="N"/>
+  <TaxAuthority taxAuthGeoId="NY" taxAuthPartyId="NY_DTF" includeTaxInPrice="N"/>
+  <TaxAuthority taxAuthGeoId="TX" taxAuthPartyId="TX_TAXMAN" includeTaxInPrice="N"/>
+  <TaxAuthority taxAuthGeoId="UT" taxAuthPartyId="UT_TAXMAN" includeTaxInPrice="N"/>
+  <TaxAuthority taxAuthGeoId="_NA_" taxAuthPartyId="_NA_" includeTaxInPrice="N"/>
+
+  <!-- the older style records... -->
+    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="_NA_" stateProvinceGeoId="_NA_" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="1% OFB _NA_ Tax" minItemPrice="25.00" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.01" taxAuthPartyId="_NA_" taxAuthGlAccountId="224000"/>
+    
+    <!-- some interesting information at: http://www.taxadmin.org/fta/rate/tax_stru.html -->
+    <!-- note that these rates are for the given Geo only and do not include local taxes (county, city) -->
+    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="CA" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="California State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0625" taxAuthPartyId="CA_BOE" taxAuthGlAccountId="224100"/>
+    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="NY" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="New York State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0425" taxAuthPartyId="NY_DTF" taxAuthGlAccountId="224200"/>
+    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="TX" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="Texas State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0625" taxAuthPartyId="TX_TAXMAN" taxAuthGlAccountId="224000"/>
+    <SimpleSalesTaxLookup productStoreId="9000" countryGeoId="USA" stateProvinceGeoId="UT" taxCategory="_NA_" fromDate="2001-01-01 00:00:00.001" description="Utah State Sales Tax" minItemPrice="0.0" minPurchase="0.0" taxShipping="N" salesTaxPercentage="0.0475" taxAuthPartyId="UT_TAXMAN" taxAuthGlAccountId="224000"/>
 </entity-engine-xml>
-

Deleted: trunk/applications/order/script/org/ofbiz/order/order/TaxRateServices.xml
===================================================================
--- trunk/applications/order/script/org/ofbiz/order/order/TaxRateServices.xml	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/order/script/org/ofbiz/order/order/TaxRateServices.xml	2005-11-17 08:09:01 UTC (rev 6136)
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!--
- *  Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
- *
- *  Permission is hereby granted, free of charge, to any person obtaining a
- *  copy of this software and associated documentation files (the "Software"),
- *  to deal in the Software without restriction, including without limitation
- *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
- *  and/or sell copies of the Software, and to permit persons to whom the
- *  Software is furnished to do so, subject to the following conditions:
- *
- *  The above copyright notice and this permission notice shall be included
- *  in all copies or substantial portions of the Software.
- *
- *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
- *  OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
- *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * @author     Andy Zeneski (jaz at ofbiz.org)
- * @version    $Rev$
- * @since      2.0
--->
-
-<simple-methods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
-        xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/simple-methods.xsd">
-    <simple-method method-name="createTaxRate" short-description="Create a Tax Rate">
-        <check-permission permission="TAXRATE" action="_CREATE"><fail-property resource="OrderErrorUiLabels" property="OrderSecurityErrorToRunCreateTaxRate"/></check-permission>
-        <check-errors/>
-
-        <make-value value-name="newEntity" entity-name="SimpleSalesTaxLookup"/>
-        <set-nonpk-fields map-name="parameters" value-name="newEntity"/>
-        <set-pk-fields map-name="parameters" value-name="newEntity"/>
-        <if-empty field-name="fromDate" map-name="newEntity">
-            <now-timestamp-to-env env-name="fromDate"/>
-            <env-to-field env-name="fromDate" map-name="newEntity" field-name="fromDate"/>
-        </if-empty>
-        <if-empty field-name="taxCategory" map-name="newEntity">
-            <string-to-field string="_NA_" map-name="newEntity" field-name="taxCategory"/>
-        </if-empty>
-
-        <create-value value-name="newEntity"/>
-
-    </simple-method>
-
-    <simple-method method-name="removeTaxRate" short-description="Remove a Tax Rate">
-        <check-permission permission="TAXRATE" action="_DELETE"><fail-property resource="OrderErrorUiLabels" property="OrderSecurityErrorToRunRemoveTaxRate"/></check-permission>
-        <check-errors/>
-
-        <make-value entity-name="SimpleSalesTaxLookup" value-name="lookupPKMap"/>
-        <set-pk-fields map-name="parameters" value-name="lookupPKMap"/>
-        <find-by-primary-key entity-name="SimpleSalesTaxLookup" map-name="lookupPKMap" value-name="lookedUpValue"/>
-        <remove-value value-name="lookedUpValue"/>
-    </simple-method>
-
-</simple-methods>
\ No newline at end of file

Modified: trunk/applications/order/servicedef/services.xml
===================================================================
--- trunk/applications/order/servicedef/services.xml	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/order/servicedef/services.xml	2005-11-17 08:09:01 UTC (rev 6136)
@@ -338,68 +338,6 @@
        <attribute name="orderItem" type="GenericValue" mode="IN" optional="false"/>
    </service>
 
-    <!-- Tax Services -->
-    <service name="calcTaxInterface" engine="interface" location="" invoke="">
-        <description>Tax Calc Service Interface</description>
-        <attribute name="productStoreId" type="String" mode="IN"/>
-        <attribute name="billToPartyId" type="String" mode="IN" optional="true"/> <!-- would like to have this not-optional, but in some circumstances may need a tax estimate without knowing who the customer is -->
-        <attribute name="itemProductList" type="java.util.List" mode="IN"/>
-        <attribute name="itemAmountList" type="java.util.List" mode="IN"/>
-        <attribute name="itemPriceList" type="java.util.List" mode="IN"/>
-        <attribute name="itemShippingList" type="java.util.List" mode="IN" optional="true"/>
-        <attribute name="orderShippingAmount" type="Double" mode="IN" optional="true"/>
-        <attribute name="shippingAddress" type="org.ofbiz.entity.GenericValue" mode="IN" optional="true"/>
-        <attribute name="orderAdjustments" type="java.util.List" mode="OUT"/>
-        <attribute name="itemAdjustments" type="java.util.List" mode="OUT"/>
-    </service>
-
-    <service name="calcTax" engine="java"
-            location="org.ofbiz.order.order.OrderServices" invoke="simpleTaxCalc">
-        <description>Simple Calc Tax Service</description>
-        <implements service="calcTaxInterface"/>
-    </service>
-
-    <service name="createTaxRate" engine="simple"
-            location="org/ofbiz/order/order/TaxRateServices.xml" invoke="createTaxRate">
-        <description>Create a Tax Rate entry</description>
-        <attribute name="productStoreId" type="String" mode="IN" optional="false"/>
-        <attribute name="countryGeoId" type="String" mode="IN" optional="false"/>
-        <attribute name="stateProvinceGeoId" type="String" mode="IN" optional="false"/>
-        <attribute name="taxCategory" type="String" mode="IN" optional="true"/>
-        <attribute name="taxShipping" type="String" mode="IN" optional="false"/>
-        <attribute name="minItemPrice" type="Double" mode="IN" optional="false"/>
-        <attribute name="minPurchase" type="Double" mode="IN" optional="false"/>
-        <attribute name="description" type="String" mode="IN" optional="true"/>
-        <attribute name="salesTaxPercentage" type="Double" mode="IN" optional="false"/>
-        <attribute name="fromDate" type="Timestamp" mode="IN" optional="true"/>
-        <attribute name="thruDate" type="Timestamp" mode="IN" optional="true"/>
-    </service>
-
-    <service name="removeTaxRate" engine="simple"
-            location="org/ofbiz/order/order/TaxRateServices.xml" invoke="removeTaxRate">
-        <description>Remove a Tax Rate entry</description>
-        <attribute name="productStoreId" type="String" mode="IN" optional="false"/>
-        <attribute name="countryGeoId" type="String" mode="IN" optional="false"/>
-        <attribute name="stateProvinceGeoId" type="String" mode="IN" optional="false"/>
-        <attribute name="taxCategory" type="String" mode="IN" optional="false"/>
-        <attribute name="minItemPrice" type="Double" mode="IN" optional="false"/>
-        <attribute name="minPurchase" type="Double" mode="IN" optional="false"/>
-        <attribute name="fromDate" type="Timestamp" mode="IN" optional="false"/>
-    </service>
-
-    <!-- ZipSales Tax Services -->
-    <service name="importZipSalesTaxData" engine="java" transaction-timout="7200"
-            location="org.ofbiz.order.thirdparty.zipsales.ZipSalesServices" invoke="importFlatTable">
-        <description>Import ZipSales Flat File</description>
-        <attribute name="taxFileLocation" type="String" mode="IN" optional="false"/>
-        <attribute name="ruleFileLocation" type="String" mode="IN" optional="false"/>
-    </service>
-
-    <service name="_calcTax" engine="java"
-            location="org.ofbiz.order.thirdparty.zipsales.ZipSalesServices" invoke="flatTaxCalc">
-        <description>Zip Sales Calc Tax Service - change this to calcTax to run</description>
-        <implements service="calcTaxInterface"/>
-    </service>
     <!-- Order View Services -->
     <service name="getOrderedSummaryInformation" engine="simple"
             location="org/ofbiz/order/order/OrderServices.xml" invoke="getOrderedSummaryInformation">

Modified: trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java
===================================================================
--- trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java	2005-11-17 08:02:29 UTC (rev 6135)
+++ trunk/applications/order/src/org/ofbiz/order/order/OrderServices.java	2005-11-17 08:09:01 UTC (rev 6136)
@@ -2282,207 +2282,6 @@
         return result;
     }
 
-    /** Null tax calc service. */
-    public static Map nullTaxCalc(DispatchContext dctx, Map context) {
-        return UtilMisc.toMap("orderAdjustments", UtilMisc.toList(null), "itemAdjustments", UtilMisc.toList(null));
-    }
-
-    /** Simple tax calc service. */
-    public static Map simpleTaxCalc(DispatchContext dctx, Map context) {
-        GenericDelegator delegator = dctx.getDelegator();
-        String productStoreId = (String) context.get("productStoreId");
-        String billToPartyId = (String) context.get("billToPartyId");
-        List itemProductList = (List) context.get("itemProductList");
-        List itemAmountList = (List) context.get("itemAmountList");
-        List itemPriceList = (List) context.get("itemPriceList");
-        List itemShippingList = (List) context.get("itemShippingList");
-        Double orderShippingAmount = (Double) context.get("orderShippingAmount");
-        GenericValue shippingAddress = (GenericValue) context.get("shippingAddress");
-        //GenericValue userLogin = (GenericValue) context.get("userLogin");
-        //Locale locale = (Locale) context.get("locale");
-
-        // Simple Tax Calc only uses the state from the address and the SalesTaxLookup entity.
-
-        String countryCode = null;
-        String stateCode = null;
-
-        if (shippingAddress != null) {
-            countryCode = shippingAddress.getString("countryGeoId");
-            stateCode = shippingAddress.getString("stateProvinceGeoId");
-        }
-
-        // Setup the return lists.
-        List orderAdjustments = new ArrayList();
-        List itemAdjustments = new ArrayList();
-
-        // Loop through the products; get the taxCategory; and lookup each in the cache.
-        for (int i = 0; i < itemProductList.size(); i++) {
-            GenericValue product = (GenericValue) itemProductList.get(i);
-            Double itemAmount = (Double) itemAmountList.get(i);
-            Double itemPrice = (Double) itemPriceList.get(i);
-            Double shippingAmount = (Double) itemShippingList.get(i);
-            List taxList = null;
-            if (shippingAddress != null) {
-                taxList = getTaxAmount(delegator, product, productStoreId, billToPartyId, countryCode, stateCode, itemPrice.doubleValue(), itemAmount.doubleValue(), shippingAmount.doubleValue());
-            }
-            itemAdjustments.add(taxList);
-        }
-        if (orderShippingAmount.doubleValue() > 0) {
-            List taxList = getTaxAmount(delegator, null, productStoreId, billToPartyId, countryCode, stateCode, 0.00, 0.00, orderShippingAmount.doubleValue());
-            orderAdjustments.addAll(taxList);
-        }
-
-        Map result = UtilMisc.toMap("orderAdjustments", orderAdjustments, "itemAdjustments", itemAdjustments);
-
-        return result;
-    }
-
-    private static List getTaxAmount(GenericDelegator delegator, GenericValue item, String productStoreId, String billToPartyId, String countryCode, String stateCode, double itemPrice, double itemAmount, double shippingAmount) {
-        Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
-        List adjustments = new ArrayList();
-
-        // store expr
-        EntityCondition storeCond = new EntityExpr("productStoreId", EntityOperator.EQUALS, productStoreId);
-
-        // build the country expressions
-        List countryExprs = UtilMisc.toList(new EntityExpr("countryGeoId", EntityOperator.EQUALS, countryCode), new EntityExpr("countryGeoId", EntityOperator.EQUALS, "_NA_"));
-        EntityCondition countryCond = new EntityConditionList(countryExprs, EntityOperator.OR);
-
-        // build the state expression
-        List stateExprs = UtilMisc.toList(new EntityExpr("stateProvinceGeoId", EntityOperator.EQUALS, stateCode), new EntityExpr("stateProvinceGeoId", EntityOperator.EQUALS, "_NA_"));
-        EntityCondition stateCond = new EntityConditionList(stateExprs, EntityOperator.OR);
-
-        // build the tax cat expression
-        List taxCatExprs = UtilMisc.toList(new EntityExpr("taxCategory", EntityOperator.EQUALS, "_NA_"));
-        if (item != null && item.get("taxCategory") != null) {
-            taxCatExprs.add(new EntityExpr("taxCategory", EntityOperator.EQUALS, item.getString("taxCategory")));
-        }
-        EntityCondition taxCatCond = new EntityConditionList(taxCatExprs, EntityOperator.OR);
-
-        // build the main condition clause
-        List mainExprs = UtilMisc.toList(storeCond, countryCond, stateCond);
-        if (taxCatExprs.size() > 1) {
-            mainExprs.add(taxCatCond);
-        } else {
-            mainExprs.add(taxCatExprs.get(0));
-        }
-        EntityCondition mainCondition = new EntityConditionList(mainExprs, EntityOperator.AND);
-
-        // create the orderby clause
-        List orderList = UtilMisc.toList("minItemPrice", "minPurchase", "fromDate");
-
-        try {
-            List lookupList = delegator.findByCondition("SimpleSalesTaxLookup", mainCondition, null, orderList);
-            List filteredList = EntityUtil.filterByDate(lookupList);
-
-            if (filteredList.size() == 0) {
-                Debug.logWarning("SimpleTaxCalc: No State/TaxCategory pair found (with or without taxCat).", module);
-                return adjustments;
-            }
-
-            // find the right entry(s) based on purchase amount
-            Iterator flIt = filteredList.iterator();
-            while (flIt.hasNext()) {
-                GenericValue taxLookup = (GenericValue) flIt.next();
-                double minPrice = taxLookup.get("minItemPrice") != null ? taxLookup.getDouble("minItemPrice").doubleValue() : 0.00;
-                double minAmount = taxLookup.get("minPurchase") != null ? taxLookup.getDouble("minPurchase").doubleValue() : 0.00;
-
-                // DEJ20050528 not sure why this is done like this, could put this condition in the query sent to the database, though perhaps it is this way because of issues with that of some sort?
-                if (itemPrice >= minPrice && itemAmount >= minAmount) {
-                    double taxRate = taxLookup.get("salesTaxPercentage") != null ? taxLookup.getDouble("salesTaxPercentage").doubleValue() : 0;
-                    double taxable = 0.00;
-
-                    if (item != null && (item.get("taxable") == null || (item.get("taxable") != null && item.getBoolean("taxable").booleanValue()))) {
-                        taxable += itemAmount;
-                    }
-                    if (taxLookup != null && (taxLookup.get("taxShipping") == null || (taxLookup.get("taxShipping") != null && taxLookup.getBoolean("taxShipping").booleanValue()))) {
-                        taxable += shippingAmount;
-                    }
-
-                    // TODO: DEJ20050528 this is an interesting way to round the number, according to the JavaDoc
-                    //this uses the "ROUND_HALF_EVEN" method (as defined in the BigDecimal class, see JavaDoc
-                    //of that for details); it seems we might want to use the ROUND_HALF_UP method...
-                    String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00");
-                    DecimalFormat formatter = new DecimalFormat(currencyFormat);
-                    double taxTotal = taxable * taxRate;
-                    String amountStr = formatter.format(taxTotal);
-                    Double taxAmount = null;
-                    try {
-                        taxAmount = new Double(formatter.parse(amountStr).doubleValue());
-                    } catch (ParseException e) {
-                        throw new GeneralException("Problem getting parsed amount from string", e);
-                    }
-
-                    String primaryGeoId = taxLookup.getString("stateProvinceGeoId");
-                    String secondaryGeoId = taxLookup.getString("countryGeoId");
-                    String taxAuthPartyId = taxLookup.getString("taxAuthPartyId");
-                    String taxAuthGlAccountId = taxLookup.getString("taxAuthGlAccountId");
-
-                    // if no state/province, the country is the primary
-                    if (primaryGeoId == null || "_NA_".equals(primaryGeoId)) {
-                        primaryGeoId = secondaryGeoId;
-                        secondaryGeoId = null;
-                    }
-
-                    Map adjMap = new HashMap();
-                    adjMap.put("amount", taxAmount);
-                    adjMap.put("sourcePercentage", new Double(taxRate));
-                    adjMap.put("orderAdjustmentTypeId", "SALES_TAX");
-                    // the primary Geo should be the main jurisdiction that the tax is for, and the secondary would just be to define a parent or wrapping jurisdiction of the primary
-                    adjMap.put("primaryGeoId", primaryGeoId);
-                    if (secondaryGeoId != null) adjMap.put("secondaryGeoId", secondaryGeoId);
-                    adjMap.put("comments", taxLookup.getString("description"));
-                    if (taxAuthPartyId != null) adjMap.put("taxAuthPartyId", taxAuthPartyId);
-                    if (taxAuthGlAccountId != null) adjMap.put("overrideGlAccountId", taxAuthGlAccountId);
-                    if (primaryGeoId != null) adjMap.put("taxAuthGeoId", primaryGeoId);
-
-                    // check to see if this party has a tax ID for this, and if the party is tax exempt in the primary (most-local) jurisdiction
-                    if (UtilValidate.isNotEmpty(billToPartyId) && primaryGeoId != null) {
-                        // see if partyId is a member of any groups , if so honor their tax exemptions
-                        // look for PartyRelationship with partyRelationshipTypeId=GROUP_ROLLUP, the partyIdTo is the group member, so the partyIdFrom is the groupPartyId
-                        Set billToPartyIdSet = FastSet.newInstance();
-                        billToPartyIdSet.add(billToPartyId);
-                        List partyRelationshipList = EntityUtil.filterByDate(delegator.findByAndCache("PartyRelationship", UtilMisc.toMap("partyIdTo", billToPartyId, "partyRelationshipTypeId", "GROUP_ROLLUP")), true);
-                        Iterator partyRelationshipIter = partyRelationshipList.iterator();
-                        while (partyRelationshipIter.hasNext()) {
-                            GenericValue partyRelationship = (GenericValue) partyRelationshipIter.next();
-                            billToPartyIdSet.add(partyRelationship.get("partyIdFrom"));
-                        }
-
-                        List ptiConditionList = UtilMisc.toList(
-                                new EntityExpr("partyId", EntityOperator.IN, billToPartyIdSet),
-                                new EntityExpr("geoId", EntityOperator.EQUALS, primaryGeoId));
-                        ptiConditionList.add(new EntityExpr("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp));
-                        ptiConditionList.add(new EntityExpr(new EntityExpr("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, new EntityExpr("thruDate", EntityOperator.GREATER_THAN, nowTimestamp)));
-                        EntityCondition ptiCondition = new EntityConditionList(ptiConditionList, EntityOperator.AND);
-                        // sort by -fromDate to get the newest (largest) first, just in case there is more than one, we only want the most recent valid one, should only be one per jurisdiction...
-                        List partyTaxInfos = delegator.findByCondition("PartyTaxInfo", ptiCondition, null, UtilMisc.toList("-fromDate"));
-                        if (partyTaxInfos.size() > 0) {
-                            GenericValue partyTaxInfo = (GenericValue) partyTaxInfos.get(0);
-                            adjMap.put("customerReferenceId", partyTaxInfo.get("partyTaxId"));
-                            if ("Y".equals(partyTaxInfo.getString("isExempt"))) {
-                                adjMap.put("amount", new Double(0));
-                                adjMap.put("exemptAmount", taxAmount);
-                            }
-                        }
-                    } else {
-                        Debug.logInfo("NOTE: A tax calculation was done without a billToPartyId or primaryGeoId, so no tax exemptions or tax IDs considered; billToPartyId=[" + billToPartyId + "] primaryGeoId=[" + primaryGeoId + "]", module);
-                    }
-
-                    adjustments.add(delegator.makeValue("OrderAdjustment", adjMap));
-                }
-            }
-        } catch (GenericEntityException e) {
-            Debug.logError(e, "Problems looking up tax rates", module);
-            return new ArrayList();
-        } catch (GeneralException e) {
-            Debug.logError(e, "Problems looking up tax rates", module);
-            return new ArrayList();
-        }
-
-        return adjustments;
-    }
-
     // return / refund services
 
     // helper method for sending return notifications



More information about the Svn mailing list