function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Troy CenterTroy Center 

Can you make this code any more efficient? How?

I have these requirements. 
The BillingCode generated must be unique in the org. 
The BillingCode should whenever possible match the first three alpha letters of the Account Name, prefixed with 280. 

if Account name is A A Highlight, the Billing Code would be 280AAH, unless that was taken, 280AA? (? is single wildcard alpha char) is acceptable and if they are all taken, 280A?? would be acceptable. Of course in the end, Any available 280??? code is acceptable. 
Accept of course that there are only 17,576 available codes using this. That is acceptable too, exit and do nothing. 

AND Thanks. Think of this as a challenge. The Nested loops were flagged as potentially problematic. Is there another way to do this within these requirements? Thanks. Troy

Class and test Class below. Should work in a sandbox. You need to create the Billing_Code__c field on Account. Text, 6 characters. 
 
public with sharing class testbillingcode {
    public testbillingcode(list<Id> acctToCheck) {
        //Update the Accounts. 
        if(acctToCheck.size() > 0){
            list<Account> acctsList = [SELECT Id, Name, Billing_Code__c FROM Account WHERE Id IN :acctToCheck];
            List<Account> acctToUpdate = new List<Account>(); 
            if(acctsList.size() > 0){
                for(Account a : acctsList){
                    String strAccountName = a.Name; 
                    //Remove all Special Characters from Name String. 
                    strAccountName = strAccountName.replaceAll('(\\s+)', '');
                    strAccountName = strAccountName.replaceAll('[^a-zA-Z0-9\\s+]','');                    
                    String strAccountNameFirstCharacters = strAccountName.left(3).toUpperCase();

                    BillingCodeGenerator acctBillingCode = new BillingCodeGenerator(strAccountNameFirstCharacters);
                    String finalBillCode = acctBillingCode.getValue();
                    a.Billing_Code__c = finalBillCode;
                    a.Time_Code__c = '0'+finalBillCode+'01';
                    acctToUpdate.add(a);
                }
                update acctToUpdate;    
            }
        }            
    }

    public class BillingCodeGenerator {
        private final String value;
    
        public BillingCodeGenerator(String strAccountNameFirstCharacters) {
            this.value = this.generateValue(strAccountNameFirstCharacters);
        }
    
        public String getValue() {
            return this.value;
        }
    
        private String generateValue(String strAccountNameFirstCharacters) {
            
            Boolean FoundValidBillingCode = False; 
            String strAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

            //Select All Billing Codes from Salesforce where like 280
            List<Account> lstBillingCodeAccts = [SELECT Billing_Code__c FROM Account WHERE Billing_Code__c LIKE '280%'];
            List<String> lstBillingCodes = new List<String>();
                       

            for(Account a : lstBillingCodeAccts){
                lstBillingCodes.add(a.Billing_Code__c);
            }

            //Search for perfect match
            String strBillingCodePrefix = '280'+strAccountNameFirstCharacters;
            if(!lstBillingCodes.contains(strBillingCodePrefix)){
                //Did not find in SF. Use this Billing Code. Perfect Match found.
                FoundValidBillingCode = True;
                return strBillingCodePrefix;
            }
            if(FoundValidBillingCode == False){
               for(integer x = 0; x <= 25; x++){
                    strBillingCodePrefix = strBillingCodePrefix.left(5) +  strAlphabet.substring(x, x+1);
                    if(!lstBillingCodes.contains(strBillingCodePrefix) && !test.isRunningTest()){
                        FoundValidBillingCode = True;
                        return strBillingCodePrefix;
                    }
                }
            }
            if(FoundValidBillingCode == False){ 
                for(integer y = 0; y <= 25; y++){
                    for(integer x = 0; x <= 25; x++){
                        strBillingCodePrefix = strBillingCodePrefix.left(4) + strAlphabet.substring(x, x+1) + strAlphabet.substring(y, y+1);
                        if(!lstBillingCodes.contains(strBillingCodePrefix) && !test.isRunningTest()){
                            FoundValidBillingCode = True;
                            return strBillingCodePrefix; 
                        }
                    }
                }
            }
            if(FoundValidBillingCode == False) {
                for(integer z = 0; z <= 25; z++){
                    for(integer y = 0; y <= 25; y++){
                        for(integer x = 0; x <= 25; x++){
                            strBillingCodePrefix = '280' + strAlphabet.substring(x, x+1) + strAlphabet.substring(y, y+1) + strAlphabet.substring(z, z+1);
                            if(!lstBillingCodes.contains(strBillingCodePrefix)){
                                FoundValidBillingCode = True;
                                return strBillingCodePrefix;
                            }
                        }
                    } 
                }
            }
            return null;
        }
    }    
}


@istest
public class ContractTrigger_Tests {

    @istest
    public static void ContractTrigger_AcctBillCodeUpd_ZZZ_test() {		
        List<Id> lstAcctIds = new List<Id>(); 

        Account acctOne = new Account();
            acctOne.Name = 'Z Z-X-TestAccountAgain'; //AccountName has space in it. 
            acctOne.Type = 'Prospect';
            acctOne.RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Standard').getRecordTypeId();
        insert acctOne;
        
        
        // Account acctTest1 = [SELECT Id, Billing_Code__c, Type, Name FROM Account WHERE id = :acctOne.Id];
        System.assertEquals(null, acctOne.Billing_Code__c, 'Account Billing Code s/b null. Actual:: '+acctOne.Billing_Code__c);
    
        lstAcctIds.add(acctOne.Id);
        testbillingcode sendTest; 
        sendTest = new testbillingcode(lstAcctIds);

        Account acctResult2 = [SELECT Id,Billing_Code__c,Type FROM Account WHERE id = :acctOne.Id];
        System.assertEquals(6, acctResult2.Billing_Code__c.length(), 'Account Billing_Code__c s/b 6 characters. Actual:: '+acctResult2.Billing_Code__c.length());

        List<Account> acctResult3 = [SELECT Id,Billing_Code__c,Type FROM Account WHERE Account.Billing_Code__c=:acctResult2.Billing_Code__c];
        System.assertEquals(1, acctResult3.size(), 'Only one account should have this Billing Code. Actual:: '+acctResult3.size());
    }