Skip to content

Instantly share code, notes, and snippets.

@dsilvadeepal
Created December 21, 2017 21:56
Show Gist options
  • Save dsilvadeepal/9848995ddd3a1237ad2ca54263005259 to your computer and use it in GitHub Desktop.
Save dsilvadeepal/9848995ddd3a1237ad2ca54263005259 to your computer and use it in GitHub Desktop.
A trigger that sets a case status to 'Closed' if there are more than 2 cases created that day associated with the same contact Also close cases if there are more than 3 cases created on that account that day
/*
Write a trigger that sets a case status to 'Closed' if there are more than 2 cases created
that day associated with the same contact
Also close cases if there are more than 3 cases created on that account that day
*/
trigger MaxCases on Case (before insert) {
for(Case myCase : Trigger.new) {
//Find all cases created today
if(myCase.ContactId != null) {
List<Case> casesCreatedToday = [SELECT Id
FROM Case
WHERE ContactId = :myCase.ContactId
AND CreatedDate = TODAY];
//Close the case
if(casesCreatedToday.size() >= 2){
myCase.Status = 'Closed';
}
}
//Find all cases with this account created today
if(myCase.AccountId != null){
List<Case> casesTodayFromAccount = [SELECT Id
FROM CASE
WHERE AccountId = :myCase.AccountId
AND CreatedDate = TODAY];
//Close the case
if(casesTodayFromAccount.size() >=3){
myCase.Status = 'Closed';
}
}
}
}
//Test Class
@isTest
private class MaxCasesTest {
@isTest static void noCasesToday(){
Contact con = new Contact();
con.LastName = 'Flint';
insert con;
Case myCase = new Case();
myCase.ContactId = con.Id;
myCase.Status = 'New';
insert myCase;
Case updatedCase = [SELECT Status
FROM Case
WHERE Id = :myCase.Id];
System.assertEquals('New', updatedCase.Status);
}
@isTest static void threeCasesTodayOnContact(){
Contact con = new Contact();
con.LastName = 'Flint';
insert con;
List<Case> oldCases = new List<Case>();
for(integer i = 0; i < 2; i++){
Case oldCase = new Case();
oldCase.ContactId = con.Id;
oldCases.add(oldCase);
}
insert oldCases;
Case myCase = new Case();
myCase.ContactId = con.Id;
insert myCase;
Case updatedCase = [SELECT Status
FROM Case
WHERE Id = :myCase.Id];
System.assertEquals('Closed', updatedCase.Status);
}
@isTest static void fourCasesTodayOnAccount(){
Account acc = new Account();
acc.Name = 'Windsor Hotels';
insert acc;
List<Case> oldCases = new List<Case>();
for(integer i = 0; i < 3; i++){
Case oldCase = new Case();
oldCase.AccountId = acc.Id;
oldCases.add(oldCase);
}
insert oldCases;
Case myCase = new Case();
myCase.AccountId = acc.Id;
insert myCase;
Case updatedCase = [SELECT Status
FROM Case
WHERE Id = :myCase.Id];
System.assertEquals('Closed', updatedCase.Status);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment