User Story
As a Salesforce admin, I want to automatically update the Rating
field of Accounts based on the number of closed Cases, so that I can categorize Accounts by their engagement level.
Description:
When Accounts have associated closed Cases, their Rating
should be dynamically updated to reflect their level of activity and engagement:
- Cold: Accounts with fewer than 2 closed Cases.
- Warm: Accounts with 2 to 5 closed Cases.
- Hot: Accounts with more than 5 closed Cases.
This functionality ensures the Rating
field is always up-to-date and helps prioritize Accounts for engagement.
Codes
public class AccountRatingUpdater {
public static void updateAccountRatings(List<Account> acList) {
List<Id> IDs = new List<Id>();
for(Account ac : acList){
IDs.add(ac.Id);
}
List<Account> accountsToUpdate = [
SELECT Id, Rating,
(SELECT Id, IsClosed FROM Cases WHERE IsClosed = true)
FROM Account WHERE Id IN: IDs
];
for (Account acc : accountsToUpdate) {
Integer closedCaseCount = acc.Cases.size();
if (closedCaseCount < 2) {
acc.Rating = 'Cold';
} else if (closedCaseCount >= 2 && closedCaseCount <= 5) {
acc.Rating = 'Warm';
} else if (closedCaseCount > 5) {
acc.Rating = 'Hot';
}
}
try {
update accountsToUpdate;
} catch (DmlException e) {
System.debug('Error updating accounts: ' + e.getMessage());
}
}
}