Case Escalation – Post in Chatter Private Group

I came across a scenario that when a Customer service agent change case status to ‘Escalated’ a group of users should be notified. Though this can be achieved in number of ways in Salesforce, but here I am going to give an example relating to Chatter feed. A  feedItem in Private Group should be posted when case status changes, this Private Group carries users that should be notified.

This works even if a customer service agent is not a member of Private Group, a trigger event is fired when a case status changes to ‘Escalated’, as soon as status changes our code creates a new feedItem with Case Number and URL of that Case,

Lets go through code,

trigger ChatterPostTrigger on Case (after insert, after update) {

//on insert and update only
if (Trigger.isInsert || Trigger.isUpdate){

ID groupId = [Select Id from CollaborationGroup where Name = ‘Demo Private Group’].Id;
List<feedItem> postFeed = new List<feedItem>();

for (Case c : Trigger.new){

if (c.status == ‘Escalated’){

//URL to post in Chatter.
String caseURL = URL.getSalesforceBaseUrl().toExternalForm() + ‘/’ + c.id;

//Create new chatter post
feedItem fi = new feedItem();
fi.Body = ‘Case Number ‘ + c.CaseNumber + ‘ is Escalated, please have a look ‘ + caseURL ;
fi.ParentId = groupId;

postFeed.add(fi);
}
}

//DML to create postFeed in Private Chatter Group
if (!postFeed.isEmpty())
insert postFeed;
}
}

Test Class

@isTest(seeAllData = true)
private class ChatterPostTest{

static testmethod void feedtestMethod(){

ID groupID = [Select Id from CollaborationGroup where Name = ‘Demo Private Group’].Id;

Case c = new Case();
c.origin = ‘Email’;
c.status = ‘New’;

insert c;

String caseURL = URL.getSalesforceBaseUrl().toExternalForm() + ‘/’ + c.id;

Case updateCase = [Select Id, CaseNumber, status from case where Id =: c.Id];
updateCase.status = ‘Escalated’;

test.StartTest();
update updateCase;
test.StopTest();

FeedItem f = [Select body from FeedItem where ParentId =: groupID order By createdDate DESC Limit 1];

System.assertEquals (f.body,’Case Number ‘ + updateCase.CaseNumber + ‘ is Escalated, please have a look ‘ + caseURL);

}

}