Skip to content

Instantly share code, notes, and snippets.

@infocynic
Created March 29, 2024 13:20
Show Gist options
  • Save infocynic/31fba2c5b4346733ca8f25da58b27e46 to your computer and use it in GitHub Desktop.
Save infocynic/31fba2c5b4346733ca8f25da58b27e46 to your computer and use it in GitHub Desktop.
Apex Trigger Handler for Bucketing Contacts
//this class assumes you are running in a trigger context. it would be better to inherit from a base trigger class and replace
//the reference on line 11 with that.
public without sharing class ContactTriggerHandler {
private map<string, id> saMap = new Map<string, id>();
public static final Integer keyLength = 2;
// Constructor
public ContactTriggerHandler() {
//better: replace static reference to trigger with something from a base handler
if (Trigger.isInsert) {
setup((List<Contact>) newObjs);
}
}
public void beforeInsert(SObject so) {
Contact c = (Contact) so;
if (shouldBucket(c)) {
//bucket key is first 2 of last name, Z-padded to 2 chars
string nameKey = getNameKey(c);
if (saMap.containsKey(nameKey)) {
//found key
c.AccountId = saMap.get(nameKey);
} else {
//TODO log and throw exception - setup should have made this impossible
}
}
}
public void setup(List<Contact> newContacts) {
//replace with your own method for getting the record type to use for these accounts
Id rType_systemAccount = AccountRepository.RECORD_TYPE_SYSTEM;
//update the where clause to select the user who will own the acounts
User genericApi = [SELECT Id FROM User WHERE ExternalID__c = 'XXXXAPI' LIMIT 1];
list<Account> accAdd = new List<Account>();
cacheSystemAccounts(false);
Set<string> nameKeys = new Set<string>();
boolean newSystemAccounts = false;
for (Contact c : newContacts) {
nameKeys.add(getNameKey(c));
}
for (string namekey : nameKeys) {
if (!saMap.containsKey(nameKey)) {
//we have at least one contact that needs this key.
Account a = new Account(
Name = nameKey + ' System Account Bucket',
RecordTypeId = rType_systemAccount,
SystemExternalId__c = nameKey,
Type = 'Other',
OwnerId = genericApi.Id
);
saMap.put(nameKey, a.Id);
accAdd.add(a);
newSystemAccounts = true;
}
}
if (newSystemAccounts) {
insert accAdd;
cacheSystemAccounts(newSystemAccounts);
}
}
@testVisible
private string getNameKey(Contact c) {
string nameCopy = c.LastName.replaceAll('[^\\w]', '');
return nameCopy.left(keyLength).rightPad(keyLength, 'Z').toUpperCase();
}
private void cacheSystemAccounts(boolean forceUpdate) {
if (saMap.size() > 0 && !forceUpdate)
return;
List<Account> sysAccts = [
SELECT id, SystemExternalID__c
FROM Account
WHERE RecordTypeId = :rType_systemAccount AND Type = 'Other'
];
for (Account a : sysAccts) {
saMap.put(a.SystemExternalID__c, a.id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment