Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.7 kB
2
Indexable
Never
trigger HandleOverflowChildCases on Case (before insert, before update) {
    Set<Id> parentCaseIds = new Set<Id>();
    Map<Id, Integer> agentCapacityMap = new Map<Id, Integer>();

    for (Case childCase : Trigger.new) {
        if (childCase.ParentId != null) {
            parentCaseIds.add(childCase.ParentId);
        }
    }

    if (!parentCaseIds.isEmpty()) {
        // Query parent cases to get their owners
        List<Case> parentCases = [SELECT Id, OwnerId FROM Case WHERE Id IN :parentCaseIds];

        // Query the current case count for each agent
        for (Case parentCase : parentCases) {
            Integer currentCapacity = [SELECT COUNT() FROM Case WHERE OwnerId = :parentCase.OwnerId];
            agentCapacityMap.put(parentCase.OwnerId, currentCapacity);
        }

        for (Case childCase : Trigger.new) {
            if (childCase.ParentId != null) {
                Case parentCase = parentCases.get(parentCaseMap.get(childCase.ParentId));

                if (parentCase != null && parentCase.OwnerId != null) {
                    Integer currentCapacity = agentCapacityMap.get(parentCase.OwnerId);

                    if (currentCapacity != null && currentCapacity >= [YOUR_CAPACITY_LIMIT]) {
                        childCase.Deferred_Assignment__c = true;
                        childCase.OwnerId = [SELECT Id FROM Group WHERE Name = 'Deferred Child Cases Queue' LIMIT 1].Id;
                    } else {
                        childCase.OwnerId = parentCase.OwnerId;
                        agentCapacityMap.put(parentCase.OwnerId, currentCapacity + 1); // Increment capacity count
                    }
                }
            }
        }
    }
}
Leave a Comment