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
TBouscalTBouscal 

SingleEmailMessage.setSaveAsActivity doesn't save as activity

Hello world!

What am I overlooking?  
When I run my test I can see the debug line stating that the send was successful but my assertion fails because the expected task record doesn't exist.  
For (Contact c:myRecipients){
                    Id EvId = EventMap.get(c.id);
                    String theMsg = ('Please click the link below, or copy and paste into your browser to complete a brief survey ');
                    theMsg = theMsg + ('related to your recent interaction with an Acme service representative. \n \n '); 
                    theMsg = theMsg + ('http://www.acmewidgets.com/survey?iv=xfjtzd9uazro&q1=' + EvId + '&q2=' + c.id);
                    System.debug(theMsg);
                    
                    Messaging.SingleEmailMessage myEmail = new Messaging.SingleEmailMessage();
                    myEmail.setSenderDisplayName(owa.DisplayName); 
                    myEmail.setReplyTo(owa.Address);
                    System.debug('c.id = ' + c.id); 
                    myEmail.setTargetObjectId(c.id);
                    myEmail.setUseSignature(false); 
                    myEmail.setSubject('Please complete this survey from Acme');
                    myEmail.setPlainTextBody(theMsg);
                    myEmail.setSaveAsActivity(true);
                    
                    Messaging.SingleEmailMessage[] theMessages = new List<Messaging.SingleEmailMessage>{myEmail};
                        Messaging.SendEmailResult[] results = Messaging.sendEmail(theMessages);  
                    
                    
                    if (results[0].success){
                        System.debug('The email was sent'); 
                    } else {
                        System.debug('The email failed to send: ' + results[0].errors[0].message);
                    }
                    
                }

 
Amit Chaudhary 8Amit Chaudhary 8
can you please post you test class as well which is failing ?
TBouscalTBouscal
Sure thing, when the account is created a task is assigned in a regular workflow.  This one should be the 2nd task on the account which is why my assertion looks for 2.  I've also run a loop around the returned list and confirmed that the new account task is the one that is created and the email task is not.

 
public static testmethod void testNewEventNoTask()
    {  // Event Record Type: 01270000000DS5i = FaceTime
        date theDate = Date.today(); 
        datetime theDateTime=DateTime.now();
        // Account/Contact/Event for test
        Account Acc1 = createAccount();
        Contact Con1 = createContact(Acc1);
        Event Evt1 = createEvent(Con1.id,Acc1.id); 
        System.debug('**** First set:  Account:'+acc1.id+' Contact:'+con1.id+' Event:'+evt1.id);
        Evt1.Event_Status__c='Completed'; 
        Update Evt1;         
        List<Task> TskList1 = [SELECT id, subject FROM task WHERE whatid=:Acc1.Id]; 
        for(Task t:TskList1){
            System.debug('Acc1 Tasks: ' + t.subject); 
        }        
        System.assertEquals(2, TskList1.size());        
    }





 
Amit Chaudhary 8Amit Chaudhary 8
Whan you are executing your above code ? That is trigger ? please post full code
TBouscalTBouscal

Before Update.

I only posted that snippet because the only item failing is the setSaveAsActivity = true.  The email says it sends but the task it should have created didn't get created.

Here's the trigger: 

/**
* Event trigger
*/
trigger Events on Event (after delete, after insert, after undelete, after update, before insert, before update, before delete) {
    
    FS_SurveyEmail fs = new FS_SurveyEmail();
    
    if(Trigger.isAfter && Trigger.isUpdate) {

    }
    else if (Trigger.isAfter && Trigger.isDelete) {
        
    }
    else if (Trigger.isAfter && Trigger.isInsert) {

    }
    else if (Trigger.isAfter && Trigger.isUndelete) {
        
    }
    else if (Trigger.isBefore && Trigger.isUpdate){
 
            fs.checkEvents(Trigger.new);
    }
    else if (Trigger.isBefore && Trigger.isDelete){
        
    }
    else if (Trigger.isBefore && Trigger.isInsert){

    }
}

