KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensourcestrategies > financials > util > UtilFinancial


1 /*
2  * Copyright (c) 2006 - 2007 Open Source Strategies, Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the Honest Public License.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * Honest Public License for more details.
11  *
12  * You should have received a copy of the Honest Public License
13  * along with this program; if not, write to Funambol,
14  * 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA
15  */

16
17 package com.opensourcestrategies.financials.util;
18
19
20 import java.util.*;
21 import java.sql.Timestamp JavaDoc;
22 import java.math.BigDecimal JavaDoc;
23
24 import javolution.util.FastMap;
25
26 import org.ofbiz.accounting.invoice.InvoiceWorker;
27 import org.ofbiz.accounting.util.UtilAccounting;
28 import org.ofbiz.base.util.Debug;
29 import org.ofbiz.base.util.UtilDateTime;
30 import org.ofbiz.base.util.UtilMisc;
31 import org.ofbiz.base.util.UtilNumber;
32 import org.ofbiz.entity.GenericDelegator;
33 import org.ofbiz.entity.GenericEntity;
34 import org.ofbiz.entity.GenericEntityException;
35 import org.ofbiz.entity.GenericValue;
36 import org.ofbiz.entity.condition.EntityConditionList;
37 import org.ofbiz.entity.condition.EntityExpr;
38 import org.ofbiz.entity.condition.EntityOperator;
39 import org.ofbiz.entity.util.EntityUtil;
40 import org.ofbiz.service.DispatchContext;
41 import org.ofbiz.service.GenericServiceException;
42 import org.ofbiz.service.LocalDispatcher;
43 import org.ofbiz.service.ModelService;
44 import org.ofbiz.service.ServiceUtil;
45 /**
46  * UtilFinancial - Utilities for financials.
47  *
48  * @author <a HREF="mailto:leon@opensourcestrategies.com">Leon Torres</a>
49  * @version $Rev: 81 $
50  * @since 2.2
51  */

52
53 public class UtilFinancial {
54     
55     public static String JavaDoc module = UtilFinancial.class.getName();
56
57     public static int decimals = UtilNumber.getBigDecimalScale("fin_arithmetic.properties", "financial.statements.decimals");
58     public static int rounding = UtilNumber.getBigDecimalRoundingMode("fin_arithmetic.properties", "financial.statements.rounding");
59     protected static final BigDecimal JavaDoc ZERO = new BigDecimal JavaDoc("0"); // TODO: this will soon be UtilNumber.BD_ZERO
60
protected static final int MILLISECONDS_PER_DAY = 86400000;
61     public static final String JavaDoc DEFAULT_PRODUCT_ID = "_NA_"; // productId to use in various Maps in case there is no product (ie, bulk items)
62

63     /**
64      * Return either the field productId from the value or the DEFAULT_PRODUCT_ID (usually "_NA_")
65      * @param value
66      * @return
67      */

68     public static String JavaDoc getProductIdOrDefault(GenericValue value) {
69         if (value.getString("productId") != null) {
70             return value.getString("productId");
71         } else {
72             return DEFAULT_PRODUCT_ID;
73         }
74     }
75     
76     public static EntityExpr getAssetExpr(GenericDelegator delegator) throws GenericEntityException {
77         return getGlAccountClassExpr("ASSET", delegator);
78     }
79
80     public static EntityExpr getLiabilityExpr(GenericDelegator delegator) throws GenericEntityException {
81         return getGlAccountClassExpr("LIABILITY", delegator);
82     }
83
84     public static EntityExpr getEquityExpr(GenericDelegator delegator) throws GenericEntityException {
85         return getGlAccountClassExpr("EQUITY", delegator);
86     }
87
88     /**
89      * Gets an entity expression where the field glAccountClassId is a child of the given rootGlAccountClassId.
90      * The intent is to assist with building queries such as 'get all accounts of type ASSET'.
91      * If the class is not defined, an expression that always evaluates to true is returned instead.
92      * Use one of the shortcut methods, like getAssetExpr() instead.
93      *
94      * Ex. Submitting "DEBIT" results in the expression,
95      * glAccountClassId IN ('DEBIT', 'ASSET', 'DISTRIBUTION', 'EXPENSE', 'INCOME', 'NON_POSTING')
96      *
97      * @param rootGlAccountClassId The ancestor class to check that the field glAccountClassId is a member of
98      * @return A suitable EntityExpr for checking that the glAccountClassId field is a member of this tree
99      */

100     public static EntityExpr getGlAccountClassExpr(String JavaDoc rootGlAccountClassId, GenericDelegator delegator) throws GenericEntityException {
101
102         // first get the gl class root value
103
GenericValue glAccountClass = delegator.findByPrimaryKeyCache("GlAccountClass", UtilMisc.toMap("glAccountClassId", rootGlAccountClassId));
104         if (glAccountClass == null) {
105             Debug.logWarning("Cannot find GlAccountClass [" + rootGlAccountClassId + "]", module);
106             return new EntityExpr(new Integer JavaDoc(1), EntityOperator.EQUALS, new Integer JavaDoc(1));
107         }
108
109         // recursively build the list of ids that are of this class
110
List ids = new ArrayList();
111         recurseGetGlAccountClassIds(glAccountClass, ids);
112
113         // make a WHERE glAccountId IN (list of ids) expression
114
return new EntityExpr("glAccountClassId", EntityOperator.IN, ids);
115     }
116
117     /**
118      * Recursively obtains the IDs of all children of a given glAccountClass.
119      * @param ids A List to populate with the children IDs
120      */

121     public static void recurseGetGlAccountClassIds(GenericValue glAccountClass, List ids) throws GenericEntityException {
122         ids.add(glAccountClass.getString("glAccountClassId"));
123         List children = glAccountClass.getRelatedCache("ChildGlAccountClass");
124         for (Iterator iter = children.iterator(); iter.hasNext(); ) {
125             GenericValue child = (GenericValue) iter.next();
126             recurseGetGlAccountClassIds(child, ids);
127         }
128     }
129
130     /**
131      * Gets an entity expression where the field glAccountTypeId is a child of the given rootGlAccountTypeId.
132      * The intent is to assist with building queries such as 'get all accounts of type SALES_ACCOUNT'.
133      * If the type is not defined, an expression that always evaluates to true is returned instead.
134      *
135      * Ex. Submitting "COGS_ACCOUNT" results in the expression,
136      * glAccountTypeId IN ('COGS_ACCOUNT', 'COGS_ADJ_AVG_COST')
137      *
138      * @param rootGlAccountTypeId The ancestor type to check that the field glAccountTypeId is a member of
139      * @return A suitable EntityExpr for checking that the glAccountTypeId field is a member of this tree
140      */

141     public static EntityExpr getGlAccountTypeExpr(String JavaDoc rootGlAccountTypeId, GenericDelegator delegator) throws GenericEntityException {
142
143         // first get the gl type root value
144
GenericValue glAccountType = delegator.findByPrimaryKeyCache("GlAccountType", UtilMisc.toMap("glAccountTypeId", rootGlAccountTypeId));
145         if (glAccountType == null) {
146             Debug.logWarning("Cannot find GlAccountType [" + rootGlAccountTypeId + "]", module);
147             return new EntityExpr("1", EntityOperator.EQUALS, "1");
148         }
149
150         // recursively build the list of ids that are of this type
151
List ids = new ArrayList();
152         recurseGetGlAccountTypeIds(glAccountType, ids);
153
154         // make a WHERE glAccountId IN (list of ids) expression
155
return new EntityExpr("glAccountTypeId", EntityOperator.IN, ids);
156     }
157
158     /**
159      * Recursively obtains the IDs of all children of a given glAccountType.
160      * @param ids A List to populate with the children IDs
161      */

162     public static void recurseGetGlAccountTypeIds(GenericValue glAccountType, List ids) throws GenericEntityException {
163         ids.add(glAccountType.getString("glAccountTypeId"));
164         List children = glAccountType.getRelatedCache("ChildGlAccountType");
165         for (Iterator iter = children.iterator(); iter.hasNext(); ) {
166             GenericValue child = (GenericValue) iter.next();
167             recurseGetGlAccountTypeIds(child, ids);
168         }
169     }
170
171     /**
172      * Determines conversion factor given a source currencyUomId and the organizationPartyId's accounting preference.
173      * @param delegator
174      * @param dispatcher
175      * @param organizationPartyId
176      * @param currencyUomId
177      * @throws GenericEntityException
178      * @throws GenericServiceException
179      * @author Leon Torres
180      */

181     public static double determineUomConversionFactor(GenericDelegator delegator, LocalDispatcher dispatcher,
182             String JavaDoc organizationPartyId, String JavaDoc currencyUomId) throws GenericEntityException, GenericServiceException {
183         return determineUomConversionFactor(delegator, dispatcher, organizationPartyId, currencyUomId, UtilDateTime.nowTimestamp() );
184     }
185
186     /**
187      * Determines conversion factor given a source currencyUomId, the organizationPartyId's accounting preference and a date.
188      */

189     public static double determineUomConversionFactor(GenericDelegator delegator, LocalDispatcher dispatcher,
190             String JavaDoc organizationPartyId, String JavaDoc currencyUomId, Timestamp JavaDoc asOfDate) throws GenericEntityException, GenericServiceException {
191         try {
192             // default conversion factor
193
double conversionFactor = 1.0;
194             // if currencyUomId is null, return default
195
if (currencyUomId == null) {
196                 return conversionFactor;
197             }
198             
199             // get our organization's accounting preference
200
GenericValue accountingPreference = delegator.findByPrimaryKey("Party",
201                     UtilMisc.toMap("partyId", organizationPartyId)).getRelatedOne("PartyAcctgPreference");
202             if (accountingPreference == null) {
203                 String JavaDoc msg = "Currency conversion failed: No PartyAcctgPreference entity data for organizationPartyId " + organizationPartyId;
204                 Debug.logError(msg, module);
205                 throw new GenericServiceException(msg);
206             }
207             
208             // if the currencies are equal, return default
209
if (currencyUomId.equals(accountingPreference.getString("baseCurrencyUomId"))) {
210                 return conversionFactor;
211             }
212             
213             // this does a currency conversion, based on currencyUomId and the party's accounting preferences. conversionFactor will be used for postings
214
Map tmpResult = dispatcher.runSync("convertUom", UtilMisc.toMap("originalValue", new Double JavaDoc(conversionFactor),
215                     "uomId", currencyUomId, "uomIdTo", accountingPreference.getString("baseCurrencyUomId"), "asOfDate", asOfDate ));
216             
217             if (((String JavaDoc) tmpResult.get(ModelService.RESPONSE_MESSAGE)).equals(ModelService.RESPOND_SUCCESS)) {
218                 conversionFactor = ((Double JavaDoc) tmpResult.get("convertedValue")).doubleValue();
219             } else {
220                 String JavaDoc msg = "Currency conversion failed: No currencyUomId defined in PartyAcctgPreference entity for organizationPartyId " + organizationPartyId;
221                 Debug.logError(msg, module);
222                 throw new GenericServiceException(msg);
223             }
224             
225             Debug.logInfo("currency conversion factor is = " + conversionFactor, module);
226             return conversionFactor;
227             
228         } catch (GenericEntityException ex) {
229             Debug.logError(ex.getMessage(), module);
230             throw new GenericEntityException(ex);
231         } catch (GenericServiceException ex) {
232             Debug.logError(ex.getMessage(), module);
233             throw new GenericServiceException(ex);
234         }
235     }
236
237 }
238
Popular Tags