User Story
As a Salesforce Administrator,
I want a utility that identifies and merges duplicate Account records programmatically,
So that I can ensure data cleanliness and improve system efficiency.
The utility should be implemented as an invocable method in an Apex class named AccountMergeUtility.
Duplicate accounts must be identified by matching the following fields:
- FirstName
- LastName
- PersonBirthDate
Codes
public with sharing class AccountMergeUtility {
public class request {
@InvocableVariable(required=true)
public Id recordId;
}
@InvocableMethod(label='Merge Duplicate Accounts' description='Merges duplicate Accounts based on FirstName, LastName, and BirthDate')
public static void mergeDuplicateAccounts(List<request> params) {
Id recordId = params[0].recordId;
try {
Account relatedAccount = [SELECT Id, FirstName, LastName, PersonBirthDate
FROM Account
WHERE Id = :recordId];
List<Account> duplicates = [SELECT Id, FirstName, LastName, PersonBirthDate
FROM Account
WHERE FirstName = :relatedAccount.FirstName
AND LastName = :relatedAccount.LastName
AND PersonBirthDate = :relatedAccount.PersonBirthDate
AND Id != :relatedAccount.Id];
if (duplicates.isEmpty()) {
System.debug('No duplicates found to merge for recordId: ' + recordId);
} else {
Database.MergeResult mergeResult = Database.merge(relatedAccount, duplicates, true)[0];
if (mergeResult.isSuccess()) {
System.debug('Merge successful for recordId: ' + recordId + '. Merged record IDs: ' + mergeResult.getMergedRecordIds());
} else {
for (Database.Error error : mergeResult.getErrors()) {
System.debug('Merge failed for recordId: ' + recordId + ' with error: ' + error.getMessage());
}
}
}
} catch (Exception e) {
System.debug('Error during merge operation for recordId: ' + recordId + ' - ' + e.getMessage());
}
}
}