diff --git a/force-app/main/service/HouseholdNamingService.cls b/force-app/main/service/HouseholdNamingService.cls index a225a9c4de7..08d1aa5f829 100644 --- a/force-app/main/service/HouseholdNamingService.cls +++ b/force-app/main/service/HouseholdNamingService.cls @@ -38,6 +38,7 @@ public without sharing class HouseholdNamingService { private HouseholdSettings settings = new HouseholdSettings(); + private static Boolean isNamingServiceExecuted = false; @TestVisible private ContactSelector contactSelector { @@ -419,12 +420,38 @@ public without sharing class HouseholdNamingService { } public void setCustomNamingField(List records, Map oldMap) { + if (isNamingServiceExecuted) { + return; + } + isNamingServiceExecuted = true; + for (SObject household : records) { SObject oldRecord = oldMap.get(household.Id); - setCustomNamingStringValue(household, oldRecord); + // Update only if manual changes are detected in the relevant fields + if (manualChangesDetected(household, oldRecord)) { + setCustomNamingStringValue(household, oldRecord); // Populate the custom naming field + } else { + household.put('npo02__SYSTEM_CUSTOM_NAMING__c', null); + } } } + private Boolean manualChangesDetected(SObject household, SObject oldRecord) { + // Detect changes in fields that impact the custom naming logic + return hasFieldChanged(household, oldRecord, 'npo02__Formal_Greeting__c') || + hasFieldChanged(household, oldRecord, 'npo02__Informal_Greeting__c') || + hasFieldChanged(household, oldRecord, 'Name'); + } + + private Boolean hasFieldChanged(SObject current, SObject oldRecord, String fieldApiName) { + if (oldRecord == null) { + return true; // Treat as changed if no old record exists + } + Object currentValue = current.get(fieldApiName); + Object oldValue = oldRecord.get(fieldApiName); + return currentValue != oldValue; // Compare values for change + } + public void setNameAndGreetingsToReplacementText(List records) { for (SObject household : records) { setNameAndGreetingsToReplacementText(household); @@ -534,8 +561,13 @@ public without sharing class HouseholdNamingService { private void setCustomNamingStringValue(SObject household, SObject oldRecord) { HouseholdNamingUserControlledFields userControlledNamingFields = new HouseholdNamingUserControlledFields(household, oldRecord); - household.put('npo02__SYSTEM_CUSTOM_NAMING__c', - userControlledNamingFields.asConcatenatedString()); + String concatenatedValue = userControlledNamingFields.asConcatenatedString(); + + if (!String.isBlank(concatenatedValue)) { + household.put('npo02__SYSTEM_CUSTOM_NAMING__c', concatenatedValue); // Populate field + } else { + household.put('npo02__SYSTEM_CUSTOM_NAMING__c', null); // Clear the field if no value is needed + } } private String namingOverridesFor(SObject household) {