package com.sourcetap.sfa.lead;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
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.GenericPK;
import org.ofbiz.entity.GenericValue;
import com.sourcetap.sfa.account.AccountEventProcessor;
import com.sourcetap.sfa.contact.ContactEventProcessor;
import com.sourcetap.sfa.event.DataMatrix;
import com.sourcetap.sfa.event.GenericEventProcessor;
import com.sourcetap.sfa.opportunity.OpportunityEventProcessor;
import com.sourcetap.sfa.ui.UICache;
import com.sourcetap.sfa.ui.UIWebScreenSection;
import com.sourcetap.sfa.ui.UIWebUtility;
import com.sourcetap.sfa.util.UserInfo;
public class LeadConverter {
public static final String module = LeadConverter.class.getName();
public List fieldMapping;
public HashMap screenSections;
public HashMap sourceData;
public String accountId = null;
public String contactId = null;
public String opportunityId = null;
public String opportunityName = null;
public String opportunityStageId = null;
public boolean createContact = true;
public boolean createOpportunity = true;
protected GenericDelegator delegator = null;
protected UICache uiCache = null;
protected UIWebScreenSection uiWebScreenSection = null;
protected UserInfo userInfo = null;
protected LeadEventProcessor leadEventProcessor = null;
public LeadConverter( GenericDelegator delegator, UICache uiCache, UserInfo userInfo, LeadEventProcessor leadEventProcessor)
{
fieldMapping = new ArrayList();
sourceData = new HashMap();
initializeFieldMappings();
this.delegator = delegator;
this.uiCache = uiCache;
this.userInfo = userInfo;
this.leadEventProcessor = leadEventProcessor;
try {
this.uiWebScreenSection = UIWebScreenSection.getUiWebScreenSection(userInfo, "LEAD", "LeadHeader", delegator, uiCache);
} catch (GenericEntityException e) {
Debug.logError("Error creating leadConverter: " + e.getMessage(), module);
throw new IllegalArgumentException("Unable to load screen section LEAD.LeadHeader in LeadConverter");
}
}
public void initializeFieldMappings()
{
addMapping( "Lead", "leadOwnerId", "ACCOUNT", "AccountHeader", "Account", "accountOwnerId" );
addMapping( "Lead", "companyName", "ACCOUNT", "AccountHeader", "Account", "accountName" );
addMapping( "Lead", "businessPhone", "ACCOUNT", "AccountHeader", "Account", "phone" );
addMapping( "Lead", "faxPhone", "ACCOUNT", "AccountHeader", "Account", "fax" );
addMapping( "Address", "mailingAddress", "ACCOUNT", "AccountHeader", "Address", "mailingAddress");
addMapping( "Address", "city", "ACCOUNT", "AccountHeader", "Address", "city");
addMapping( "Address", "state", "ACCOUNT", "AccountHeader", "Address", "state");
addMapping( "Address", "zip", "ACCOUNT", "AccountHeader", "Address", "zip");
addMapping( "Address", "country", "ACCOUNT", "AccountHeader", "Address", "country");
addMapping( "Lead", "stockSymbol", "ACCOUNT", "AccountHeader", "Account", "stockSymbol" );
addMapping( "Lead", "annualRevenue", "ACCOUNT", "AccountHeader", "Account", "annualRevenue" );
addMapping( "Lead", "sicCodeId", "ACCOUNT", "AccountHeader", "Account", "sicCodeId" );
addMapping( "Lead", "industry", "ACCOUNT", "AccountHeader", "Account", "industry");
addMapping( "Lead", "numberOfEmployees", "ACCOUNT", "AccountHeader", "Account", "numberOfEmployees" );
addMapping( "Lead", "dunsNumber", "ACCOUNT", "AccountHeader", "Account", "dunsNumber" );
addMapping( "Lead", "websiteUrl", "ACCOUNT", "AccountHeader", "Account", "websiteUrl" );
addMapping( "Lead", "businessDescription", "ACCOUNT", "AccountHeader", "Account", "businessDescription" );
//AccountHeader_Account_accountTypeId_0
//AccountHeader_Account_classInfo_0
//AccountHeader_Account_statusId_0
// addMapping( "Lead", "statusId", );
// addMapping( "Lead", "activeFlag", );
// addMapping( "Lead", "validatedFlag", );
// addMapping( "Lead", "leadSourceDetails", );
// addMapping( "Lead", "ownershipTypeId", "AccountHeader", "Account", );
addMapping( "Lead", "leadOwnerId", "CONTACT", "ContactHeader", "Contact", "contactOwnerId" );
addMapping( "Lead", "firstName", "CONTACT", "ContactHeader", "Contact", "firstName" );
addMapping( "Lead", "lastName", "CONTACT", "ContactHeader", "Contact", "lastName" );
addMapping( "Lead", "title", "CONTACT", "ContactHeader", "Contact", "title" );
addMapping( "Lead", "email", "CONTACT", "ContactHeader", "Contact", "email" );
addMapping( "Lead", "businessPhone", "CONTACT", "ContactHeader", "Contact", "businessPhone" );
addMapping( "Lead", "homePhone", "CONTACT", "ContactHeader", "Contact", "homePhone" );
addMapping( "Lead", "faxPhone", "CONTACT", "ContactHeader", "Contact", "faxPhone");
addMapping( "Lead", "mobilePhone", "CONTACT", "ContactHeader", "Contact", "mobilePhone");
addMapping( "Lead", "pager", "CONTACT", "ContactHeader", "Contact", "pager");
addMapping( "Address", "mailingAddress", "CONTACT", "ContactHeader", "Address", "mailingAddress");
addMapping( "Address", "city", "CONTACT", "ContactHeader", "Address", "city");
addMapping( "Address", "state", "CONTACT", "ContactHeader", "Address", "state");
addMapping( "Address", "zip", "CONTACT", "ContactHeader", "Address", "zip");
addMapping( "Address", "country", "CONTACT", "ContactHeader", "Address", "country");
//ContactHeader_Contact_ssn_0
//ContactHeader_Contact_statusId_0
//ContactHeader_Contact_accountId_0
addMapping( "Lead", "targetAmount", "OPPORTUNITIES", "OpportunityHeader", "Deal", "amount" );
addMapping( "Lead", "targetRatingId", "OPPORTUNITIES", "OpportunityHeader", "Deal", "ratingId" );
addMapping( "Lead", "targetDescription", "OPPORTUNITIES", "OpportunityHeader", "Deal", "description" );
addMapping( "Lead", "leadSourceId", "OPPORTUNITIES", "OpportunityHeader", "Deal", "leadSourceId" );
addMapping( "Lead", "leadOwnerId", "OPPORTUNITIES", "OpportunityHeader", "Deal", "ownerId" );
//OpportunityHeader_Deal_dealName_0
//OpportunityHeader_Deal_accountId_0
//OpportunityHeader_Deal_dealTypeId_0
//OpportunityHeader_Deal_projectedCloseDate_0
//OpportunityHeader_Deal_actualCloseDate_0
//OpportunityHeader_Deal_stageId_0
//OpportunityHeader_Deal_dealStatusId_0
//OpportunityHeader_Deal_isInForecast_0
}
public void addData( String entityName, GenericValue value)
{
sourceData.put("entityName", value);
}
public void addMapping( String fromEntity, String fromAttribute, String toScreenName, String toScreenSection, String toEntity, String toAttribute)
{
fieldMapping.add(new MappingInfo(fromEntity, fromAttribute, toScreenName, toScreenSection, toEntity, toAttribute));
}
public boolean convert ( String leadId )
{
DataMatrix dataMatrix = DataMatrix.fillFromDB(delegator, userInfo, uiWebScreenSection, leadEventProcessor,
new GenericPK( delegator.getModelEntity("Lead"), UtilMisc.toMap("leadId", leadId) ));
return convert( delegator, dataMatrix, userInfo, uiCache );
}
public boolean convert( GenericDelegator delegator, DataMatrix leadData, UserInfo userInfo, UICache uiCache )
{
try {
HashMap dataMatrixMap = new HashMap();
Iterator mappingIter = fieldMapping.iterator();
while ( mappingIter.hasNext())
{
MappingInfo mapInfo = (MappingInfo) mappingIter.next();
String screenId = mapInfo.screenName + "." + mapInfo.screenSection;
DataInfo dataInfo = (DataInfo) dataMatrixMap.get(screenId);
if ( dataInfo == null )
{
UIWebScreenSection uiWebScreenSection = UIWebScreenSection.getUiWebScreenSection(userInfo, mapInfo.screenName, mapInfo.screenSection, delegator, uiCache);
dataInfo = new DataInfo( delegator, uiWebScreenSection);
dataMatrixMap.put(screenId, dataInfo);
}
String field = mapInfo.toParamName;
GenericValue sourceGV = leadData.getCurrentBuffer().getGenericValue(0, mapInfo.fromEntity, false);
if ( sourceGV != null )
{
String value = sourceGV.getString(mapInfo.fromAttribute);
dataInfo.add( mapInfo.toParamName, value);
}
else
{
System.out.println("Unable to get source entity" + mapInfo.fromEntity);
}
}
GenericValue leadGV = leadData.getCurrentBuffer().getGenericValue(0, "Lead", false);
GenericValue addressGV = leadData.getCurrentBuffer().getGenericValue(0, "Address", false);
boolean hasAccountInfo = false;
String accountName = UtilFormatOut.checkNull(leadGV.getString("companyName"));
if ( ((accountId != null ) && ( accountId.length() > 0)) || (accountName.length() > 0) )
hasAccountInfo = true;
if ( hasAccountInfo )
{
DataInfo dataInfo = (DataInfo) dataMatrixMap.get("ACCOUNT.AccountHeader");
GenericEventProcessor eventProcessor = new AccountEventProcessor();
if ( (accountId != null) && ( accountId.length() > 0) )
{
dataInfo.retrieveFromDB(userInfo, eventProcessor, new GenericPK( delegator.getModelEntity("Account"), UtilMisc.toMap("accountId", accountId)));
dataInfo.processUpdate( userInfo, delegator, eventProcessor );
}
else
{
dataInfo.loadData(userInfo, eventProcessor);
dataInfo.processInsert( userInfo, delegator, eventProcessor );
}
GenericValue accountGV = dataInfo.dataMatrix.getCurrentBuffer().getGenericValue(0, "Account", false);
accountId = accountGV.getString("accountId");
accountName = accountGV.getString("accountName");
}
if ( getCreateContact())
{
DataInfo dataInfo = (DataInfo) dataMatrixMap.get("CONTACT.ContactHeader");
GenericEventProcessor eventProcessor = new ContactEventProcessor();
if ( (contactId != null) && (contactId.length() > 0))
{
dataInfo.retrieveFromDB(userInfo, eventProcessor, new GenericPK( delegator.getModelEntity("Contact"), UtilMisc.toMap("contactId", contactId)));
if ( hasAccountInfo )
{
GenericValue contactGV = dataInfo.dataMatrix.getCurrentBuffer().getGenericValue(0, "Contact", false);
String accountIdOrig = contactGV.getString("accountId");
if ( ( accountIdOrig == null ) || ( accountIdOrig.length() < 1) )
contactGV.set("accountId", accountId);
}
dataInfo.processUpdate( userInfo, delegator, eventProcessor );
}
else
{
dataInfo.loadData(userInfo, eventProcessor);
if ( hasAccountInfo )
dataInfo.dataMatrix.getCurrentBuffer().getGenericValue(0, "Contact", false).set("accountId", accountId);
dataInfo.processInsert( userInfo, delegator, eventProcessor );
}
GenericValue contactGV = dataInfo.dataMatrix.getCurrentBuffer().getGenericValue(0, "Contact", false);
contactId = contactGV.getString("contactId");
// Add ContactEmploymentInfo if there is an account tied to this record
if ( ( accountId != null) && ( accountId.length() > 0) )
{
GenericValue employmentGV = delegator.findByPrimaryKey("ContactEmployment", UtilMisc.toMap("contactEmploymentId", contactId + "-E"));
if ( employmentGV == null )
{
employmentGV = new GenericValue( delegator.getModelEntity("ContactEmployment"));
employmentGV.setDelegator(delegator);
employmentGV.set("contactEmploymentId", contactId + "-E");
employmentGV.set("contactId", contactId);
employmentGV.set("title", leadGV.getString("title"));
employmentGV.set("companyName", accountName);
if ( addressGV != null )
{
employmentGV.set("mailingAddress", addressGV.getString("mailingAddress"));
employmentGV.set("city", addressGV.getString("city"));
employmentGV.set("state", addressGV.getString("state"));
employmentGV.set("zip", addressGV.getString("zip"));
}
employmentGV.create();
}
}
}
if ( getCreateOpportunity() && hasAccountInfo)
{
DataInfo dataInfo = (DataInfo) dataMatrixMap.get("OPPORTUNITIES.OpportunityHeader");
GenericEventProcessor eventProcessor = new OpportunityEventProcessor();
DataMatrix dataMatrix = dataInfo.loadData(userInfo, eventProcessor);
GenericValue dealGV = dataMatrix.getCurrentBuffer().getGenericValue(0, "Deal", false);
dealGV.set("accountId", accountId);
if ( opportunityName != null)
dealGV.set("dealName", opportunityName);
else
dealGV.set("dealName", "Opportunity for " + accountName);
if ( opportunityStageId != null )
dealGV.set("stageId", opportunityStageId);
dealGV.set("dealTypeId", "1");
dataInfo.processInsert( userInfo, delegator, eventProcessor );
opportunityId = dealGV.getString("dealId");
}
// move the related lead data to the contact or account
String leadId = leadGV.getString("leadId");
//PartyIdentifiers are moved to the account and contact
List partyIdentifiers = delegator.findByAnd("PartyIdentifier", UtilMisc.toMap("partyId", leadId), null);
String partyId = contactId;
String partyType = "Contact";
if ( hasAccountInfo )
{
partyType = "Account";
partyId = accountId;
Iterator identIter = partyIdentifiers.iterator();
while ( identIter.hasNext())
{
GenericValue gv = (GenericValue) identIter.next();
gv.set("partyId", accountId);
}
delegator.storeAll(partyIdentifiers);
}
if ( getCreateContact() )
{
Iterator identIter = partyIdentifiers.iterator();
while ( identIter.hasNext())
{
GenericValue gv = (GenericValue) identIter.next();
gv.set("partyId", contactId);
}
delegator.storeAll(partyIdentifiers);
}
delegator.removeByAnd("PartyIdentifier", UtilMisc.toMap("partyId", leadId));
//Activities are mapped to the contact and account
List activities = delegator.findByAnd("Activity", UtilMisc.toMap("leadId", leadId), null);
Iterator actIter = activities.iterator();
while ( actIter.hasNext())
{
GenericValue gv = (GenericValue) actIter.next();
gv.set("accountId", accountId);
gv.set("contactId", contactId);
}
delegator.storeAll(activities);
//Notes are mapped to the account
List notes = delegator.findByAnd("NoteLink", UtilMisc.toMap("noteLinkType", "Lead", "noteLinkId", leadId), null);
delegator.removeByAnd("NoteLink", UtilMisc.toMap("noteLinkType", "Lead", "noteLinkId", leadId));
Iterator noteIter = notes.iterator();
while ( noteIter.hasNext())
{
GenericValue gv = (GenericValue) noteIter.next();
gv.set("noteLinkType", partyType);
gv.set("noteLinkId", partyId);
}
delegator.storeAll(notes);
//File attachments are mapped to account and contact
List leadFiles = delegator.findByAnd("LeadFile", UtilMisc.toMap("leadId", leadId), null);
delegator.removeByAnd("LeadFile", UtilMisc.toMap("leadId", leadId));
Iterator fileIter = leadFiles.iterator();
while ( fileIter.hasNext())
{
GenericValue gv = (GenericValue) fileIter.next();
if ( hasAccountInfo )
{
GenericValue accountFile = new GenericValue(delegator.getModelEntity("AccountFile"));
accountFile.setDelegator(delegator);
accountFile.set("accountId", accountId);
accountFile.set("fileId", gv.get("fileId"));
accountFile.set("createdBy", gv.get("createdBy"));
accountFile.set("modifiedBy",gv.get("modifiedBy"));
accountFile.set("createdDate", gv.get("createdDate"));
accountFile.set("modifiedDate",gv.get("modifiedDate"));
accountFile.create();
}
if ( getCreateContact() )
{
GenericValue contactFile = new GenericValue(delegator.getModelEntity("ContactFile"));
contactFile.setDelegator(delegator);
contactFile.set("contactId", contactId);
contactFile.set("fileId", gv.get("fileId"));
contactFile.set("createdBy", gv.get("createdBy"));
contactFile.set("modifiedBy",gv.get("modifiedBy"));
contactFile.set("createdDate", gv.get("createdDate"));
contactFile.set("modifiedDate",gv.get("modifiedDate"));
contactFile.create();
}
}
// update the converted date on the lead.
Timestamp now = new Timestamp(Calendar.getInstance().getTime().getTime());
leadGV.set("convertedDate", now);
leadGV.set("convertedAccountId", accountId);
leadGV.set("convertedContactId", contactId);
delegator.store(leadGV);
return true;
}
catch ( Exception e)
{
Debug.logError(e, module);
return false;
}
}
public class MappingInfo {
public String fromEntity;
public String fromAttribute;
public String toEntity;
public String toAttribute;
public String toParamName;
public String screenName;
public String screenSection;
public MappingInfo( String fromEntityStr, String fromAttributeStr, String screenNameStr, String screenSectionStr, String toEntityStr, String toAttributeStr)
{
fromEntity = fromEntityStr;
fromAttribute = fromAttributeStr;
toEntity = toEntityStr;
toAttribute = toAttributeStr;
screenName = screenNameStr;
screenSection = screenSectionStr;
toParamName = UIWebUtility.getParamName("", screenSection, toEntity, toAttribute, 0);
}
}
public class DataInfo
{
UIWebScreenSection uiWebScreenSection;
DataMatrix dataMatrix;
Vector values;
Vector fields;
GenericDelegator delegator;
String[] valuesA;
public DataInfo( GenericDelegator delegator_, UIWebScreenSection uiWebScreenSection_ )
{
delegator = delegator_;
uiWebScreenSection = uiWebScreenSection_;
dataMatrix = new DataMatrix(delegator, uiWebScreenSection.getEntityParamVector());
values = new Vector();
fields = new Vector();
}
public void add(String field, String value)
{
fields.add(field);
values.add(value);
}
public DataMatrix retrieveFromDB(UserInfo userInfo, GenericEventProcessor eventProcessor, GenericPK primaryKey)
throws GenericEntityException
{
dataMatrix = DataMatrix.fillFromDB(delegator, userInfo, uiWebScreenSection, eventProcessor, primaryKey );
dataMatrix.addRowFromArray(0, values, fields, uiWebScreenSection);
return dataMatrix;
}
public DataMatrix loadData(UserInfo userInfo, GenericEventProcessor eventProcessor)
throws GenericEntityException
{
eventProcessor.processCreate( userInfo, uiWebScreenSection.getEntityNameList(), delegator, dataMatrix);
dataMatrix.addRowFromArray(0, values, fields, uiWebScreenSection);
return dataMatrix;
}
public void processInsert( UserInfo userInfo, GenericDelegator delegator, GenericEventProcessor eventProcessor)
throws GenericEntityException
{
eventProcessor.processInsert( userInfo, delegator, dataMatrix );
}
public void processUpdate( UserInfo userInfo, GenericDelegator delegator, GenericEventProcessor eventProcessor)
throws GenericEntityException
{
eventProcessor.processUpdate( userInfo, delegator, dataMatrix );
}
}
/**
* @return
*/
public String getAccountId()
{
return accountId;
}
/**
* @return
*/
public String getContactId()
{
return contactId;
}
/**
* @return
*/
public String getOpportunityName()
{
return opportunityName;
}
/**
* @return
*/
public String getOpportunityStageId()
{
return opportunityStageId;
}
/**
* @param string
*/
public void setAccountId(String string)
{
accountId = string;
}
/**
* @param string
*/
public void setContactId(String string)
{
contactId = string;
}
/**
* @param string
*/
public void setOpportunityName(String string)
{
opportunityName = string;
}
/**
* @param string
*/
public void setOpportunityStageId(String string)
{
opportunityStageId = string;
}
/**
* @return
*/
public String getOpportunityId()
{
return opportunityId;
}
/**
* @param string
*/
public void setOpportunityId(String string)
{
opportunityId = string;
}
/**
* @return
*/
public boolean getCreateContact()
{
return createContact;
}
/**
* @return
*/
public boolean getCreateOpportunity()
{
return createOpportunity;
}
/**
* @param b
*/
public void setCreateContact(boolean b)
{
createContact = b;
}
/**
* @param b
*/
public void setCreateOpportunity(boolean b)
{
createOpportunity = b;
}
}