Apex Triggers - 89 (Persistent Interview Scenario)
When an Account already has 2 existing cases, and a 3rd new case is created under that same Account, the system must automatically create a High Priority Task assigned to the parent Account.
============================================================
trigger CaseCountTrigger on Case (after insert) { // Ensure the execution only runs during the after insert context if (Trigger.isAfter && Trigger.isInsert) { CaseCountTriggerHandler.handleAfterInsert(Trigger.new); } }
========================================================
public class CaseCountTriggerHandler {
public static void handleAfterInsert(List<Case> newCases) {
Set<Id> accountIds = new Set<Id>();
// 1. Collect Account IDs from the incoming cases
for (Case c : newCases) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
// Null check on the set to optimize performance
if (!accountIds.isEmpty()) {
Map<Id, Integer> accCaseMap = new Map<Id, Integer>();
// 2. Fetch all cases associated with these accounts to determine the total count
List<Case> existingCases = [SELECT Id, AccountId FROM Case WHERE AccountId IN :accountIds];
// 3. Build the Map with AccountId as Key and Total Case Count as Value
for (Case c : existingCases) {
if (accCaseMap.containsKey(c.AccountId)) {
accCaseMap.put(c.AccountId, accCaseMap.get(c.AccountId) + 1);
} else {
accCaseMap.put(c.AccountId, 1);
}
}
List<Task> tasksToInsert = new List<Task>();
// 4. Iterate over new cases and check if the total count exceeds 2
for (Case c : newCases) {
if (c.AccountId != null) {
Integer totalCount = accCaseMap.containsKey(c.AccountId) ? accCaseMap.get(c.AccountId) : 0;
// If total cases (including the new one) are greater than 2, trigger a task
if (totalCount > 2) {
Task newTask = new Task();
newTask.Subject = 'Review High Case Volume';
newTask.Priority = 'High';
newTask.Status = 'Not Started';
newTask.Description = 'New task has been created for newly created case';
newTask.WhatId = c.AccountId; // Relates the task to the Parent Account
newTask.ActivityDate = Date.today().addDays(2); // Sets due date to 2 days from today
tasksToInsert.add(newTask);
}
}
}
// 5. Perform DML outside of the loop to stay within Governor Limits
if (!tasksToInsert.isEmpty()) {
insert tasksToInsert;
}
}
}
}
Comments
Post a Comment