The class: 
public with sharing class FS_SurveyEmail {
    
    public void checkEvents(Event[] ev){
        date dtRange=date.today(); 
        dtRange=dtRange.addMonths(-6);
        
        Id recTypeId='01270000000DS5i';
        List<Id>EventMembers = new List<Id>();
        Map<Id,Id> EventMap = new Map<Id, Id>(); 
        
        If (ev !=null){ 
            For (Event e:ev){
                if(e.Account_Status__c == 'Client' && e.RecordTypeId==recTypeid && e.Send_Survey__c==true && e.Event_Status__c=='Completed' && e.Survey_Sent__c==false){
                    If(e.WhoId != null){
                        EventMembers.add(e.WhoId);
                        EventMap.put(e.whoid, e.id);
                        e.Survey_Sent__c=true; // update the event field so this doesn't fire again
                    }
                }
            }
        }
        
        If(EventMembers.size()>0){
            string EmailFailure=null;
            // generate list of contacts to send message to  
            List<Contact>myRecipients = [SELECT id, firstname, lastname, email FROM contact WHERE id IN :EventMembers AND (NOT email LIKE '%acme%') ];
            System.debug('myRecipients size = ' + myRecipients.size()); 
            // query all prior tasks for these contacts that meet the survey criteria
            List<Task> myTasks = [SELECT id,whoid,subject FROM task WHERE createddate > :dtRange AND subject = 'Email: Please complete this survey from Acme.' AND whoid IN :EventMembers];
            
            // compare contact list to task list, if a prior task exists, remove the contact from the list.
            for(Integer c=myRecipients.size()-1; c>=0; --c){
                for(Task t:myTasks){
                    try{
                        System.debug(t.Subject);
                        if(t.Subject=='Email: Please complete this survey from Acme.'){
                            if(myRecipients.get(c).id == t.whoid){myRecipients.remove(c);}
                        }
                    }
                    catch(System.ListException e){
                    }
                }
            }
            // insure we still have at least one record to mail to or exit
            System.debug('myRecipients.size() = ' + myRecipients.size());
            if(myrecipients.size()>0){
                // create email objects as a list
                
                List<Messaging.SingleEmailMessage> allMsg = new List<Messaging.SingleEmailMessage>();
                
                OrgWideEmailAddress owa = [SELECT id, DisplayName, Address FROM OrgWideEmailAddress WHERE DisplayName='Field Services' LIMIT 1];
                // append new message to above list for each Contact
                
                For (Contact c:myRecipients){
                    Id EvId = EventMap.get(c.id);
                    String theMsg = ('Please click the link below, or copy and paste into your browser to complete a brief survey ');
                    theMsg = theMsg + ('related to your recent interaction with an Acme service representative. \n \n '); 
                    theMsg = theMsg + ('http://www.acme.com/survey?iv=xfjtzd9uazro&q1=' + EvId + '&q2=' + c.id);
                    System.debug(theMsg);
                    
                    Messaging.SingleEmailMessage myEmail = new Messaging.SingleEmailMessage();
                    myEmail.setSenderDisplayName(owa.DisplayName); 
                    myEmail.setReplyTo(owa.Address);
                    System.debug('c.id = ' + c.id); 
                    myEmail.setTargetObjectId(c.id);
                    myEmail.setUseSignature(false); 
                    myEmail.setSubject('Please complete this survey from Acme');
                    myEmail.setPlainTextBody(theMsg);
                    myEmail.setSaveAsActivity(true);
                    
                    Messaging.SingleEmailMessage[] theMessages = new List<Messaging.SingleEmailMessage>{myEmail};
                        Messaging.SendEmailResult[] results = Messaging.sendEmail(theMessages);  
                    
                    
                    if (results[0].success){
                        System.debug('The email was sent'); 
                    } else {
                        System.debug('The email failed to send: ' + results[0].errors[0].message);
                    }
                    
                }
            }
        }
    }
}

and the test class: 
(testNewEventNoTask is the only method that fails)
 
@IsTest(SeeAllData=True)

public class FS_SurveyEmail_Test
{
    public static testmethod void testNewEventNoTask()
    {  // Event Record Type: 01270000000DS5i = ClientFaceTime
        date theDate = Date.today(); 
        datetime theDateTime=DateTime.now();
        // Account/Contact/Event for non Acme
        Account Acc1 = createAccount();
        Contact Con1 = createContact(Acc1);
        Event Evt1 = createEvent(Con1.id,Acc1.id); 
        System.debug('**** First set:  Account:'+acc1.id+' Contact:'+con1.id+' Event:'+evt1.id);
        Evt1.Event_Status__c='Completed'; 
        Update Evt1;         
        List<Task> TskList1 = [SELECT id, subject FROM task WHERE whatid=:Acc1.Id]; 
        for(Task t:TskList1){
            System.debug('Acc1 Tasks: ' + t.subject); 
        }        
        System.assertEquals(2, TskList1.size());        
    }
    public static testmethod void testNewEventOneTask(){
        // Account/Contact/Event for Acme
        Account Acc2 = createAccount();
        Contact Con2 = createContact(Acc2); 
        Event Evt2 = createEvent(Con2.id, Acc2.id);
        //        System.debug('**** Second set:  Account:'+acc2.id+' Contact:'+con2.id+' Event:'+evt2.id);   
        Con2.Email='noreply@acme.com'; // do not survey Acme
        Con2.FirstName='Thomas'; 
        Con2.LastName='Jefferson'; 
        Update Con2;         
        Evt2.Event_Status__c='Completed'; 
        Update Evt2;         
        List<Task> TskList2 = [SELECT id, subject FROM task WHERE whatid=:Acc2.Id]; 
        for(Task t2:TskList2){
            System.debug('Acc2 Tasks: ' + t2.subject); 
        }       
        System.assertEquals(1, TskList2.size());    
    }
    public static testmethod void testNew_SF_Event(){    
        
        // Account/Contact/Event/Task for previously surveyed (expect no survey)
        Account Acc3 = createAccount(); 
        Contact Con3 = createContact(Acc3); 
        Task Tsk3 = createTask(Con3.Id, Acc3.id);
        Event Evt3 = createEvent(Con3.id, Acc3.id); 
        System.debug('**** Third set:  Account:'+acc3.id+' Contact:'+con3.id+' Event:'+evt3.id + ' Task:' + Tsk3.id);                
        Evt3.Event_Status__c='Completed';
        Update Evt3;        
        List<Task> TskList3 = [SELECT id, subject FROM task WHERE whatid=:Acc3.Id]; 
        for(Task t3:TskList3){
            System.debug('Acc3 Tasks: ' + t3.subject);
        }
        System.assertEquals(2, TskList3.size());       
    }
    
    
    public static Account createAccount(){
        Account UsAcct = new Account(
            recordtypeid='01270000000Q7Td', 
            name='Test Account', 
            Status__c='Client',
            Line_of_Business__c='Widgets',
            phone='8005551212', 
            currencyisocode='USD'); 
        
        insert UsAcct;
        return UsAcct; 
    }    
    public static Contact createContact(Account UsAcct){
        Contact UsCont = new Contact(email='noreply@acme.com', firstname='George', lastname='Washington',accountid=UsAcct.id);
        insert UsCont;        
        return UsCont; 
    }
    public static Task createTask(Id ContactId, Id AccountId){
        
        Task newTask = new Task(
            whoid=ContactId, 
            whatid=AccountId, 
            Subject='Email: Please complete this survey from Acme.'); 
        insert newTask;
        return newTask; 
    }
    
    public static Event CreateEvent(Id ContactId, Id AccountId){
        Date theDt = Date.today();
        DateTime theDtTm = DateTime.now();
        Event newEvent = new Event(
            whoid=ContactId, 
            whatid=AccountId,
            recordtypeid='01270000000DS5i', 
            Type='Site Visit', 
            ActivityDate=theDt,
            ActivityDateTime=theDtTm,
            Time_on_site__c = .25, 
            durationinminutes=15, 
            Primary_Products_addressed__c = 'Widgetsr',                                 
            Primary_Product_Time_hours__c = .25, 
            Description='This is a test event',
            Send_Survey__c=true,
            Survey_Sent__c=false,
            Event_Status__c='Scheduled'
        ); 
        insert newEvent; 
        return newEvent;         
    }    
    
}


The desired outcome is that a message is sent when an event is completed as long as the customer isn't Acme and they haven't received a survey in the past 6 months.

 
Amit Chaudhary 8Amit Chaudhary 8
Can you please to fatch Task base on Who ID
 List<Task> TskList1 = [SELECT id, subject FROM task WHERE whoid=:c.Id];

Let us know if this will help you
TBouscalTBouscal
Thank you Amit, however all the assertions failed using the whoid.