Apex Max Cases Per Account Trigger

Fun coding challenge from:

Show me the code: Extravagant Record Creation

Max cases Trigger

trigger MaxCaseTrigger on Case (before insert) {
    CaseHelper ch = new CaseHelper();
    ch.checkMaxCase(Trigger.new);
}

Max cases helper class

public with sharing class CaseHelper {
    
    private static Case_Settings__c caseSettings;
    private static Integer maxCases = 99;
    
    static {
     Map<String, Case_Settings__c> setting = Case_Settings__c.getall();
     caseSettings = setting.get('Sandbox_Settings');
     
     if (caseSettings!=null && caseSettings.Max_Cases__c!=null){
         maxCases = Integer.valueOf(caseSettings.Max_Cases__c);
     }
    }
    
    public void checkMaxCase(List<Case> newCases){
        Map<Id, Case> accountIdToCaseMap = new Map<Id, Case>();
        for (Case newCase :newCases){
            if (newCase.AccountId!=null)
                accountIdToCaseMap.put(newCase.OwnerId, newCase);
        }
        
        List<AggregateResult> agList = [Select count(id) caseCount, OwnerId, Owner.Name from Case where OwnerId IN :accountIdToCaseMap.keySet() Group By OwnerId, Owner.Name Having count(id)>=:maxCases];
        
        List<Case> casesToThrowError = new List<Case>();
        Map<Id, String> caseToContactNameMap = new Map<Id, String>();
        for (AggregateResult ag : agList){
            String ownerId = (String)ag.get('OwnerId');
            if (accountIdToCaseMap.containsKey(ownerId)){
                Case errorCase = accountIdToCaseMap.get(ownerId);
                casesToThrowError.add(errorCase);
                caseToContactNameMap.put(ownerId, (String)ag.get('Name'));
            }
        }
         
        if (!casesToThrowError.isEmpty()){
            for (Case caseToThrowError : casesToThrowError){
                caseToThrowError.addError('Too many cases created this month for user ' + caseToContactNameMap.get(caseToThrowError.OwnerId) + ' (' + caseToThrowError.OwnerId +  ') : ' + maxCases);
            }
        }
    }
}

Max cases helper test

@isTest
public class CaseHelperTest {

    static Integer maxCasesToCreate = 99;
    
    @TestSetup static void setup(){
        Case_Settings__c caseSettings = new Case_Settings__c(Name='Sandbox_Settings', Max_Cases__c=maxCasesToCreate);
        insert caseSettings;
    
        Account newAccount = new Account(Name='Test');
        insert newAccount;
        
        Contact newContact = new Contact(FirstName='First', LastName='Last', AccountId=newAccount.Id, Email='test@google.com');
        insert newContact;
    
        List<Case> caseLst = new List<Case>();
        
        for (Integer k = 0; k < maxCasesToCreate-1; k++){
            Case newCase = new Case();
            newCase.OwnerId = UserInfo.getUserId();
            newCase.AccountId = newAccount.Id;
            newCase.ContactId = newContact.Id;
            newCase.Status = 'Open';
            caseLst.add(newCase);
        }
        
        insert caseLst;
    }

     @isTest static void belowThreshold(){
        Case_Settings__c cs = Case_Settings__c.getInstance('Sandbox_Settings');
        cs.Max_Cases__c = 101;
        update cs;
        
        Test.startTest();
            System.assertEquals([Select Id from Case where ContactId!=null].size(), 98);
            Case newCase = new Case();
            newCase.OwnerId = UserInfo.getUserId();
            newCase.AccountId = [Select Id from Account][0].Id;
            newCase.ContactId = [Select Id from Contact][0].Id;
            newCase.Status = 'Open';
            insert newCase;
        Test.stopTest();
    }

    @isTest static void errorAboveThreshold(){
        Test.startTest();
            System.assertEquals([Select Id from Case where ContactId!=null].size(), 98);
            Case newCase = new Case();
            newCase.AccountId = [Select Id from Account][0].Id;
            newCase.ContactId = [Select Id from Contact][0].Id;
            newCase.Status = 'Open';
            try{
                insert newCase;        
            } catch(Exception ex){         
                System.assert(ex.getMessage().contains('Too many cases created this month for user'));
            }
        Test.stopTest();
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: