Created
March 29, 2017 15:58
-
-
Save Walletau/62120db4a8a7702c4b842b434e5e7ae1 to your computer and use it in GitHub Desktop.
sample1MagicParents
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 static Set<Id> getTopAccountIds(Set<Id> accountsTargeted) { | |
Set<Id> topAccountIds = new Set<Id>(); | |
Set<Id> recursivelyTargetedAccountIds = new Set<Id>(); | |
for (Account targetedAccount : [ | |
SELECT Id, | |
Name, | |
ChildrenUserGroupId__c, | |
ChildrenIncludedUserGroupId__c, | |
UserGroupId__c, | |
ParentUserGroupId__c, | |
ParentID, | |
Parent.ParentID, | |
Parent.Parent.ParentID, | |
Parent.Parent.Parent.ParentID | |
FROM Account | |
WHERE Id IN :accountsTargeted | |
]) { | |
if (targetedAccount.Parent.Parent.Parent.ParentID != null) { | |
recursivelyTargetedAccountIds.add(targetedAccount.Parent.Parent.Parent.ParentID); | |
} else if (targetedAccount.Parent.Parent.ParentId != null) { | |
topAccountIds.add(targetedAccount.Parent.Parent.ParentId); | |
} else if (targetedAccount.Parent.ParentId != null) { | |
topAccountIds.add(targetedAccount.Parent.ParentId); | |
} else if (targetedAccount.ParentId != null) { | |
topAccountIds.add(targetedAccount.ParentId); | |
} else { | |
topAccountIds.add(targetedAccount.Id); | |
} | |
} | |
if (!recursivelyTargetedAccountIds.isEmpty()) { | |
topAccountIds.addAll(getTopAccountIds(recursivelyTargetedAccountIds)); | |
} | |
return topAccountIds; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment