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
dev2014dev2014 

Opportunity conditional statements +task to send email to task owner

Hi, I'm trying accomplish the following business logic:

1. IF  opportunity record is a financial vertical type And IF the opportunity is above $500K
2. Create a task to send an email to opportunity owner.

Here's what I have so far . I would appreciate your input of whats missing or  filling the blanks to make it work .

trigger on OpportunityCreation on opportunity (before insert) {

 

    //loop through all new opportunities  saved

    for(Opportunity Op: Trigger.new)

    {

         // if the Opportunity amount is greater than 500000

         if (Op. Amount_c >= 500000)

//and  if Opportunity  Vertical  (customized  pick list field)  value = Financial

         If (Op. Vertical_c) = 'Financial'

                // create a user task that ...

               

            Task T = new Task();

            T.Type = 'Email';

            T.Description = Opportunity was created with amount  of  above 500,000 in your speciality field'; //string

            T.OwnerId = Op.OwnerId;

            //T.WhatId = ''; //record id

   

           insert T;

}
         else
         {
             // if the anual amount is less than 500000 and not financial vertical do nothing ....
         }
        
    }
}
Magdiel HerreraMagdiel Herrera
What error does it gives this code to you ?
Trigger
trigger on OpportunityCreation on opportunity (before insert) {
    
    // If tasks are to be created then save them in a separate set and run dml operations outside loop statements	
    List<Task> tList = new  List<Task>();
	
    //loop through all new opportunities  saved
    for(Opportunity Op: Trigger.new)
    {
        // if the Opportunity amount is greater than 500000 AND Opportunity Vertical = Financial
        if (Op.Amount__c >= 500000 && Op.Vertical__c == 'Financial'){

            // create a user task that ...
            Task T        = new Task();
            T.Type        = 'Email';
            T.Description = 'Opportunity was created with amount  of  above 500,000 in your speciality field';
            T.OwnerId     = Op.OwnerId;
            //T.WhatId    = ''; //record id
	    
            // DO NOT RUN DML OPERATIONS INSIDE FOR LOOPS            
	    tList.add(T);
	}
        else {
            // if the anual amount is less than 500000 and not financial vertical do nothing ....
        }
    }
	
    if(tList!=null && !tList.isEmpty()){
	OpportunityTriggerHelper.createTasks(tList);
    }
}

Apex Class
public class OpportunityTriggerHelper	
	
	public static void createTasks(List<Task> tList){
		try{
		       insert tList;
		}
		catch(Exception err){
			system.debug('\n Error while creating tasks. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}
	}

}

Other than that, not sure why you need a task, you could just create a workflow rule using that criteria and fire an email alert.
Vinit_KumarVinit_Kumar
Agreed you should be using Workflows to send an Email alert instead of creating an Apex Trigger.
dev2014dev2014

Magdiel, thanks for the code input I appreciate it. The reason I'm using an Apex  trigger is that in  the next step my client wants  to assign those opportunities type tasks  to a specidific financial team role based specializing in those type of opportunities. I just wanted to make sure that the conditional part of the trigger works first. I assume the task command at this first part will send email to me as a test as the opportunity owner and task owner.

This is the error I got from the code input your provided. I'm new to this so your  input on making this trigger work is  appreciated.

the error on line 29 :"Duplicate variable: tList"


User-added image

 


Vinit_KumarVinit_Kumar
Ben,

You should be creating 2 components as per the code provided by Magdiel,one Apex Class and another Apex Trigger.


I can see you are merging both into one.
Magdiel HerreraMagdiel Herrera
Thanks @Vinit_Kumar,

@Ben as @Vinit_Kumar said, I splitted the logic into one apex trigger, and one apex class,

If it makes sense for the business then it makes sense for us if nothing more is available, I was about to mention if you knew about the big deal alert in salesforce, to accomplish this requirement the only one thing I'll suggest is this line of code requires your attention,

//T.WhatId    = ''; //record id

You'll need to change your trigger to run on after insert as that's the only way you'll have access to the record's id, so try this trigger instead,

trigger on OpportunityCreation on opportunity (after insert) {
    
    // If tasks are to be created then save them in a separate set and run dml operations outside loop statements	
    List<Task> tList = new  List<Task>();
	
    //loop through all new opportunities  saved
    for(Opportunity Op: Trigger.new)
    {
        // if the Opportunity amount is greater than 500000 AND Opportunity Vertical = Financial
        if (Op.Amount__c >= 500000 && Op.Vertical__c == 'Financial'){

            // create a user task that ...
            Task T        = new Task();
            T.Type        = 'Email';
            T.Description = 'Opportunity was created with amount  of  above 500,000 in your speciality field';
            T.OwnerId     = Op.OwnerId;
            T.WhatId      = Op.Id; //record id
	    
            // DO NOT RUN DML OPERATIONS INSIDE FOR LOOPS            
	    tList.add(T);
	}
        else {
            // if the anual amount is less than 500000 and not financial vertical do nothing ....
        }
    }
	
    if(tList!=null && !tList.isEmpty()){
	OpportunityTriggerHelper.createTasks(tList);
    }
}

Once your trigger is up and running with no issues, it comes the time when additional processing can be added to your helper class, this is one of many approaches, I tried to cover the basics on some best practices, including the email you need to send.

public class OpportunityTriggerHelper	
	
	public static void createTasks(List<Task> tList){
		Set<String> tIds = new Set<String>();
		try{
            // false for second parameter and a record fails, the remainder of the DML operation can still succeed		
			// (https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database.htm#apex_System_Database_insert_2)
		    Database.SaveResult[] srTask  = insert(tList, false);

			// Iterate through each returned result
			// (http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database_saveresult.htm)
			for (Database.SaveResult sr : srTask) {
				if (sr.isSuccess()) {
					// Operation was successful, so get the ID of the record that was processed and fire an email
					System.debug('Successfully created the task. ID: ' + sr.getId());					
					tIds.add(sr.getId());
				}
				else {
					// Operation failed, so get all errors                
					for(Database.Error err : sr.getErrors()) {
						System.debug('The following error has occurred.');                    
						System.debug(err.getStatusCode() + ': ' + err.getMessage());
						System.debug('Task fields that affected this error: ' + err.getFields());
					}
				}
			}
			
			// We check for the tasks successfully created and then read information they're related to needed to send an email
			if(tIds!=null && !tIds.isEmpty()){
				for(Task tObj : [SELECT Id, What.Name, WhatId, What.OwnerId FROM Task WHERE Id IN :tIds]){
					SendEmailNotification(tObj.What.OwnerId, 'BIG DEAL !!!', 'WE GOTEM', tObj.WhatId, tObj.What.Name);
				}
			}
		}
		catch(Exception err){
			system.debug('\n Error while creating tasks. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}
	}
	
	public static void SendEmailNotification(Id SendTo, string Subject, string BodyText, String LinkURL, String LinkLabel){
		try
		{
			Messaging.reserveSingleEmailCapacity(1);
			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
			// Sending the email to a user doesn't count against the limited amount of apex emails try to always do it this way or don't use it
			mail.setTargetObjectId(SendTo);
			mail.saveAsActivity = false;
			mail.setSenderDisplayName('Salesforce custom big deal alert');
			mail.setSubject(Subject);

			if (LinkURL != null) {
				mail.setHtmlBody(BodyText + '<br />' + 'Click for details : ' + '<a href=' + LinkURL + '>' + LinkLabel + '</a>');
			}
			else {
				mail.setHtmlBody(BodyText);
			}
			Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
		}
		catch (Exception ex) { 
			system.debug('\n Error while sending email. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}

	} 

}

Hope that helps.
dev2014dev2014
Thanks Magdiel and Vinit, I'm new to this so appreciate your valuable input. I tried the previous before version trigger as separate trigger and separate Apex class but it didn't send the email to the opportunity owner. So I will try the After trigger you are suggesting here.  Do i need all of the 69 lines of the Apex helper class above   to send  the opportunity  notification  email  to  the opportunity owner?Would the lines below of the Helper class would not be suffieicent  tomake the trigger work to send the email ?
public class OpportunityTriggerHelper  
02     
03     public static void createTasks(List<Task> tList){
04         try{
05                insert tList;
06         }
07         catch(Exception err){
08             system.debug('\n Error while creating tasks. \n'
09                                   + err.getMessage() + ' \n'
10                                   + err.getStackTraceString());        
11         }
12     }
13  
14 }
Magdiel HerreraMagdiel Herrera
@ben been, actually a good question,

When creating a task using the Salesforce UI, you have an option to send an email, but when using Apex code, you don't have this feature,

I found these comments,

No it's not a flag you could set on the Task
http://salesforce.stackexchange.com/questions/14205/which-field-represents-the-send-notification-email-checkbox-present-on-the-tas

More than one are suggesting a workaround which I do not recommend,
http://salesforceapexcodecorner.blogspot.com/2011/07/send-email-when-create-task-using-apex.html?_sm_au_=i7HMnRRPv7rkFMrr
http://blog.wdcigroup.net/2013/11/salesforce-apex-send-notification-when-task-created-from-apex/

The solution I suggested, uses the successful creation of a task to decide if an email should be sent to the opp owner or not, it involves apex, and yes you need all the code, plus the code coverage,

But there are as many other solutions you could try,

Your requirement #2 reads "Create a task to send an email to opportunity owner", I assumed the email alert was dependent upon the task creation and assignment, no task then no email alert,

We already have the task created only for our oppportunities (evaluating the vertical), we need then to check for the task to be successfuly created to then fire the email if your requirement is correct, in which case the last code you posted won't be sufficient UNLESS,

You find a way up from the successful creation of a task, to a workflow based on the opportunity to fire the email alert,

dev2014dev2014
Great Thanks Magdiel. Just in case,  let me clarify the logic.
If the 2 conditions together (above 500k and vertical "finance" from a pick list type field ) are not met, then no task and no email.  The two conditions together need to happen to execute the task. It's most important that it will create a task for the opportunity owner in those conditions. Email alert to the opportunity owner  is just a bonus extra alert to the task here.

added your after Trigger and those are the two errors:
User-added image
User-added image

Magdiel HerreraMagdiel Herrera
remove the <strong> tags from your code, it was probably something from editing the post, and add a { after the class name, also probably something I missed when edited the post
dev2014dev2014
Thanks Magdiel. See new error below related  regarding not having "ownerId"  column. There is an "Opportunity Owner" field.
User-added image
Magdiel HerreraMagdiel Herrera
Sorry about that, I wrote the code directly in the post, didn't realized of some details, the field What for a task is a polymorphic one which can be treated as more than one entity, it only has access to information like Id and Name of the related record, so we'll have to send the opportunity info to the helper class and relate back to it at the time we need it,

Notice we needed to use a map which contains the opp info, you might want to restrict this to a more granular information, choise is yours,

This is the updated solution,

APEX TRIGGER
trigger on OpportunityCreation on opportunity (after insert) {
    
    // If tasks are to be created then save them in a separate set and run dml operations outside loop statements	
    List<Task> tList = new  List<Task>();
    Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
	
    //loop through all new opportunities  saved
    for(Opportunity Op: Trigger.new)
    {
        // if the Opportunity amount is greater than 500000 AND Opportunity Vertical = Financial
        if (Op.Amount__c >= 500000 && Op.Vertical__c == 'Financial'){

            // create a user task that ...
            Task T        = new Task();
            T.Type        = 'Email';
            T.Description = 'Opportunity was created with amount  of  above 500,000 in your speciality field';
            T.OwnerId     = Op.OwnerId;
            T.WhatId      = Op.Id; //record id
	    
            // DO NOT RUN DML OPERATIONS INSIDE FOR LOOPS            
	    tList.add(T);
	    oppMap.put(Op.Id, Op);
	}
        else {
            // if the anual amount is less than 500000 and not financial vertical do nothing ....
        }
    }
	
    if(tList!=null && !tList.isEmpty()){
	OpportunityTriggerHelper.createTasks(tList, oppMap);
    }
}




APEX CLASS
public class OpportunityTriggerHelper {

	
	public static void createTasks(List<Task> tList, Map<Id, Opportunity> oppMap){
		Set<String> tIds = new Set<String>();
		try{
		
		    Database.SaveResult[] srTask  = Database.insert(tList, false);

			for (Database.SaveResult sr : srTask) {
				if (sr.isSuccess()) {
					// Operation was successful, so get the ID of the record that was processed and fire an email
					System.debug('Successfully created the task. ID: ' + sr.getId());					
					tIds.add(sr.getId());
				}
				else {
					// Operation failed, so get all errors                
					for(Database.Error err : sr.getErrors()) {
						System.debug('The following error has occurred.');                    
						System.debug(err.getStatusCode() + ': ' + err.getMessage());
						System.debug('Task fields that affected this error: ' + err.getFields());
					}
				}
			}
			
			if(tIds!=null && !tIds.isEmpty()){
				for(Task tObj : [SELECT Id, What.Name, WhatId FROM Task WHERE Id IN :tIds]){
					Opportunity oppObj = oppMap.get(tObj.WhatId);
					SendEmailNotification(oppObj.OwnerId, 'BIG DEAL !!!', 'WE GOTEM', tObj.WhatId, tObj.What.Name);
				}
			}
		}
		catch(Exception err){
			system.debug('\n Error while creating tasks. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}
	}
	
	public static void SendEmailNotification(Id SendTo, string Subject, string BodyText, String LinkURL, String LinkLabel){
		try
		{
			Messaging.reserveSingleEmailCapacity(1);
			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
			mail.setTargetObjectId(SendTo);
			mail.saveAsActivity = false;
			mail.setSenderDisplayName('Salesforce custom big deal alert');
			mail.setSubject(Subject);

			if (LinkURL != null) {
				mail.setHtmlBody(BodyText + '<br />' + 'Click for details : ' + '<a href=' + LinkURL + '>' + LinkLabel + '</a>');
			}
			else {
				mail.setHtmlBody(BodyText);
			}
			Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
		}
		catch (Exception err) { 
			system.debug('\n Error while sending email. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}

	} 


}


dev2014dev2014
Great. Thanks Magdiel. I added the new Trigger and class and no error when saving the code. After saving I tried testing by creating a new opportunity above  500k and chose "financial" in the picklis+ filled in the required fields but it didn't send an email or created an activity task on that opportunity record ( see screenshot below). What are we missing here to make it work?

Thanks,

User-added image

User-added image
Magdiel HerreraMagdiel Herrera
The code has a lot of debug statements, take a look at the logs and you'll find where the issue is.
dev2014dev2014
 The debug log indicated : Success. See below but no email or task was created for this opportunity.  Do we need to include the required fields like Opportunity owner, Due date, close date and probability  stage to make it work? Appreciate your input.
User	Ben Been	Date	6/7/2014 5:39:01 AM PDT
Status	Success	Application	Browser
Request Type	Application	Operation	/006/e
Duration (ms)	772	Log Size (bytes)	4,865
Log	

30.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO
05:39:01.736 (736843436)|EXECUTION_STARTED
05:39:01.736 (736879754)|CODE_UNIT_STARTED|[EXTERNAL]|01qi0000000j9HP|OpportunityCreation on Opportunity trigger event AfterInsert for [006i000000LjAgz]
05:39:01.736 (736953809)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
05:39:01.737 (737692572)|HEAP_ALLOCATE|[71]|Bytes:3
05:39:01.737 (737720658)|HEAP_ALLOCATE|[76]|Bytes:152
05:39:01.737 (737736860)|HEAP_ALLOCATE|[272]|Bytes:408
05:39:01.737 (737755441)|HEAP_ALLOCATE|[285]|Bytes:408
05:39:01.737 (737771524)|HEAP_ALLOCATE|[379]|Bytes:48
05:39:01.737 (737796349)|HEAP_ALLOCATE|[131]|Bytes:6
05:39:01.737 (737940620)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:12
05:39:01.737 (737954821)|VARIABLE_SCOPE_BEGIN|[1]|this|OpportunityCreation|true|false
05:39:01.738 (738015386)|VARIABLE_ASSIGNMENT|[1]|this|{}|0x265c6e47
05:39:01.738 (738051727)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:12
05:39:01.738 (738059464)|VARIABLE_SCOPE_BEGIN|[1]|this|OpportunityCreation|true|false
05:39:01.738 (738072907)|VARIABLE_ASSIGNMENT|[1]|this|{}|0x265c6e47
05:39:01.738 (738080731)|STATEMENT_EXECUTE|[1]
05:39:01.738 (738084052)|STATEMENT_EXECUTE|[4]
05:39:01.738 (738092194)|HEAP_ALLOCATE|[4]|Bytes:4
05:39:01.738 (738141216)|SYSTEM_CONSTRUCTOR_ENTRY|[4]|<init>()
05:39:01.738 (738168880)|SYSTEM_CONSTRUCTOR_EXIT|[4]|<init>()
05:39:01.738 (738201901)|HEAP_ALLOCATE|[50]|Bytes:5
05:39:01.738 (738223383)|HEAP_ALLOCATE|[56]|Bytes:5
05:39:01.738 (738232071)|HEAP_ALLOCATE|[63]|Bytes:7
05:39:01.738 (738263983)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
05:39:01.738 (738290191)|VARIABLE_ASSIGNMENT|[4]|this.tList|{"serId":1,"value":[]}|0x265c6e47
05:39:01.738 (738294814)|STATEMENT_EXECUTE|[5]
05:39:01.738 (738302185)|HEAP_ALLOCATE|[5]|Bytes:4
05:39:01.738 (738351225)|VARIABLE_ASSIGNMENT|[5]|this.oppMap|{"serId":1,"value":{}}|0x265c6e47
05:39:01.738 (738421164)|SYSTEM_METHOD_ENTRY|[8]|LIST<Opportunity>.iterator()
05:39:01.738 (738637725)|SYSTEM_METHOD_EXIT|[8]|LIST<Opportunity>.iterator()
05:39:01.738 (738665932)|SYSTEM_METHOD_ENTRY|[8]|system.ListIterator.hasNext()
05:39:01.738 (738686076)|HEAP_ALLOCATE|[8]|Bytes:5
05:39:01.738 (738693172)|SYSTEM_METHOD_EXIT|[8]|system.ListIterator.hasNext()
05:39:01.738 (738718303)|VARIABLE_SCOPE_BEGIN|[8]|Op|Opportunity|true|false
05:39:01.739 (739176534)|VARIABLE_ASSIGNMENT|[8]|Op|{"ForecastCategory":"Pipeline","StageName":"Prospecting","IsWon":false,"Probability":10,"Amount":700000.00,"LastModifiedById":"005i00000033mWFAAY","OwnerId":"005i00000033mWFAAY","LastModifiedDate":"2014-06-07T12:39:00.000Z","ExpectedRevenue":70000.00,"End_of_quarter_date2 (3 more) ...":"2014-06-30T00:00:00.000Z","IsPrivate":false,"Name":"Triggertest2","IsClosed":false,"HasOpportunityLineIt (2 more) ...":false,"SystemModstamp":"2014-06-07T12:39:00.000Z","CreatedById":"005i00000033mWFAAY","CreatedDate":"2014-06-07T12:39:00.000Z","IsDeleted":false,"ForecastCategoryName":"Pipeline","Id":"006i000000LjAgzAAF","CloseDate":"2014-06-10T00:00:00.000Z","Vertical__c":"Finance"}|0x40208ff7
05:39:01.739 (739190051)|STATEMENT_EXECUTE|[9]
05:39:01.739 (739242023)|HEAP_ALLOCATE|[69]|Bytes:4
05:39:01.739 (739258469)|HEAP_ALLOCATE|[11]|Bytes:12
05:39:01.739 (739269864)|HEAP_ALLOCATE|[11]|Bytes:28
05:39:01.739 (739300172)|SYSTEM_METHOD_ENTRY|[11]|Decimal.compareTo(Decimal)
05:39:01.739 (739326504)|SYSTEM_METHOD_EXIT|[11]|Decimal.compareTo(Decimal)
05:39:01.739 (739348122)|HEAP_ALLOCATE|[11]|Bytes:9
05:39:01.739 (739375851)|STATEMENT_EXECUTE|[24]
05:39:01.739 (739384680)|SYSTEM_METHOD_ENTRY|[8]|system.ListIterator.hasNext()
05:39:01.739 (739393091)|HEAP_ALLOCATE|[8]|Bytes:5
05:39:01.739 (739399010)|SYSTEM_METHOD_EXIT|[8]|system.ListIterator.hasNext()
05:39:01.739 (739409062)|VARIABLE_ASSIGNMENT|[8]|Op|null|
05:39:01.739 (739428524)|SYSTEM_METHOD_ENTRY|[29]|LIST<Task>.isEmpty()
05:39:01.739 (739443906)|SYSTEM_METHOD_EXIT|[29]|LIST<Task>.isEmpty()
05:39:01.739 (739449854)|STATEMENT_EXECUTE|[29]
05:39:01.051 (739464964)|CUMULATIVE_LIMIT_USAGE
05:39:01.051|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 10
  Number of Email Invocations: 0 out of 10
  Number of fields describes: 0 out of 100
  Number of record type describes: 0 out of 100
  Number of child relationships describes: 0 out of 100
  Number of picklist describes: 0 out of 100
  Number of future calls: 0 out of 10

05:39:01.051|CUMULATIVE_LIMIT_USAGE_END

05:39:01.739 (739520695)|CODE_UNIT_FINISHED|OpportunityCreation on Opportunity trigger event AfterInsert for [006i000000LjAgz]
05:39:01.739 (739529803)|EXECUTION_FINISHED

dev2014dev2014
t
Hi, Any input on that on that Debug log  and what ismissing to create that conditional assigned  task work? Need to provides some results to the client in the next 3days.

Thanks,
Magdiel HerreraMagdiel Herrera
You need to debug this condition,

(Op.Amount__c >= 500000 && Op.Vertical__c == 'Financial')

It seems like it's not evaluating to true.
dev2014dev2014
Great thanks. Email was sent . I changed it to  " if (Op.Amount>= 500000 & Op.Vertical__c == 'Finance')
 Activity was created but can't get into the task and doesn't  see  the task description line:  "T.Description = 'Opportunity was created with amount  of  above 500,000 in your speciality field'; (see opportunity record screenshot below).Am I missing something here regarding getting into the task?  Im new to this so appreciate your input.

User-added image

User-added image
Magdiel HerreraMagdiel Herrera
Not sure what your issue is now, you can see there is an open activity there.

You just need to set the Name and Subject for the task and change the search layout to display the columns you want on the related list.
dev2014dev2014

Hi Magdiel,  I truly appreciate your valuable input and contribution with this use case. I just wanted to make sure I didn't miss anything with the Apex code.  This is my first Salesforce project so please be patient with me .

Now that we got the main part of the conditional working the final part of the logic is just to add the  vertical task assignment to the  vertical specific vertical user team:

 1.//and  if Op. Vertical_c = Finance then assign that  Opportunity task to financial user team role
   2.    // and  if Op. Vertical_c = Retail  then assign opportunity task  to Retail user team


I assume I will have to set up a and ID based Queue for Financial role  team and Queue team for the Retail role for the retail user team role. I guess I will need to change my object from Opportunity to leads since salesforce doesn't allow building role based queues for the opportunity object.

I would appreciate if you can  your insight for a code reference for this final part of the trigger.  so this is what we got so farthat works.

 

Thanks,

 

trigger OpportunityCreation on opportunity (after insert) {
    
    // If tasks are to be created then save them in a separate set and run dml operations outside loop statements	
    List<Task> tList = new  List<Task>();
    Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
	
    //loop through all new opportunities  saved
    for(Opportunity Op: Trigger.new)
    {
        // if the Opportunity amount is greater than 500000 AND Opportunity Vertical = Financial
        if (Op.Amount >= 500000 & Op.Vertical__c == 'Finance') {

            // create a user task that ...
            Task T        = new Task();
            T.Type        = 'Email';
            T.Description = 'Opportunity was created with amount  of  above 500,000 in your speciality field';
            T.OwnerId     = Op.OwnerId;
            T.WhatId      = Op.Id; //record id
	    
            // DO NOT RUN DML OPERATIONS INSIDE FOR LOOPS            
	    tList.add(T);
	    oppMap.put(Op.Id, Op);
	}
        else {
            // if the anual amount is less than 500000 and not financial vertical do nothing ....
        }
    }
	
    if(tList!=null && !tList.isEmpty()){
	OpportunityTriggerHelper.createTasks(tList, oppMap);
    }
}
public class OpportunityTriggerHelper {

	
	public static void createTasks(List<Task> tList, Map<Id, Opportunity> oppMap){
		Set<String> tIds = new Set<String>();
		try{
		
		    Database.SaveResult[] srTask  = Database.insert(tList, false);

			for (Database.SaveResult sr : srTask) {
				if (sr.isSuccess()) {
					// Operation was successful, so get the ID of the record that was processed and fire an email
					System.debug('Successfully created the task. ID: ' + sr.getId());					
					tIds.add(sr.getId());
				}
				else {
					// Operation failed, so get all errors                
					for(Database.Error err : sr.getErrors()) {
						System.debug('The following error has occurred.');                    
						System.debug(err.getStatusCode() + ': ' + err.getMessage());
						System.debug('Task fields that affected this error: ' + err.getFields());
					}
				}
			}
			
			if(tIds!=null && !tIds.isEmpty()){
				for(Task tObj : [SELECT Id, What.Name, WhatId FROM Task WHERE Id IN :tIds]){
					Opportunity oppObj = oppMap.get(tObj.WhatId);
					SendEmailNotification(oppObj.OwnerId, 'Finance Opportunity TASK WAS CREATED FOR YOU ON SALESFORCE  !!!', 'GO GETHEM', tObj.WhatId, tObj.What.Name);
				}
			}
		}
		catch(Exception err){
			system.debug('\n Error while creating tasks. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}
	}
	
	public static void SendEmailNotification(Id SendTo, string Subject, string BodyText, String LinkURL, String LinkLabel){
		try
		{
			Messaging.reserveSingleEmailCapacity(1);
			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
			mail.setTargetObjectId(SendTo);
			mail.saveAsActivity = false;
			mail.setSenderDisplayName('Salesforce custom big deal alert');
			mail.setSubject(Subject);

			if (LinkURL != null) {
				mail.setHtmlBody(BodyText + '<br />' + 'Click for details : ' + '<a href=' + LinkURL + '>' + LinkLabel + '</a>');
			}
			else {
				mail.setHtmlBody(BodyText);
			}
			Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
		}
		catch (Exception err) { 
			system.debug('\n Error while sending email. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}

	} 


}