/*
*
* Copyright (c) 2004 SourceTap - www.sourcetap.com
*
* The contents of this file are subject to the SourceTap Public License
* ("License"); You may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.sourcetap.com/license.htm
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
*/
package com.sourcetap.sfa.contact;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.model.ModelEntity;
import com.sourcetap.sfa.address.AddressHelper;
import com.sourcetap.sfa.attachment.AbstractAttachmentEP;
import com.sourcetap.sfa.event.DataMatrix;
import com.sourcetap.sfa.event.GenericEventProcessor;
import com.sourcetap.sfa.replication.GenericReplicator;
import com.sourcetap.sfa.ui.UIScreenSectionEntity;
import com.sourcetap.sfa.util.QueryInfo;
import com.sourcetap.sfa.util.UserInfo;
import com.sourcetap.sfa.security.SecurityLinkInfo;
/**
* DOCUMENT ME!
*
*/
public class ContactEventProcessor extends GenericEventProcessor {
public static final String module = ContactEventProcessor.class.getName();
/**
* DOCUMENT ME!
*
* @param userInfo
* @param delegator
* @param dataMatrix
*
* @return
*/
protected int preUpdate(UserInfo userInfo, GenericDelegator delegator,
DataMatrix dataMatrix) {
// Just process the first row for now.
GenericValue contactGV = null;
GenericValue addressGV = null;
GenericValue partyGV = null;
GenericValue userLoginGV = null;
try {
contactGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"Contact", true);
addressGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"Address", false);
partyGV = dataMatrix.getCurrentBuffer().getGenericValue(0, "Party",
false);
userLoginGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"UserLogin", false);
} catch (GenericEntityException e) {
Debug.logError(
"[ContactEventProcessor.preUpdate] Error getting generic value: " +
e.toString(), module);
return STATUS_ERROR;
}
// Copy the contact ID to the address owner ID in case it is not already filled in.
String contactId = contactGV.getString("contactId");
Timestamp now = new Timestamp(Calendar.getInstance().getTime().getTime());
setNameFields( contactGV );
// Update the address if it is new.
String addressId = addressGV.getString("addressId");
if ((addressId == null) || addressId.equals("")) {
addressId = GenericReplicator.getNextSeqId("Address", delegator);
addressGV.set("addressId", addressId);
addressGV.set("addressOwnerId", contactId);
addressGV.set("addressOwnerType", "Contact");
addressGV.set("isPrimary", "Y");
addressGV.set("createdDate", now);
addressGV.set("createdBy", userInfo.getPartyId());
String mailingAddress = AddressHelper.getMailingAddress( addressGV.getString("mailingAddress"), addressGV.getString("address1"), addressGV.getString("address2"), addressGV.getString("address3"));
addressGV.set("mailingAddress", mailingAddress);
}
// Copy the contact ID to the user Login Party ID in case it is not already filled in.
userLoginGV.set("partyId", contactId);
// Set the time stamps.
contactGV.set("modifiedDate", now);
addressGV.set("modifiedDate", now);
// Store the current user ID in the "modified by" field.
contactGV.set("modifiedBy", userInfo.getPartyId());
addressGV.set("modifiedBy", userInfo.getPartyId());
// Set the contact owner ID if it is empty.
String contactOwnerId = contactGV.getString("contactOwnerId");
if ((contactOwnerId == null) || contactOwnerId.equals("")) {
Debug.logVerbose("Setting contactOwnerId to " +
userInfo.getPartyId(), module);
contactGV.set("contactOwnerId", userInfo.getPartyId());
}
return STATUS_CONTINUE;
}
/** event handler for quick insert screen */
public boolean QuickInsert(UserInfo userInfo, GenericDelegator delegator,
String firstName, String lastName, String userLogin, String userPassword) {
GenericValue contactGV = new GenericValue(delegator.getModelEntity(
"Contact"));
contactGV.setDelegator(delegator);
GenericValue addressGV = new GenericValue(delegator.getModelEntity(
"Address"));
addressGV.setDelegator(delegator);
GenericValue partyGV = new GenericValue(delegator.getModelEntity(
"Party"));
partyGV.setDelegator(delegator);
GenericValue userLoginGV = new GenericValue(delegator.getModelEntity(
"UserLogin"));
userLoginGV.setDelegator(delegator);
GenericValue partyRoleGV = new GenericValue(delegator.getModelEntity(
"PartyRole"));
partyRoleGV.setDelegator(delegator);
contactGV.set("firstName", firstName);
contactGV.set("lastName", lastName);
contactGV.set("accountId", userInfo.getAccountId());
setNameFields( contactGV );
contactGV.set("contactTypeId", "user");
userLoginGV.set("userLoginId", userLogin);
userLoginGV.set("currentPassword", userPassword);
DataMatrix dataMatrix = new DataMatrix(delegator, new Vector());
dataMatrix.getCurrentBuffer().addContentsRow(new Vector());
dataMatrix.addEntity("Contact", false, true);
dataMatrix.getCurrentBuffer().getContentsRow(0).add(contactGV);
dataMatrix.addEntity("Address", false, true);
dataMatrix.getCurrentBuffer().getContentsRow(0).add(addressGV);
dataMatrix.addEntity("Party", false, true);
dataMatrix.getCurrentBuffer().getContentsRow(0).add(partyGV);
dataMatrix.addEntity("UserLogin", false, true);
dataMatrix.getCurrentBuffer().getContentsRow(0).add(userLoginGV);
if (preInsert(userInfo, delegator, dataMatrix) != STATUS_CONTINUE) {
return false;
}
if ( (userLogin != null) && (userLogin.length() > 0))
{
try {
partyGV =dataMatrix.getCurrentBuffer().getGenericValue(0, "Party", true);
} catch (GenericEntityException e) {
Debug.logError(
"[ContactEventProcessor.QuickInsert] Error getting generic value: " +
e.getLocalizedMessage(), module);
return false;
}
partyRoleGV.set("partyId", partyGV.getString("partyId"));
partyRoleGV.set("roleTypeId", "SFA_USER");
dataMatrix.addEntity("PartyRole", false, true);
dataMatrix.getCurrentBuffer().getContentsRow(0).add(partyRoleGV);
}
try {
delegator.storeAll((List) dataMatrix.getCurrentBuffer()
.getContentsRow(0));
} catch (GenericEntityException e2) {
Debug.logError(
"[ContactEventProcessor.QuickInsert] Error updating: " +
e2.getLocalizedMessage(), module);
return false;
}
return true;
}
/**
* DOCUMENT ME!
*
* @param userInfo
* @param delegator
* @param dataMatrix
*
* @return
*/
protected int preInsert(UserInfo userInfo, GenericDelegator delegator,
DataMatrix dataMatrix) {
// Just process the first row for now.
GenericValue contactGV = null;
GenericValue addressGV = null;
GenericValue partyGV = null;
GenericValue userLoginGV = null;
try {
contactGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"Contact", true);
addressGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"Address", false);
partyGV = dataMatrix.getCurrentBuffer().getGenericValue(0, "Party",
false);
userLoginGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"UserLogin", false);
} catch (GenericEntityException e) {
Debug.logError(
"[ContactEventProcessor.preInsert] Error getting generic value: " +
e.getLocalizedMessage(), module);
return STATUS_ERROR;
}
// Generate new keys for the contact and address.
String contactId = GenericReplicator.getNextSeqId("Party", delegator);
String addressId = GenericReplicator.getNextSeqId("Address", delegator);
contactGV.set("contactId", contactId);
addressGV.set("addressId", addressId);
addressGV.set("addressOwnerId", contactId);
addressGV.set("addressOwnerType", "Contact");
partyGV.set("partyId", contactId);
userLoginGV.set("partyId", contactId);
String mailingAddress = AddressHelper.getMailingAddress( addressGV.getString("mailingAddress"), addressGV.getString("address1"), addressGV.getString("address2"), addressGV.getString("address3"));
addressGV.set("mailingAddress", mailingAddress);
setNameFields( contactGV );
// Make this address the primary one for the contact.
addressGV.set("isPrimary", "Y");
Date hireDate = contactGV.getDate("hireDate");
if (hireDate == null) {
contactGV.set("hireDate",
new Timestamp(Calendar.getInstance().getTime().getTime()));
}
// Set the time stamps.
Timestamp now = new Timestamp(Calendar.getInstance().getTime().getTime());
contactGV.set("createdDate", now);
addressGV.set("createdDate", now);
contactGV.set("modifiedDate", now);
addressGV.set("modifiedDate", now);
// Store the current user ID in the "modified by" field.
contactGV.set("createdBy", userInfo.getPartyId());
addressGV.set("createdBy", userInfo.getPartyId());
contactGV.set("modifiedBy", userInfo.getPartyId());
addressGV.set("modifiedBy", userInfo.getPartyId());
// Set the contact owner ID if it is empty.
String contactOwnerId = contactGV.getString("contactOwnerId");
if ((contactOwnerId == null) || contactOwnerId.equals("")) {
contactGV.set("contactOwnerId", userInfo.getPartyId());
}
//Set the account ID if it is empty. This should only be the case if it is an employee created thru quick create
String accountId = contactGV.getString("accountId");
if ((accountId == null) || accountId.equals("")) {
contactGV.set("accountId", userInfo.getAccountId());
}
return STATUS_CONTINUE;
}
/**
* DOCUMENT ME!
*
* @param userInfo
* @param entityNameList
* @param delegator
* @param dataMatrix
*
* @return
*/
protected int postCreate(UserInfo userInfo, List entityNameList,
GenericDelegator delegator, DataMatrix dataMatrix) {
// Get the empty generic values.
GenericValue contactGV = null;
GenericValue addressGV = null;
GenericValue partyGV = null;
GenericValue userLoginGV = null;
try {
contactGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"Contact", true);
addressGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"Address", false);
partyGV = dataMatrix.getCurrentBuffer().getGenericValue(0, "Party",
false);
userLoginGV = dataMatrix.getCurrentBuffer().getGenericValue(0,
"UserLogin", false);
} catch (GenericEntityException e) {
Debug.logError(
"[ContactEventProcessor.postCreate] Error getting generic value: " +
e.toString(), module);
return STATUS_ERROR;
}
// Set default values on the new record so they will be displayed for the user to see before saving.
// Contact owner ID
contactGV.set("contactOwnerId", userInfo.getPartyId());
// Status
contactGV.set("statusId", "A");
// Contact Type
contactGV.set("contactTypeId", "regular");
// Country
addressGV.set("country", "USA");
// Refresh the cache in the delegator so that dropdowns will show the new contact
delegator.getAndCache().clear();
return STATUS_CONTINUE;
}
/**
* DOCUMENT ME!
*
* @param userInfo
* @param delegator
* @param originatingEntityName
* @param entityGV
*
* @return
*/
public int deleteAllRelated(UserInfo userInfo, GenericDelegator delegator,
String originatingEntityName, GenericValue entityGV) {
int status = STATUS_CONTINUE;
// Delete related ActivityContacts.
status = deleteOneRelated(userInfo, delegator, entityGV, "",
"ActivityContact", originatingEntityName,
new GenericEventProcessor());
if (status != STATUS_CONTINUE) {
return status;
}
// Delete related Addresses.
status = deleteOneRelated(userInfo, delegator, entityGV, "", "Address",
originatingEntityName, new GenericEventProcessor());
if (status != STATUS_CONTINUE) {
return status;
}
// Delete related Parties.
status = deleteOneRelated(userInfo, delegator, entityGV, "", "Party",
originatingEntityName, new GenericEventProcessor());
if (status != STATUS_CONTINUE) {
return status;
}
// Delete related UserLogins.
status = deleteOneRelated(userInfo, delegator, entityGV, "",
"UserLogin", originatingEntityName, new GenericEventProcessor());
if (status != STATUS_CONTINUE) {
return status;
}
// Delete related OpportunityContacts.
status = deleteOneRelated(userInfo, delegator, entityGV, "",
"OpportunityContact", originatingEntityName,
new GenericEventProcessor());
if (status != STATUS_CONTINUE) {
return status;
}
// Delete related FileAttachments. (Note: This must happen before the ContactFiles are deleted.)
status = deleteOneRelated(userInfo, delegator, entityGV, "",
"FileAttachment", originatingEntityName,
new AbstractAttachmentEP());
if (status != STATUS_CONTINUE) {
return status;
}
// Delete related ContactFiles. (Note: This must happen after the FileAttachments are deleted.)
status = deleteOneRelated(userInfo, delegator, entityGV, "",
"ContactFile", originatingEntityName,
new GenericEventProcessor());
if (status != STATUS_CONTINUE) {
return status;
}
// Find any activities whose contactId field has the current contactId in it, and change the contactId to null.
List activityGVL = super.findOneRelated(userInfo, delegator, entityGV,
"", "Activity");
Iterator activityGVI = activityGVL.iterator();
while (activityGVI.hasNext()) {
GenericValue activityGV = (GenericValue) activityGVI.next();
String activityId = activityGV.getString("activityId");
activityGV.set("contactId", null);
try {
activityGV.store();
} catch (GenericEntityException e) {
Debug.logError(
"[ContactEventProcessor.deleteAllRelated] Error clearing the contact ID field on " +
"a related activity during delete of a contact: " +
e.getLocalizedMessage(), module);
}
}
return STATUS_CONTINUE;
}
/**
* DOCUMENT ME!
*
* @param userInfo
* @param delegator
* @param entityGV
* @param relationTitle
* @param relatedEntityName
*
* @return
*/
public List findOneRelated(UserInfo userInfo, GenericDelegator delegator,
GenericValue entityGV, String relationTitle, String relatedEntityName) {
// Find instances of an entity related to the current entity so the instances can be deleted.
if (relatedEntityName.equals("FileAttachment")) {
// Finding related FileAttachment records. Need special processing because the relationship cannot be
// defined in the sfa-config.xml file.
// Get all the related ContactFile records using the generic version of findOneRelated.
List contactFileGVL = super.findOneRelated(userInfo, delegator,
entityGV, "", "ContactFile");
// Make a List of FileAttachments tied to the identified ContactFiles.
List fileAttachmenGVL = new LinkedList();
Iterator contactFileGVI = contactFileGVL.iterator();
while (contactFileGVI.hasNext()) {
GenericValue contactFileGV = (GenericValue) contactFileGVI.next();
try {
GenericValue fileAttachmentGV = delegator.getRelatedOne("FileAttachment",
contactFileGV);
if (fileAttachmentGV != null) {
fileAttachmenGVL.add(fileAttachmentGV);
}
} catch (GenericEntityException e) {
Debug.logError(
"[ContactEventProcessor.findOneRelated] Error retrieving FileAttachment record: " +
e.getLocalizedMessage(), module);
}
}
return fileAttachmenGVL;
} else {
// Not finding EntityAccess or FileAttachment records. Just use the standard processing using relations.
return super.findOneRelated(userInfo, delegator, entityGV,
relationTitle, relatedEntityName);
}
}
/**
* DOCUMENT ME!
*
* @param mainGV
* @param relatedSearchClause
* @param outGVV
* @param userInfo
* @param delegator
*
* @return
*/
protected GenericValue retrieveOneRelatedGV(GenericValue mainGV,
UIScreenSectionEntity relatedSearchClause, Vector outGVV, UserInfo userInfo,
GenericDelegator delegator) {
String relationRelEntityName = (String) relatedSearchClause.getEntityName();
if (relationRelEntityName.equals("Address")) {
// Special processing for the Address record since it can't be retrieved with a relationship
// defined in the sfa-config.xml file.
// Get Contact ID from the Contact record.
String contactId = mainGV.getString("contactId");
HashMap addressFindMap = new HashMap();
addressFindMap.put("addressOwnerId", contactId);
addressFindMap.put("isPrimary", "Y");
GenericValue addressGV = null;
try {
List addressGVL = delegator.findByAnd("Address", addressFindMap);
Iterator addressGVI = addressGVL.iterator();
if (addressGVI.hasNext()) {
// Address record was found.
addressGV = (GenericValue) addressGVI.next();
} else {
// Address record was not found. Allow generic event processor to create an empty one.
}
return addressGV;
} catch (GenericEntityException e) {
Debug.logError(
"[ContactEventProcessor.retrieveOneRelatedGV] An error occurred while searching for " +
"the address record for the Contact: " +
e.getLocalizedMessage(), module);
return addressGV;
}
} else {
// Retrieve all other related entities the regular way.
return super.retrieveOneRelatedGV(mainGV, relatedSearchClause,
outGVV, userInfo, delegator);
}
}
/**
* Add entity clauses for one related entity. This will join related tables to the query
* during a retrieve so query values can be entered that are in related entities.
* <P>
* This version overrides the ancestor to handle the Account entity, which
* has no relation defined.
*
* @author <a href='mailto:jnutting@sourcetap.com'>John Nutting</a>
*
* @param delegator Reference to the OFBIZ delegator being used to connect to the data base
* @param relationTitle Relation title
* @param relatedEntityName Name of related entity
* @param primaryEntityName Name of the primary entity
* @param primaryME ModelEntity object for the primary entity
* @param queryInfo criteria to be used in search.
*/
public void addOneRelationClause(GenericDelegator delegator,
String relationTitle, String relatedAndFields, String relatedEntityName,
String primaryEntityName, ModelEntity primaryME, boolean isOuterJoin, QueryInfo queryInfo)
throws GenericEntityException {
if (relatedEntityName.equals("Address")) {
// Adding entity clauses for the Address entity. Need to build it manually.
// Join the address owner ID field
queryInfo.addJoin("Contact", "Address", Boolean.valueOf(isOuterJoin), "contactId", "addressOwnerId");
if ( isOuterJoin )
{
queryInfo.addAlias("Address", "isPrimary", "isPrimary");
queryInfo.addAlias("Address", "addressId", "addressId");
queryInfo.addCondition( new EntityConditionList( UtilMisc.toList( new EntityExpr("isPrimary", EntityOperator.EQUALS, "Y"),
new EntityExpr("addressId", EntityOperator.EQUALS, null)), EntityOperator.OR));
}
else
queryInfo.addCondition("Address", "isPrimary", EntityOperator.EQUALS, "Y");
} else {
// Use the parent script for all other related entities.
super.addOneRelationClause(delegator, relationTitle, relatedAndFields,
relatedEntityName, primaryEntityName, primaryME, isOuterJoin, queryInfo);
}
}
public static void setNameFields( GenericValue contactGV )
{
String firstName = UtilFormatOut.checkNull(contactGV.getString("firstName"));
String lastName = UtilFormatOut.checkNull(contactGV.getString("lastName"));
String prefix = UtilFormatOut.checkNull(contactGV.getString("prefix"));
String suffix = UtilFormatOut.checkNull(contactGV.getString("suffix"));
String profSuffix = UtilFormatOut.checkNull(contactGV.getString("profSuffix"));
String fullName = UtilFormatOut.checkNull(contactGV.getString("fullName"));;
if ( (lastName.length() == 0) && ( fullName.length() > 0) )
{
lastName = fullName;
contactGV.set("lastName", lastName);
} else
{
String flds[] = { prefix, firstName, lastName, suffix, profSuffix };
fullName = "";
for ( int i=0; i < flds.length; i++)
{
if ( flds[i].length() > 0 )
{
if ( fullName.length() > 0)
fullName = fullName + " " + flds[i];
else
fullName = flds[i];
}
}
contactGV.set("fullName", fullName);
}
}
/**
* DOCUMENT ME!
*
* @param userInfo
* @param delegator
*
* @return
*/
public SecurityLinkInfo getSecurityLinkInfo(UserInfo userInfo,
GenericDelegator delegator) {
return new SecurityLinkInfo("Account", "accountId", false);
}
}