KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensourcestrategies > crmsfa > party > PartyHelper


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

41 package com.opensourcestrategies.crmsfa.party;
42
43 import java.util.Map JavaDoc;
44 import java.util.List JavaDoc;
45 import java.util.Iterator JavaDoc;
46 import java.sql.Timestamp JavaDoc;
47
48 import javolution.util.FastMap;
49
50 import org.ofbiz.base.util.Debug;
51 import org.ofbiz.base.util.UtilMisc;
52 import org.ofbiz.base.util.UtilDateTime;
53 import org.ofbiz.entity.GenericDelegator;
54 import org.ofbiz.entity.GenericEntityException;
55 import org.ofbiz.entity.GenericValue;
56 import org.ofbiz.entity.util.EntityUtil;
57 import org.ofbiz.service.DispatchContext;
58 import org.ofbiz.service.GenericServiceException;
59 import org.ofbiz.service.LocalDispatcher;
60 import org.ofbiz.service.ServiceUtil;
61 import org.ofbiz.security.Security;
62
63 /**
64  * Party Helper methods which are designed to provide a consistent set of APIs that can be reused by
65  * higher level services.
66  *
67  * @author <a HREF="mailto:leon@opensourcestrategies.com">Leon Torres</a>
68  * @version $Rev: 312 $
69  */

