Created
July 10, 2024 23:26
-
-
Save durveshshah/210feb4f86b893dc3a4f674db1855e72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class OpportunityTriggerHandler { | |
// Method to create the Account-Opportunity Map | |
public static Map<Id, List<Opportunity>> createAccountOpportunityMap(Set<Id> accountIds) { | |
// Step 1: Query Opportunities with related Account Ids | |
List<Opportunity> oppList = [ | |
SELECT Id, AccountId, Name | |
FROM Opportunity | |
WHERE AccountId IN :accountIds | |
]; | |
// Step 2: Initialize the Map | |
Map<Id, List<Opportunity>> accountOppMap = new Map<Id, List<Opportunity>>(); | |
// Step 3: Organize Opportunities into the Map | |
for (Opportunity opp : oppList) { | |
if (!accountOppMap.containsKey(opp.AccountId)) { | |
accountOppMap.put(opp.AccountId, new List<Opportunity>()); | |
} | |
List<Opportunity> oppListForAccount = accountOppMap.get(opp.AccountId); | |
oppListForAccount.add(opp); | |
} | |
// Return the map containing Account Ids as keys and lists of related Opportunities as values | |
return accountOppMap; | |
} | |
// Method to check if an account has opportunities and add error if not | |
public static void checkAccountHasOpportunities(List<Opportunity> opps) { | |
// Create a set with the Account Ids from the opportunities | |
Set<Id> accountIds = new Set<Id>(); | |
for (Opportunity opp : opps) { | |
if (opp.AccountId != null) { | |
accountIds.add(opp.AccountId); | |
} | |
} | |
// Populate the map using the createAccountOpportunityMap method | |
Map<Id, List<Opportunity>> accountOppMap = createAccountOpportunityMap(accountIds); | |
// Step 4: Check if each opportunity's account has any opportunities in the map | |
for (Opportunity opp : opps) { | |
if (opp.AccountId != null && !accountOppMap.containsKey(opp.AccountId)) { | |
opp.addError('The associated account does not have any opportunities.'); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment