Tuesday 23 September 2014

Service Cloud's Support.EmailTemplateSelector Example

A cool feature for Salesforce Service agents is being able to send e-mails back to customers directly from the Case Feed using the "Email" publisher action.

Using things like Auto-response rules and Quick Text allows agents to manage customer queries with incredible power and ease, but one case scenario I found that has come up a number of times is wanting to have almost case specific boiler plate text pre-filled in the e-mail, such as salutations and signatures.

It is definitely not uncommon to have more than one "product" or "channel" being managed through Service Cloud support cases, often by the same group of agents, changing their hats as different cases need attention, and so presenting the most appropriate Email Template for them to "fill in" as a response to a customer comes down to the "Enable Default Email Templates" feature..


This can be found and enabled in Setup > Customise > Cases > Support Settings towards the bottom.. but don't go over then enabling it just yet, as you need to do some ground work first.

Once enabled, this setting lets you use an Apex Class to determine which Email template you will use for this specific case. This literally throws the full power of Apex into the decision engine you are about to craft.

I am going to talk you through using this feature to deliver two different e-mail templates which can be used depending on whether a case was delivered to the system by email-to-case or web-to-case.. and this assumes you have configured these two channels to set the "Origin" of the case to Email and Web. In each case we want to salute the customer, thank them for engaging on the relevant channel and then sign off with a different help desk name. The middle of the e-mail will be left blank for the agent to fill in their response.

So

Step 1. Make the e-mail templates
I won't molly coddle you through this process. Go into Setup > Communication Templates > Email Templates and using your favourite format, folder structure and style, craft two different e-mail templates for your support staff. My Email support one looks like this:



Once you have them...

Step 2. Create your Apex Class
Now this really is the crux of it. You have to provide an Apex Class that implements the Support.EmailTemplateSelector interface, and implements the global method global ID getDefaultEmailTemplateId(ID caseId) in it. This returned ID is the template that will be placed into the Email box when a case is loaded into the Case Feed.

So here is where you can get complicated, there are examples using dozens of templates, custom objects and custom settings to determine what template to load, so go nuts! In this simple example though, I am going to use the Case Origin to load a relatively named template, or return null (which will just use the default email format).

This is all my class contains:

global class DefaultCaseEmailTemplates implements Support.EmailTemplateSelector {
 
    global ID getDefaultEmailTemplateId(ID caseId){
        // Load the relevant case details
        Case thisCase = [SELECT Origin FROM Case WHERE Id=:caseId];
        
        // Concatenate the "matching" support e-mail name
        String templateName = thisCase.Origin.replace(' ', '_') + '_Support';
                
        // Load the template Id by this name
        List emailTemplate = [SELECT id 
                              FROM EmailTemplate 
                              WHERE DeveloperName =  :templateName];
        
        // If we got one, return it, otherwise return null
        if (!emailTemplate.isEmpty()) {
            // return the template Id
            return emailTemplate.get(0).Id;
        } else {
            // returning null means the system just presents a blank response template
            return null;
        }
    }
}

And it is as simple as that for this case scenario. "Web" origin will load a template called "Web_Support" and "Email" Origin will load "Email_Support" - if the user wants to add more channels to the origin, they can do so, and either add a new template (with "_Support" at the end) or just let it fall to the default. Lovely.

Step 3. Test that class
Now, personally, I do test driven development, so this would be step 1.5 technically in this flow, but I have included it after the Apex Class, because I know how to keep an audience interested ;-)

Testing this class isn't too difficult, but there is a trick or two - due to some old friends such as setting up system objects and user records in the same context.  

(One short fall of this test class is that it requires a user in the System Administrator profile to be available... I personally consider that a given though)

Here is the simplest (single pass, positive scenario) test class for this. I suggest you augment this a little for your own implementation if you believe in good testing!

@isTest
public class DefaultCaseEmailTemplatesTest {

    @isTest
    static void LoadEmailTemplates_SuccesfulScenario_ReturnsTemplateId() {
 
        Id templateId;
    
        User thisUser = [SELECT Id FROM User WHERE profile.name ='System Administrator' LIMIT 1];
        System.runAs(thisUser) {
            templateId = insertTemplate();
        }
        
        Id caseId = insertCase();
        
        DefaultCaseEmailTemplates dcet = new DefaultCaseEmailTemplates();

        Id result = dcet.getDefaultEmailTemplateId(caseId);
        
        System.assertEquals(templateId, result);
        
    }

    private static Id insertTemplate() { 
  
        EmailTemplate emailTemplate = new EmailTemplate(DeveloperName='test', Name='test', FolderId=UserInfo.getUserId(), TemplateType='Text');
        insert emailTemplate;
        
        return emailTemplate.Id;
    }

    private static Id insertCase() {
 
        Case testCase = new Case(Origin='Email Just Ingredients');
        insert testCase;
        
        return testCase.Id;    
    }
}


Ahh. I love it when a test class ends up 10 times the length of the code it is testing!

Step 4. Enable this class
Now it is time to head back over to  Setup > Customise > Cases > Support Settings and set "Enable Default Email Templates" at this point it will ask for your class, so point it at it using the lookup box.,

Step 5. Test it out
Head over to your Case page, or Case Feed page, for a case that has one of the Origins you specified, and click to open the Email publisher action (if you don't have this action, you will have to Google how to do that! (hint: it's under Actions on the Page Layout Editor) - and if everything has gone right, you should see you e-mail template loaded into the box, ready to be completed!


If you load a case from a different origin, you will either get their adjusted template, or no template at all. Easy!

Now - go make that Apex Class over-complicated!