Tuesday, November 15, 2016

Fire Time Based Workflows based on the Business Hours of the system

Use Case
Workflow rules don't abide business hours, it is not possible through standard salesforce functionality to fire Time Based Workflows based on the Business Hours of the system, because standard salesforce workflows fire based on real hours.

Solution

To apply the business hour, we need to make sure that our date/time field which is used in Time Based Workflow, is calculated through BusinessHours.Diff() method.
Below snippet of code calculates Case Age based on Business Hours of the system, and a workflow alert is sent evaluating the calculated field highlighted in green.

Reusable Code

BusinessHours defaultHours = [select Id from BusinessHours where IsDefault=true];
Set<Id> caseset = new Set<Id>();

    For (Case c :Trigger.new ){
        caseset.add(c.id);
    }

    for (Case c :[select id,BusinessHoursId, status,LastModifiedDate,           closeddate,CreatedDate from case where id in:caseset])

    {
Id hoursToUse = c.BusinessHoursId!=null?c.BusinessHoursId:defaultHours.Id;

         if(c.status!='Closed')
         {
//The diff method comes back in milliseconds, so we divide by 3600000 to get hours.
         Double CaseAgeBusinessHours= BusinessHours.diff(hoursToUse,     c.CreatedDate,c.LastModifiedDate)/3600000.0;
        c.Case_Age_in_Business_Hours__c   =   CaseAgeBusinessHours;
        }
           }   

No comments:

Post a Comment