KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensourcestrategies > crmsfa > opportunities > UtilOpportunity


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 /* Copyright (c) 2005-2006 Open Source Strategies, Inc. */
17
18 /*
19  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
20  *
21  * Permission is hereby granted, free of charge, to any person obtaining a
22  * copy of this software and associated documentation files (the "Software"),
23  * to deal in the Software without restriction, including without limitation
24  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
25  * and/or sell copies of the Software, and to permit persons to whom the
26  * Software is furnished to do so, subject to the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be included
29  * in all copies or substantial portions of the Software.
30  *
31  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
32  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
34  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
35  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
36  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
37  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */

39 package com.opensourcestrategies.crmsfa.opportunities;
40
41 import java.util.Map JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Iterator JavaDoc;
44 import java.util.ArrayList JavaDoc;
45 import java.util.Locale JavaDoc;
46
47 import org.ofbiz.base.util.Debug;
48 import org.ofbiz.base.util.UtilMisc;
49 import org.ofbiz.base.util.UtilDateTime;
50 import org.ofbiz.common.period.PeriodWorker;
51 import org.ofbiz.entity.*;
52 import org.ofbiz.entity.condition.*;
53 import org.ofbiz.entity.util.*;
54
55 /**
56  * Opportunity utility methods.
57  *
58  * @author <a HREF="mailto:leon@opensourcestrategies.com">Leon Torres</a>
59  */

60
61 public class UtilOpportunity {
62
63     public static final String JavaDoc module = UtilOpportunity.class.getName();
64
65     /**
66      * Helper method to get the principal account for an opportunity. This is a simplification of the
67      * datamodel and should only be calld for non-critical uses. Returns null if no account was found,
68      * which would be the case if there were a lead party Id instead.
69      */

70     public static String JavaDoc getOpportunityAccountPartyId(GenericValue opportunity) throws GenericEntityException {
71         List JavaDoc candidates = opportunity.getRelatedByAnd("SalesOpportunityRole", UtilMisc.toMap("roleTypeId", "ACCOUNT"));
72         if (candidates.size() == 0) return null;
73         // we have two out of three primary keys, so the result is guaranteed to be the one with our partyId
74
GenericValue salesOpportunityRole = (GenericValue) candidates.get(0);
75         return salesOpportunityRole.getString("partyId");
76     }
77
78     /**
79      * Helper method to get the principal lead for an opportunity. This is a simplification of the
80      * datamodel and should only be calld for non-critical uses. Returns null if no lead was found,
81      * which would be the case if there were an account party Id instead.
82      */

83     public static String JavaDoc getOpportunityLeadPartyId(GenericValue opportunity) throws GenericEntityException {
84         List JavaDoc candidates = opportunity.getRelatedByAnd("SalesOpportunityRole", UtilMisc.toMap("roleTypeId", "PROSPECT"));
85         if (candidates.size() == 0) return null;
86         // we have two out of three primary keys, so the result is guaranteed to be the one with our partyId
87
GenericValue salesOpportunityRole = (GenericValue) candidates.get(0);
88         return salesOpportunityRole.getString("partyId");
89     }
90
91     /** Helper method to get the principal lead or account partyId of an opportunity. Use this to get one or the other. */
92     public static String JavaDoc getOpportunityAccountOrLeadPartyId(GenericValue opportunity) throws GenericEntityException {
93         List JavaDoc candidates = opportunity.getRelatedByAnd("SalesOpportunityRole", UtilMisc.toMap("roleTypeId", "ACCOUNT"));
94         if (candidates.size() > 0) return ((GenericValue) candidates.get(0)).getString("partyId");
95         candidates = opportunity.getRelatedByAnd("SalesOpportunityRole", UtilMisc.toMap("roleTypeId", "PROSPECT"));
96         if (candidates.size() > 0) return ((GenericValue) candidates.get(0)).getString("partyId");
97         return null;
98     }
99
100     /**
101      * Helper method to get all account party Id's for an opportunity. This is a more serious version of the above
102      * for use in critical logic, such as security or in complex methods that should use the whole list from the beginning.
103      */

104     public static List JavaDoc getOpportunityAccountPartyIds(GenericDelegator delegator, String JavaDoc salesOpportunityId) throws GenericEntityException {
105         return getOpportunityPartiesByRole(delegator, salesOpportunityId, "ACCOUNT");
106     }
107
108     /** Helper method to get all lead party Id's for an opportunity. See comments for getOpportunityAccountPartyIds(). */
109     public static List JavaDoc getOpportunityLeadPartyIds(GenericDelegator delegator, String JavaDoc salesOpportunityId) throws GenericEntityException {
110         return getOpportunityPartiesByRole(delegator, salesOpportunityId, "PROSPECT");
111     }
112
113     /** Helper method to get all contact party Id's for an opportunity. */
114     public static List JavaDoc getOpportunityContactPartyIds(GenericDelegator delegator, String JavaDoc salesOpportunityId) throws GenericEntityException {
115         return getOpportunityPartiesByRole(delegator, salesOpportunityId, "CONTACT");
116     }
117
118     /** Helper method to get all party Id's of a given role for an opportunity. It's better to use one of the more specific methods above. */
119     public static List JavaDoc getOpportunityPartiesByRole(GenericDelegator delegator, String JavaDoc salesOpportunityId, String JavaDoc roleTypeId) throws GenericEntityException {
120         List JavaDoc maps = delegator.findByAnd("SalesOpportunityRole", UtilMisc.toMap("roleTypeId", roleTypeId, "salesOpportunityId", salesOpportunityId));
121         List JavaDoc results = new ArrayList JavaDoc();
122         for (Iterator JavaDoc iter = maps.iterator(); iter.hasNext(); ) {
123             GenericValue map = (GenericValue) iter.next();
124             results.add(map.getString("partyId"));
125         }
126         return results;
127     }
128
129     /**
130      * Helper method to make a sales opportunity history, which should be done whenever an opp is created, updated or deleted.
131      * @return The created SalesOpportunityHistory
132      */

133     public static GenericValue createSalesOpportunityHistory(GenericValue opportunity, GenericDelegator delegator, Map JavaDoc context) throws GenericEntityException {
134         GenericValue userLogin = (GenericValue) context.get("userLogin");
135         String JavaDoc historyId = delegator.getNextSeqId("SalesOpportunityHistory");
136         GenericValue history = delegator.makeValue("SalesOpportunityHistory", UtilMisc.toMap("salesOpportunityHistoryId", historyId));
137
138         // we assume the opportunity has all fields set as desired already, especially the probability
139
history.setNonPKFields(opportunity.getAllFields());
140         history.set("changeNote", context.get("changeNote"));
141         history.set("modifiedByUserLogin", userLogin.getString("userLoginId"));
142         history.set("modifiedTimestamp", UtilDateTime.nowTimestamp());
143         history.create();
144         return history;
145     }
146
147     /**
148      * Returns all account and lead opportunities for an internalPartyId. This is done by looking for all opportunities
149      * belonging to accounts and leads that the internalPartyId is RESPONSIBLE_FOR.
150      *
151      * @param organizationPartyId - filter by organization TODO: not implemented
152      * @param internalPartyId - lookup opportunities for this party
153      * @param customTimePeriodId - if not null, will only get them for this time period
154      * @param additionalConditions - if not null, this EntityConditionList will be added as well
155      * @param orderBy - List of fields to order results by, can be null
156      * @param delegator
157      * @return
158      * @throws GenericEntityException
159      */

160     public static EntityListIterator getOpportunitiesForMyAccounts(String JavaDoc organizationPartyId, String JavaDoc internalPartyId, String JavaDoc customTimePeriodId,
161             EntityConditionList additionalConditions, List JavaDoc orderBy, GenericDelegator delegator)
162         throws GenericEntityException {
163         
164         // build condition to get list of PROSPECT or ACCOUNT opportunities that the user is RESPONSIBLE_FOR
165
List JavaDoc combinedConditions = UtilMisc.toList(
166                 new EntityExpr("partyIdTo", EntityOperator.EQUALS, internalPartyId),
167                 new EntityExpr("partyRelationshipTypeId", EntityOperator.EQUALS, "RESPONSIBLE_FOR"),
168                 new EntityConditionList( UtilMisc.toList(
169                         new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "PROSPECT"),
170                         new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "ACCOUNT")
171                         ), EntityOperator.OR),
172                 EntityUtil.getFilterByDateExpr()); // filter out expired accounts
173

174         return getOpportunitiesForPartyHelper(customTimePeriodId, combinedConditions, additionalConditions, orderBy, delegator);
175     }
176
177     /**
178      * As getOpportunitiesForMyAccounts but gets all account opportunities for all teams the party belongs to.
179      * Also includes lead opportunities that the internalPartyId is RESPONSIBLE_FOR.
180      */

181     public static EntityListIterator getOpportunitiesForMyTeams(String JavaDoc organizationPartyId, String JavaDoc internalPartyId, String JavaDoc customTimePeriodId,
182             EntityConditionList additionalConditions, List JavaDoc orderBy, GenericDelegator delegator) throws GenericEntityException {
183
184         // strategy: find all the accounts of the internalPartyId, then find all the opportunities of those accounts
185
EntityConditionList conditions = new EntityConditionList( UtilMisc.toList(
186                     new EntityExpr("partyIdTo", EntityOperator.EQUALS, internalPartyId),
187                     new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "ACCOUNT"),
188                     new EntityConditionList( UtilMisc.toList(
189                             new EntityExpr("partyRelationshipTypeId", EntityOperator.EQUALS, "RESPONSIBLE_FOR"),
190                             new EntityExpr("partyRelationshipTypeId", EntityOperator.EQUALS, "ASSIGNED_TO")
191                             ), EntityOperator.OR),
192                     EntityUtil.getFilterByDateExpr()
193                     ), EntityOperator.AND);
194         List JavaDoc accounts = delegator.findByCondition("PartyRelationship", conditions, null, null);
195         ArrayList JavaDoc accountIds = new ArrayList JavaDoc();
196         for (Iterator JavaDoc iter = accounts.iterator(); iter.hasNext(); ) {
197             GenericValue account = (GenericValue) iter.next();
198             accountIds.add(account.get("partyIdFrom"));
199         }
200
201         // if no accounts are found, then return a null
202
if (accountIds.size() < 1) {
203             return null;
204         }
205         
206         // build the condition to find opportunitied belonging to these accounts
207
List JavaDoc combinedConditions = UtilMisc.toList(
208                 new EntityExpr("partyIdFrom", EntityOperator.IN, accountIds),
209                 new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "ACCOUNT")
210                 );
211         
212         return getOpportunitiesForPartyHelper(customTimePeriodId, combinedConditions, additionalConditions, orderBy, delegator);
213     }
214
215     /**
216      * As getOpportunitiesForMyAccounts but returns Account and Lead opportunities that the internalPartyId is assigned to.
217      * Note that this is a superset of getOpportunitiesForMyAccounts, which returns the opportunities that the internalPartyId
218      * is directly responsible for. Use this method to get all opportunities that the internalPartyId can see.
219      */

220     public static EntityListIterator getOpportunitiesForInternalParty(String JavaDoc organizationPartyId, String JavaDoc internalPartyId, String JavaDoc customTimePeriodId,
221             EntityConditionList additionalConditions, List JavaDoc orderBy, GenericDelegator delegator)
222         throws GenericEntityException {
223         
224         // build condition to get list of ACCOUNT or PROSPECT opportunities for the supplied internal party
225
List JavaDoc combinedConditions = UtilMisc.toList(
226                 new EntityExpr("partyIdTo", EntityOperator.EQUALS, internalPartyId),
227                 new EntityConditionList( UtilMisc.toList(
228                         new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "ACCOUNT"),
229                         new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "PROSPECT")
230                         ), EntityOperator.OR),
231                 EntityUtil.getFilterByDateExpr()); // filter out expired accounts
232

233         return getOpportunitiesForPartyHelper(customTimePeriodId, combinedConditions, additionalConditions, orderBy, delegator);
234     }
235
236
237     private static EntityListIterator getOpportunitiesForPartyHelper(String JavaDoc customTimePeriodId, List JavaDoc combinedConditions,
238             EntityConditionList additionalConditions, List JavaDoc orderBy, GenericDelegator delegator) throws GenericEntityException {
239         // if a time period is supplied, use it as a condition as well
240
if ((customTimePeriodId != null)) {
241             GenericValue timePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", customTimePeriodId));
242             if (timePeriod != null) {
243                 combinedConditions.add(PeriodWorker.getFilterByPeriodExpr("estimatedCloseDate", timePeriod));
244             }
245         }
246         
247         // if additional conditions are passed in, add them as well
248
if (additionalConditions != null) {
249             combinedConditions.add(additionalConditions);
250         }
251         EntityConditionList conditionList = new EntityConditionList(combinedConditions, EntityOperator.AND);
252
253         // fields to select
254
List JavaDoc fields = UtilMisc.toList("salesOpportunityId", "partyIdFrom", "opportunityName", "opportunityStageId", "estimatedAmount", "estimatedCloseDate");
255         fields.add("estimatedProbability");
256         fields.add("currencyUomId");
257  
258         // get the SalesOpportunityAndRoles for these accounts
259
EntityListIterator opportunities = delegator.findListIteratorByCondition("PartyRelationshipAndSalesOpportunity", conditionList, null,
260                 fields,
261                 orderBy, // fields to order by (can't use fromDate here because it's part of multiple tables => need the alias.fromDate hack)
262
// the first true here is for "specifyTypeAndConcur"
263
// the second true is for a distinct select. Apparently this is the only way the entity engine can do a distinct query
264
new EntityFindOptions(true, EntityFindOptions.TYPE_SCROLL_INSENSITIVE, EntityFindOptions.CONCUR_READ_ONLY, true));
265
266         return opportunities;
267     }
268
269     /**
270      * Gets a List of team members for a given opportunity.
271      * @return List of GenericValue PartyToSummaryByRelationship for team members
272      */

273     public static List JavaDoc getOpportunityTeamMembers(String JavaDoc salesOpportunityId, GenericDelegator delegator) throws GenericEntityException {
274         // At this point, it is sufficient to traverse the directly related primary account
275
// We'll ignore accounts associated through related contacts for now.
276
GenericValue opportunity = delegator.findByPrimaryKey("SalesOpportunity", UtilMisc.toMap("salesOpportunityId", salesOpportunityId));
277         String JavaDoc accountPartyId = getOpportunityAccountPartyId(opportunity);
278
279         EntityConditionList conditions = new EntityConditionList(UtilMisc.toList(
280                 new EntityExpr("partyIdFrom", EntityOperator.EQUALS, accountPartyId),
281                 new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "ACCOUNT"),
282                 new EntityExpr("partyRelationshipTypeId", EntityOperator.EQUALS, "ASSIGNED_TO"),
283                 EntityUtil.getFilterByDateExpr()
284                 ), EntityOperator.AND);
285         return delegator.findByConditionCache("PartyToSummaryByRelationship", conditions, null, null);
286     }
287
288
289 }
290
Popular Tags