function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SeanCenoSeanCeno 

Only insert Opportunity if one doesn't already exist on the Account

All,
I was asked to update some code so that instead of always inserting an Opportunity based on the Task insertion criteria, it only inserts an Opportunity if the related Account doesn't already have one. Usually I think this would be solved using Account.Opportunities.Size()==0, but I'm inserting the Opportunity based off a Task creation and finding the Account associated to the Contact using AccountId. And
​ cIdMap.get(tsk.whoId).AccountId.Opportunities.Size()==0
throws an Invalid foreign key relationship: Contact.AccountId error.

Does anyone know how I could solve this?

Here is the full code. The method is on lines 82-118.
public class SalesBlitzProcess {
    //Grab Lst of tasks
    protected final Task[] taskNewList;
    protected final Task[] taskOldList;
    
    public SalesBlitzProcess (Task[] taskOldList, Task[] taskNewList){
        this.taskNewList = taskNewList;
        this.taskOldList = taskOldList;
    }
    
    List<Task> taskList = new List<Task>();
    List<Opportunity> oppList = new List<Opportunity>();
    Task t;
    Opportunity o;
    Contact c;
    Account a;
    
    //Left Message - Create new Tasks if the following Outcomes == 'Left Message' || 'No Answer'
    Set<Contact> cSet = new Set<Contact>();
    public void executeLeftMessage(){
        for(Task tsk : taskNewList){
            if(tsk.Status =='Completed' && tsk.Subject == 'Sales Blitz Call - Day 1' && (tsk.Outcome__c == 'Left Message' || tsk.Outcome__c == 'No Answer')){
                //Set c.Nurture_Paused__c = True; and c.Send_Day_1_Follow_Up_Email__c = true;
                if(tsk.WhoId != null && String.valueOf(tsk.whoId).substring(0,3) == '003') {
                    c = new Contact(Id = tsk.whoId);
                    c.Nurture_Paused__c = true;
                    c.Send_Day_1_Follow_Up_Email__c = true;
                    cSet.add(c);
                }
                t = new Task();
                t.OwnerId = tsk.OwnerId;
                t.WhoId = tsk.WhoId;
                t.Subject = 'Sales Blitz Call - Day 3';
                t.Status = 'Not Started';
                t.ActivityDate = System.Today().addDays(2);
                taskList.add(t);
                
            } else if (tsk.Status =='Completed' && tsk.Subject == 'Sales Blitz Call - Day 3' && (tsk.Outcome__c == 'Left Message' || tsk.Outcome__c == 'No Answer')){
                t = new Task();
                t.OwnerId = tsk.OwnerId;
                t.WhoId = tsk.WhoId;
                t.Subject = 'Sales Blitz Call - Day 5';
                t.Status = 'Not Started';
                t.ActivityDate = System.Today().addDays(2);
                taskList.add(t);
                
            } else if (tsk.Status =='Completed' && tsk.Subject == 'Sales Blitz Call - Day 5' && (tsk.Outcome__c == 'Left Message' || tsk.Outcome__c == 'No Answer')){
                //c.Send_Day_1_Follow_Up_Email__c = true;
                if(tsk.WhoId != null && String.valueOf(tsk.whoId).substring(0,3) == '003') {
                    c = new Contact(Id = tsk.whoId);
                    c.Send_Day_5_Follow_Up_Email__c = true;
                    cSet.add(c);
                }
                t = new Task();
                t.OwnerId = tsk.OwnerId;
                t.WhoId = tsk.WhoId;
                t.Subject = 'Sales Blitz Call - Day 8';
                t.Status = 'Not Started';
                t.ActivityDate = System.Today().addDays(3);
                taskList.add(t);
                
            } else if (tsk.Status =='Completed' && tsk.Subject == 'Sales Blitz Call - Day 8' && (tsk.Outcome__c == 'Left Message' || tsk.Outcome__c == 'No Answer')){
                //Set c.Nurture_Paused__c = False;
                if(tsk.WhoId != null && String.valueOf(tsk.whoId).substring(0,3) == '003') {
                    c = new Contact(Id = tsk.whoId);
                    c.Nurture_Paused__c = false;
                    c.Send_Day_1_Follow_Up_Email__c = false;
                    c.Send_Day_5_Follow_Up_Email__c = false;
                    cSet.add(c);
                }
            }
        }
        
        If(!taskList.isEmpty()){
            insert taskList;
        }
        If(!cSet.isEmpty()){
            update new List <Contact>(cSet);
        }
    }
    
