SFDC: Re-Running Lead Assignment Rules

Often when working with a company on lead processes (or any process) there is a point when you want to assign the record to someone else. Maybe its an escalation of a record (thinking cases) or its a high value / priority customer that we want an experienced agent to handle (leads). Usually most companies handle this with a series of automations that trigger when a specific field is edited or when some flag is raised.

This is all great, but these rules usually are entered piecemeal over time (as various admins enter and leave the business). The result is most always that there are 10 different automations that need to be checked whenever a new one is added and 3 of them are not used anymore. Also, they are a mess of Flows, process builders, triggers or workflows. This setup makes it very hard to troubleshoot issues as the logic is spread among various locations.
Alternatively, we could keep all the logic in the assignment rules and just run them again when the record in question meets our criteria! This would keep our logic down too 2 places for routing and makes it much easier to maintain complex processes within Leads (or cases).

Assignment Rules


The first step is to create a new Apex class. My preferred method for running this code is in an invocable method so you can call it from a flow (or other automation). Below is some example code.

public class RunAssignmentRules {

    @InvocableMethod
    public static void assignLeads(List<Id> leadIds){
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.AssignmentRuleHeader.useDefaultRule = TRUE;
        System.debug('Running assignment rules for Lead ' + leadIds);
        List<Lead> toAssign = [SELECT Id FROM Lead WHERE Id in :leadIds];
        Database.update(toAssign,dmo);
    }

The first step is to get the Data passed into the function that you want. Usually a list of leads or cases. Then you have to pull up the AssignmentRuleHeader and set the default rule header to True. This flag is what tells Salesforce to use the assignment rules for the specific (See link below for the docs). Then when you update the records, Salesforce will run the assignment rules on them.
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Database_AssignmentRuleHeader.htm

Now to trigger this block of code, we want to create a flow (but you could use any other form of automation).

First choose your criteria for how you will run the flow. With the most recent flow updates, you can really limit when they are triggered!

Flow Example

Flow Conditions

Then Add your custom apex action for running the assignment rules!

For whatever reason, I had trouble running the flow immediately so I had it delayed by one minute. But it works quite nicely! Anyway, hopefully this helped your organization clean up your assignments (and also was a good introduction to invocable classes).