70
71 public class PartyHelper {
72
73     public static final String JavaDoc module = PartyHelper.class.getName();
74
75     public static List JavaDoc TEAM_MEMBER_ROLES = UtilMisc.toList("ACCOUNT_MANAGER", "ACCOUNT_REP", "CUST_SERVICE_REP");
76     public static List JavaDoc CLIENT_PARTY_ROLES = UtilMisc.toList("ACCOUNT", "CONTACT", "PROSPECT");
77
78     /**
79      * A helper method which finds the first valid roleTypeId for a partyId, using a List of possible roleTypeIds
80      *
81      * @param partyId
82      * @param possibleRoleTypeIds a List of roleTypeIds
83      * @param delegator
84      * @return the first roleTypeId from possibleRoleTypeIds which is actually found in PartyRole for the given partyId
85      * @throws GenericEntityException
86      */

87     public static String JavaDoc getFirstValidRoleTypeId(String JavaDoc partyId, List JavaDoc possibleRoleTypeIds, GenericDelegator delegator) throws GenericEntityException {
88
89         List JavaDoc partyRoles = delegator.findByAndCache("PartyRole", UtilMisc.toMap("partyId", partyId));
90
91         // iterate across all possible roleTypeIds from the parameter
92
Iterator JavaDoc iterValid = possibleRoleTypeIds.iterator();
93         while (iterValid.hasNext()) {
94             String JavaDoc possibleRoleTypeId = (String JavaDoc) iterValid.next();
95
96             // try to look for each one in the list of PartyRoles
97
Iterator JavaDoc partyRolesIter = partyRoles.iterator();
98             while (partyRolesIter.hasNext()) {
99                 GenericValue partyRole = (GenericValue) partyRolesIter.next();
100                 if (possibleRoleTypeId.equals(partyRole.getString("roleTypeId"))) {
101                     return possibleRoleTypeId;
102                 }
103             }
104         }
105         return null;
106     }
107     
108     /**
109      * As above, but pass in the list of internal party roles, such as ACCOUNT, CONTACT, PROSPECT
110      */

111     public static String JavaDoc getFirstValidInternalPartyRoleTypeId(String JavaDoc partyId, GenericDelegator delegator) throws GenericEntityException {
112         return getFirstValidRoleTypeId(partyId, CLIENT_PARTY_ROLES, delegator);
113     }
114     
115     /**
116      * As above, but pass in the list of team member roles such as ACCOUNT_REP, etc.
117      */

118     public static String JavaDoc getFirstValidTeamMemberRoleTypeId(String JavaDoc partyId, GenericDelegator delegator) throws GenericEntityException {
119         return getFirstValidRoleTypeId(partyId, TEAM_MEMBER_ROLES, delegator);
120     }
121     
122     /**
123      * A helper method for creating a PartyRelationship entity from partyIdTo to partyIdFrom with specified partyRelationshipTypeId, roleTypeIdFrom,
124      * a List of valid roles for the to-party, and a flag to expire any existing relationships between the two parties of the same
125      * type. The idea is that several services would do validation and then use this method to do all the work.
126      *
127      * @param partyIdTo
128      * @param partyIdFrom
129      * @param roleTypeIdFrom
130      * @param partyRelationshipTypeId
131      * @param securityGroupId
132      * @param validToPartyRoles List of roleTypeIds which are valid for the partyIdTo in the create relationship. It will cycle
133      * through until the first of these roles is actually associated with partyIdTo and then create a PartyRelationship using that
134      * roleTypeId. If none of these are associated with partyIdTo, then it will return false
135      * @param fromDate
136      * @param expireExistingRelationships If set to true, will look for all existing PartyRelationships of partyIdFrom, partyRelationshipTypeId
137      * and expire all of them as of the passed in fromDate
138      * @return false if no relationship was created or true if operation succeeds
139      */

140     public static boolean createNewPartyToRelationship(String JavaDoc partyIdTo, String JavaDoc partyIdFrom, String JavaDoc roleTypeIdFrom,
141             String JavaDoc partyRelationshipTypeId, String JavaDoc securityGroupId, List JavaDoc validToPartyRoles, Timestamp JavaDoc fromDate,
142             boolean expireExistingRelationships, GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher)
143         throws GenericEntityException, GenericServiceException {
144
145         // get the first valid roleTypeIdTo from a list of possible roles for the partyIdTo
146
// this will be the role we use as roleTypeIdTo in PartyRelationship.
147
String JavaDoc roleTypeIdTo = getFirstValidRoleTypeId(partyIdTo, validToPartyRoles, delegator);
148         
149         // if no matching roles were found, then no relationship created
150
if (roleTypeIdTo == null) return false;
151
152         /*
153          * if expireExistingRelationships is true, then find all existing PartyRelationships with partyIdFrom and partyRelationshipTypeId which
154          * are not expired on the fromDate and then expire them
155          */

156         if (expireExistingRelationships == true) {
157             List JavaDoc partyRelationships = delegator.findByAnd("PartyRelationship", UtilMisc.toMap("partyIdFrom", partyIdFrom, "partyRelationshipTypeId", partyRelationshipTypeId));
158             expirePartyRelationships(partyRelationships, fromDate, dispatcher, userLogin);
159         }
160
161         // call createPartyRelationship service to create PartyRelationship using parameters and the role we just found
162
Map JavaDoc input = UtilMisc.toMap("partyIdTo", partyIdTo, "roleTypeIdTo", roleTypeIdTo, "partyIdFrom", partyIdFrom, "roleTypeIdFrom", roleTypeIdFrom);
163         input.put("partyRelationshipTypeId", partyRelationshipTypeId);
164         input.put("securityGroupId", securityGroupId);
165         input.put("fromDate", fromDate);
166         input.put("userLogin", userLogin);
167         Map JavaDoc serviceResult = dispatcher.runSync("createPartyRelationship", input);
168
169         // on success return true
170
return true;
171     }
172
173     /**
174      * Same as above except uses a default of now for the timestamp
175      */

176     public static boolean createNewPartyToRelationship(String JavaDoc partyIdTo, String JavaDoc partyIdFrom, String JavaDoc roleTypeIdFrom,
177             String JavaDoc partyRelationshipTypeId, String JavaDoc securityGroupId, List JavaDoc validToPartyRoles,
178             boolean expireExistingRelationships, GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher)
179         throws GenericEntityException, GenericServiceException {
180         return createNewPartyToRelationship(partyIdTo, partyIdFrom, roleTypeIdFrom,
181                 partyRelationshipTypeId, securityGroupId, validToPartyRoles, UtilDateTime.nowTimestamp(),
182                 expireExistingRelationships, userLogin, delegator, dispatcher);
183     }
184
185     /**
186      * Expires a list of PartyRelationships that are still active on expireDate.
187      */

188     public static void expirePartyRelationships(List JavaDoc partyRelationships, Timestamp JavaDoc expireDate, LocalDispatcher dispatcher, GenericValue userLogin)
189         throws GenericServiceException {
190         List JavaDoc relationsActiveOnFromDate = EntityUtil.filterByDate(partyRelationships, expireDate);
191
192         // to expire on expireDate, set the thruDate to the expireDate in the parameter and call updatePartyRelationship service
193
Iterator JavaDoc iter = relationsActiveOnFromDate.iterator();
194         while (iter.hasNext()) {
195             GenericValue partyRelationship = (GenericValue) iter.next();
196             Map JavaDoc input = UtilMisc.toMap("partyIdTo", partyRelationship.getString("partyIdTo"), "roleTypeIdTo", partyRelationship.getString("roleTypeIdTo"),
197                     "partyIdFrom", partyRelationship.getString("partyIdFrom"), "roleTypeIdFrom", partyRelationship.getString("roleTypeIdFrom"));
198             input.put("fromDate", partyRelationship.getTimestamp("fromDate"));
199             input.put("userLogin", userLogin);
200             input.put("thruDate", expireDate);
201             Map JavaDoc serviceResult = dispatcher.runSync("updatePartyRelationship", input);
202             if (ServiceUtil.isError(serviceResult)) {
203                 throw new GenericServiceException("Failed to expire PartyRelationship with values: " + input.toString());
204             }
205         }
206     }
207
208     /**
209      * Method to get the current non-expired party responsible for the given account/contact/lead.
210      *
211      * @param partyIdFrom The partyId of the account/contact/lead
212      * @param roleTypeIdFrom The role of the account/contact/lead (e.g., ACCOUNT, CONTACT, LEAD)
213      * @return First non-expired PartySummaryCRMView or null if none found
214      */

215     public static GenericValue getCurrentResponsibleParty(String JavaDoc partyIdFrom, String JavaDoc roleTypeIdFrom, GenericDelegator delegator) throws GenericEntityException {
216         return getActivePartyByRole("RESPONSIBLE_FOR", partyIdFrom, roleTypeIdFrom, UtilDateTime.nowTimestamp(), delegator);
217     }
218
219     /** Method to get the current lead owner of a lead */
220     public static GenericValue getCurrentLeadOwner(String JavaDoc leadPartyId, GenericDelegator delegator) throws GenericEntityException {
221         return getActivePartyByRole("RESPONSIBLE_FOR", leadPartyId, "PROSPECT", "LEAD_OWNER", UtilDateTime.nowTimestamp(), delegator);
222     }
223
224     /**
225      * Common method used by getCurrentlyResponsibleParty and related methods. This method will obtain the first PartyRelationship found with the given criteria
226      * and return the PartySummaryCRMView with partyId = partyRelationship.partyIdTo.
227      *
228      * @param partyRelationshipTypeId The party relationship (e.g., reps that are RESPONSIBLE_FOR an account)
229      * @param partyIdFrom The partyId of the account/contact/lead
230      * @param roleTypeIdFrom The role of the account/contact/lead (e.g., ACCOUNT, CONTACT, LEAD)
231      * @param securityGroupId Optional securityGroupId of the relationsihp
232      * @param activeDate Check only for active relationships as of this timestamp
233      * @return First non-expired PartySummaryCRMView or null if none found
234      */

235     public static GenericValue getActivePartyByRole(String JavaDoc partyRelationshipTypeId, String JavaDoc partyIdFrom, String JavaDoc roleTypeIdFrom, String JavaDoc securityGroupId,
236             Timestamp JavaDoc activeDate, GenericDelegator delegator)
237         throws GenericEntityException {
238
239         Map JavaDoc input = UtilMisc.toMap("partyRelationshipTypeId", partyRelationshipTypeId, "partyIdFrom", partyIdFrom, "roleTypeIdFrom", roleTypeIdFrom);
240         if (securityGroupId != null) input.put("securityGroupId", securityGroupId);
241         List JavaDoc relationships = delegator.findByAnd("PartyRelationship", input);
242         List JavaDoc activeRelationships = EntityUtil.filterByDate(relationships, activeDate);
243
244         // if none are found, log a message about this and return null
245
if (activeRelationships.size() == 0) {
246             Debug.logInfo("No active PartyRelationships found with relationship [" + partyRelationshipTypeId + "] for party ["
247                     + partyIdFrom +"] in role [" + roleTypeIdFrom +"]", module);
248             return null;
249         }
250
251         // return the related party with partyId = partyRelationship.partyIdTo
252
GenericValue partyRelationship = (GenericValue) activeRelationships.get(0);
253         return delegator.findByPrimaryKey("PartySummaryCRMView", UtilMisc.toMap("partyId", partyRelationship.getString("partyIdTo")));
254     }
255
256     /** As above but without security group Id specified */
257     public static GenericValue getActivePartyByRole(String JavaDoc partyRelationshipTypeId, String JavaDoc partyIdFrom, String JavaDoc roleTypeIdFrom,
258             Timestamp JavaDoc activeDate, GenericDelegator delegator)
259         throws GenericEntityException {
260         return getActivePartyByRole(partyRelationshipTypeId, partyIdFrom, roleTypeIdFrom, null, activeDate, delegator);
261     }
262
263     /**
264      * Method to copy all "To" relationships of a From party to another From party. For instance, use this method to copy all relationships of an
265      * account (or optionally a specific relationship), such as the managers and reps, over to a team.
266      * NOTE: This service works on unexpired relationships as of now and will need to be refactored for other Dates.
267      * TODO: skip dupes
268      *
269      * @param partyIdFrom
270      * @param roleTypeIdFrom
271      * @param partyRelationshipTypeId optional
272      * @param newPartyIdFrom
273      * @param newRoleTypeIdFrom
274      */

275     public static void copyToPartyRelationships(String JavaDoc partyIdFrom, String JavaDoc roleTypeIdFrom, String JavaDoc partyRelationshipTypeId,
276             String JavaDoc newPartyIdFrom, String JavaDoc newRoleTypeIdFrom, GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher)
277         throws GenericEntityException, GenericServiceException {
278
279         // hardcoded activeDate
280
Timestamp JavaDoc activeDate = UtilDateTime.nowTimestamp();
281
282         // first get the unexpired relationships for the From party
283
Map JavaDoc input = UtilMisc.toMap("partyIdFrom", partyIdFrom, "roleTypeIdFrom", roleTypeIdFrom);
284         if (partyRelationshipTypeId != null) input.put("partyRelationshipTypeId", partyRelationshipTypeId);
285         List JavaDoc relationships = delegator.findByAnd("PartyRelationship", input);
286         List JavaDoc activeRelationships = EntityUtil.filterByDate(relationships, activeDate);
287
288         for (Iterator JavaDoc iter = activeRelationships.iterator(); iter.hasNext();) {
289             GenericValue relationship = (GenericValue) iter.next();
290
291             // create the relationship
292
input = UtilMisc.toMap("partyIdTo", relationship.getString("partyIdTo"), "roleTypeIdTo", relationship.getString("roleTypeIdTo"));
293             input.put("partyIdFrom", newPartyIdFrom);
294             input.put("roleTypeIdFrom", newRoleTypeIdFrom);
295             input.put("partyRelationshipTypeId", relationship.getString("partyRelationshipTypeId"));
296             input.put("securityGroupId", relationship.getString("securityGroupId"));
297             input.put("fromDate", relationship.getTimestamp("fromDate"));
298             input.put("thruDate", relationship.getTimestamp("thruDate"));
299             input.put("statusId", relationship.getString("statusId"));
300             input.put("priorityTypeId", relationship.getString("priorityTypeId"));
301             input.put("comments", relationship.getString("comments"));
302             input.put("userLogin", userLogin);
303             Map JavaDoc serviceResult = dispatcher.runSync("createPartyRelationship", input);
304             if (ServiceUtil.isError(serviceResult)) {
305                 throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResult));
306             }
307         }
308     }
309
310     /**
311      * Same as above, but passes partyRelationshipTypeId = null so that all relationship types are selected.
312      */

313     public static void copyToPartyRelationships(String JavaDoc partyIdFrom, String JavaDoc roleTypeIdFrom, String JavaDoc newPartyIdFrom, String JavaDoc newRoleTypeIdFrom,
314             GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher)
315         throws GenericEntityException, GenericServiceException {
316
317         copyToPartyRelationships(partyIdFrom, roleTypeIdFrom, null, newPartyIdFrom, newRoleTypeIdFrom, userLogin, delegator, dispatcher);
318     }
319
320     /**
321      * This array determines the entities in which to delete the party and the order of deletion.
322      * Party should be the very last element. The second element in each row denotes the partyId
323      * field to check. XXX Note: We are deleting historical data. For instance, activity records
324      * involving the partyId will be gone forever!
325      */

326     private static String JavaDoc[][] CRM_PARTY_DELETE_CASCADE = {
327         {"CustRequestRole", "partyId"},
328         {"PartyNote", "partyId"},
329         {"PartyDataSource", "partyId"},
330         {"WorkEffortPartyAssignment", "partyId"},
331         {"PartyContactMechPurpose", "partyId"},
332         {"PartyContactMech", "partyId"},
333         {"PartySupplementalData", "partyId"},
334         {"PartyNameHistory", "partyId"},
335         {"PartyGroup", "partyId"},
336         {"PartyRelationship", "partyIdFrom"},
337         {"PartyRelationship", "partyIdTo"},
338         {"Person", "partyId"},
339         {"PartyRole", "partyId"},
340         {"PartyStatus", "partyId"},
341         {"Party", "partyId"}
342     };
343
344     /**
345      * Performs a cascade delete on a party.
346      *
347      * One reason this method can fail is that there were relationships with entities that are not being deleted.
348      * If a party is not being deleted like it should, the developer should take a look at the exception thrown
349      * by this method to see if any relations were violated. If there were violations, consider adding
350      * the entities to the CASCADE array above.
351      *
352      * XXX Warning, this method is very brittle. It is essentially emulating the ON DELETE CASCADE functionality
353      * of well featured databases, but very poorly. As the datamodel evolves, this method would have to be updatd.
354      */

355     public static void deleteCrmParty(String JavaDoc partyId, GenericDelegator delegator) throws GenericEntityException {
356         for (int i = 0; i < CRM_PARTY_DELETE_CASCADE.length; i++) {
357             String JavaDoc entityName = CRM_PARTY_DELETE_CASCADE[i][0];
358             String JavaDoc fieldName = CRM_PARTY_DELETE_CASCADE[i][1];
359
360             Map JavaDoc input = UtilMisc.toMap(fieldName, partyId);
361             delegator.removeByAnd(entityName, input);
362         }
363     }
364 }
365
Popular Tags