    //Continue Process - Create Opportunity if Task has the following outcomes
    Set<Id> ContactIds = new Set<Id>();
    public void executeContinueProcess(){
        for(Task tsk : taskNewList){
            if(tsk.Status =='Completed' && (tsk.Outcome__c == 'Set First Advisor Briefing'
                || tsk.Outcome__c == 'Set Qualified Meeting'
                || tsk.Outcome__c == 'Set Existing Producer Meeting'
                || tsk.Outcome__c == 'Set Touch Base Meeting'
                || tsk.Outcome__c == 'Proposal Needed'
                || tsk.Outcome__c == 'Verbal Commitment')){
                    String tId = tsk.WhoId;
                    if(String.ValueOf(tsk.WhoId).substring(0,3) == '003'){
                        ContactIds.add(tsk.WhoId);
                    }
                    
                    List<Contact> taskContacts = [Select Id, AccountId, Account.Name, Nurture_Paused__c FROM Contact Where Id in:ContactIds];
                    Map<Id, Contact> cIdMap = new Map<Id, Contact>(taskContacts);
                    //Create Opportunity if Task has the outcome above
                    o = new Opportunity();
                    //system.debug('==========Contact Id ========'+tsk.WhoId);
                    //system.debug('==========Contact record ========'+cIdMap.get(tsk.WhoId));
                    //system.debug('==========account Id ========'+cIdMap.get(tsk.WhoId).AccountId);
                    if(tsk.WhoId != null && cIdMap.get(tsk.WhoId) != null){
                        o.AccountId = cIdMap.get(tsk.WhoId).AccountId;
                    }
                    o.Name = 'New Sales Blitz Opportunity';
                    o.StageName = 'New';
                    o.Opportunity_Potential__c = 0.00;
                    o.CloseDate = Date.today();
                    o.OriginalOpportunitySource__c = 'Sales Blitz';
                    oppList.add(o);
                }
        }
        If(!oppList.isEmpty()){
            insert oppList;
        }
    }
    
    //Not Now - Check Nurture Paused for 3 weeks if Outcome__c == Follow Up Or TBD, then unpause.
    public void executeNotNow(){
        for(Task tsk : taskNewList){
            if(tsk.Status =='Completed' && (tsk.Outcome__c == 'Follow Up' || tsk.Outcome__c == 'TBD')){
                //Set c.Nurture_Paused__c = True;
                if(tsk.WhoId != null && String.valueOf(tsk.whoId).substring(0,3) == '003') {
                    c = new Contact(Id = tsk.whoId);
                    c.Nurture_Paused__c = true;
                    cSet.add(c);
                }
                t = new Task();
                t.OwnerId = tsk.OwnerId;
                t.WhoId = tsk.WhoId;
                t.Subject = 'Unpause Nurture - 3 Weeks';
                t.Status = 'Not Started';
                t.Outcome__c = 'Unpause Nurture';
                t.ActivityDate = System.Today().addDays(21);
                taskList.add(t);
            }
            //After 3 weeks, unpause nurture
            //Once closed, uncheck checkbox
            else if (tsk.Status =='Completed' && tsk.Subject == 'Unpause Nurture - 3 Weeks' && tsk.Outcome__c == 'Unpause Nurture'){
                //Set c.Nurture_Paused__c = False;
                if(tsk.WhoId != null && String.valueOf(tsk.whoId).substring(0,3) == '003') {
                    c = new Contact(Id = tsk.whoId);
                    c.Nurture_Paused__c = false;
                    cSet.add(c);
                }
            }
        }
        If(!taskList.isEmpty()){
            insert t;
        }
        if(!cSet.isEmpty()){
            update new List <Contact>(cSet);
        }
    }
    //Hard No - Create reminder task to close in 90 days to unpause nurture
    public void executeHardNo(){
        for(Task tsk : taskNewList){
            if(tsk.Status =='Completed' && tsk.Outcome__c == 'Not Interested' && tsk.Subject.contains('Sales Blitz')){
                //Set c.Nurture_Paused__c = True;
                if(tsk.WhoId != null && String.valueOf(tsk.whoId).substring(0,3) == '003') {
                    c = new Contact(Id = tsk.whoId);
                    c.Nurture_Paused__c = true;
                    cSet.add(c);
                }
                t = new Task();
                t.OwnerId = tsk.OwnerId;
                t.WhoId = tsk.WhoId;
                t.Subject = 'Unpause Nurture - 3 Months';
                t.Status = 'Not Started';
                t.Outcome__c = 'Unpause Nurture';
                t.ActivityDate = System.Today().addDays(90);
                taskList.add(t);
            }
            //After 3 months, unpause nurture
            //Once closed, uncheck checkbox
            else if (tsk.Status =='Completed' && tsk.Subject == 'Unpause Nurture - 3 Months' && tsk.Outcome__c == 'Unpause Nurture'){
                //Set c.Nurture_Paused__c = False;
                if(tsk.WhoId != null && String.valueOf(tsk.whoId).substring(0,3) == '003') {
                    c = new Contact(Id = tsk.whoId);
                    c.Nurture_Paused__c = false;
                    cSet.add(c);
                }
            }
        }
        If(!taskList.isEmpty()){
            insert t;
        }
        if(!cSet.isEmpty()){
            update new List <Contact>(cSet);
        }
    }
}

 
Best Answer chosen by SeanCeno
suresh sanneboina 4suresh sanneboina 4
Hi 

Please use the below code and relace the code from 82-118
public void executeContinueProcess(){
        for(Task tsk : taskNewList){
            if(tsk.Status =='Completed' && (tsk.Outcome__c == 'Set First Advisor Briefing'
                || tsk.Outcome__c == 'Set Qualified Meeting'
                || tsk.Outcome__c == 'Set Existing Producer Meeting'
                || tsk.Outcome__c == 'Set Touch Base Meeting'
                || tsk.Outcome__c == 'Proposal Needed'
                || tsk.Outcome__c == 'Verbal Commitment')){
                    String tId = tsk.WhoId;
                    if(String.ValueOf(tsk.WhoId).substring(0,3) == '003'){
                        ContactIds.add(tsk.WhoId);
                    }
			}
		}
		if(!ContactIds.isEmpty())
		{
			Map<Id, Contact> cIdMap = new Map<Id, Contact>([Select Id, AccountId, Account.Name, Nurture_Paused__c FROM Contact Where Id in:ContactIds]);
			Set<Id> accountIds=new Set<Id>();
			for(Task tsk : taskNewList)
			{
				if(tsk.WhoId != null && cIdMap.get(tsk.WhoId) != null){
					//o.AccountId = cIdMap.get(tsk.WhoId).AccountId;
					accountIds.add(cIdMap.get(tsk.WhoId).AccountId);
				}
			}
			
			if(!accountIds.isEmpty())
			{
				Map<Id,Account> mapAccount=new Map<Id,Account>([SELECT Id, (SELECT Id FROM Opportunities) FROM Account where Id IN : accountIds]);
				for(Id accId:accountIds)
				{
					if(mapAccount.containsKey(accId))
					{
						if(mapAccount.get(accId).Opportunities.size() == 0)
						{
							Opportunity opp=new Opportunity();
							opp.Name = 'New Sales Blitz Opportunity';
							opp.AccountId = accId;
							opp.StageName = 'New';
							opp.Opportunity_Potential__c = 0.00;
							opp.CloseDate = Date.today();
							opp.OriginalOpportunitySource__c = 'Sales Blitz';
							oppList.add(opp);
						}
					}
				}
				
			}
        }
        If(!oppList.isEmpty()){
            insert oppList;
        }
    }

 

All Answers

Veenesh VikramVeenesh Vikram
Hi,

Using the Account Id in "cIdMap.get(tsk.WhoId).AccountId", You need to Query the Child Opportunities and then check the size. I doubt you will be able to get them directly. As the code needs to be bulkified, Create a Map of Id and Account, Query account's Child Opportunities and check their size when needed.
This will resolve your issue.

Veenesh
suresh sanneboina 4suresh sanneboina 4
Hi 

Please use the below code and relace the code from 82-118
public void executeContinueProcess(){
        for(Task tsk : taskNewList){
            if(tsk.Status =='Completed' && (tsk.Outcome__c == 'Set First Advisor Briefing'
                || tsk.Outcome__c == 'Set Qualified Meeting'
                || tsk.Outcome__c == 'Set Existing Producer Meeting'
                || tsk.Outcome__c == 'Set Touch Base Meeting'
                || tsk.Outcome__c == 'Proposal Needed'
                || tsk.Outcome__c == 'Verbal Commitment')){
                    String tId = tsk.WhoId;
                    if(String.ValueOf(tsk.WhoId).substring(0,3) == '003'){
                        ContactIds.add(tsk.WhoId);
                    }
			}
		}
		if(!ContactIds.isEmpty())
		{
			Map<Id, Contact> cIdMap = new Map<Id, Contact>([Select Id, AccountId, Account.Name, Nurture_Paused__c FROM Contact Where Id in:ContactIds]);
			Set<Id> accountIds=new Set<Id>();
			for(Task tsk : taskNewList)
			{
				if(tsk.WhoId != null && cIdMap.get(tsk.WhoId) != null){
					//o.AccountId = cIdMap.get(tsk.WhoId).AccountId;
					accountIds.add(cIdMap.get(tsk.WhoId).AccountId);
				}
			}
			
			if(!accountIds.isEmpty())
			{
				Map<Id,Account> mapAccount=new Map<Id,Account>([SELECT Id, (SELECT Id FROM Opportunities) FROM Account where Id IN : accountIds]);
				for(Id accId:accountIds)
				{
					if(mapAccount.containsKey(accId))
					{
						if(mapAccount.get(accId).Opportunities.size() == 0)
						{
							Opportunity opp=new Opportunity();
							opp.Name = 'New Sales Blitz Opportunity';
							opp.AccountId = accId;
							opp.StageName = 'New';
							opp.Opportunity_Potential__c = 0.00;
							opp.CloseDate = Date.today();
							opp.OriginalOpportunitySource__c = 'Sales Blitz';
							oppList.add(opp);
						}
					}
				}
				
			}
        }
        If(!oppList.isEmpty()){
            insert oppList;
        }
    }

 
This was selected as the best answer
SeanCenoSeanCeno
Thank you guys, worked perfectly!