User Story
As a user, I want to be restricted from creating a new case for an account with open cases so that existing cases can be resolved first.
Description:
When creating a new case in the system, if the related account already has open cases (i.e., cases with a status other than "Closed"), the system should prevent the creation of the new case and display an error message. This ensures that all unresolved issues are addressed before opening a new case.
Acceptance Criteria:
- If the account has open cases, the system displays an error message:
"You have an Existing Open Case for the related Account. You cannot create a new case without closing all existing ones!"
- If the account does not have open cases, the system allows the creation of the new case without errors.
- The functionality applies to all new case creation attempts.
Codes
Without Using Maps
public static void AddErrorOnCaseCreation(List<Case> newCases) {
List<Id> accountIds = new List<Id>();
for (Case caseRecord : newCases) {
if (caseRecord.AccountId != null) {
accountIds.add(caseRecord.AccountId);
}
}
List<Account> accountsWithOpenCases = [
SELECT Id,
(SELECT Id, Status FROM Cases WHERE Status != 'Closed')
FROM Account
WHERE Id IN :accountIds
];
for (Case caseRecord : newCases) {
for (Account account : accountsWithOpenCases) {
if (caseRecord.AccountId == account.Id && account.Cases.size() > 0) {
caseRecord.addError('You have an Existing Open Case for the related Account. ');
}
}
}
}
With Using Maps
public static void AddErrorOnCaseCreation(List<Case> newCases) {
Map<String, Case> accountCaseMap = new Map<String, Case>();
for (Case caseRecord : newCases) {
if (caseRecord.AccountId != null) {
accountCaseMap.put(caseRecord.AccountId, caseRecord);
}
}
List<Account> accountsWithOpenCases = [
SELECT Id,
(SELECT Id, Status FROM Cases WHERE Status != 'Closed')
FROM Account
WHERE Id IN :accountCaseMap.keySet()
];
for (Account account : accountsWithOpenCases) {
if (account.Cases.size() > 0) {
accountCaseMap.get(account.Id).addError('You have an Existing Open Case for the related Account. ');
}
}
}
By Ignoring Best Practices
public static void AddErrorOnCaseCreation(List<Case> newCases) {
for (Case caseRecord : newCases) {
if (caseRecord.AccountId != null) {
List<Case> openCases = [
SELECT Id
FROM Case
WHERE AccountId = :caseRecord.AccountId AND Status != 'Closed'
];
if (!openCases.isEmpty()) {
caseRecord.addError(
'You have an Existing Open Case for the related Account.');
}
}
}
}