+ Start a Discussion
Somya TiwariSomya Tiwari 

Update Branch Number on Account

I have a Scenario Where i want to update Branch Number on my Accounts. Basically it will be a tree, where Account which is the Root one will have its own Branch Code Auto Generated. While Accounts with Parent ID will have branch Code as (Parent Branch Code + Serial Number of Child).

Here is the Scenerio.
Root Node : 'Cloud Crackers' Branch Code : CC
Child Nodes of 'Cloud Crackers' as 'Somya Tiwari', and 'Harsh Panot' wherein there Branch Code is as follow:
Node: 'Somya Tiwari'  Branch Code: CC - 1
Node: 'Harsh Panot' Branch Code: CC - 2

Now if i have childs of 'Somya Tiwari' as 'A' and 'B', their Branch Code will be as follow

Node: 'A'  Branch Code: CC - 1 - 1
Node: 'B' Branch Code: CC - 1 - 1

and if 'Harsh Panot' will have child as 'C' and 'D', their branch code will be as follow:

Node: 'C'  Branch Code: CC - 2 - 1 
Node: 'D' Branch Code: CC - 2 - 2

Now whenever i change this tree i need to get all the branch codes updated. For this i have created three different classes. Currently i am learning so there is a bit of mistakes. kindly ignore those.

Here is my code, please help me with update, only that is creating issue where if i update a child which is having multiple siblings. Eg: Chidls of A as B, C, D, and E

So branch codes are as follow:
A - AA
B - AA - 1
C - AA - 2
D - AA - 3
E - AA - 4

Now if i edit D to have no parent then branch Coding must be as follow:
 
A - AA
B - AA - 1
C - AA - 2
D - DD
E - AA - 3

But Currently it is coming as follow

A - AA
B - AA - 1
C - AA - 2
D - DD
E - AA - 4

Although if i delete D then it is coming correct as follow:

A - AA
B - AA - 1
C - AA - 2
E - AA - 3

I am attaching the code. Please have a look and help me with the same.

Trigger:- Branching.apxt

trigger Branching on Account (before insert, before delete, before update, after update) 
{
    //Insert Account Logic
    if(Trigger.isInsert)
    {
        List<Account> accList = new List<Account>();
        List<Account> accListWP = new List<Account>();
        for(Account acc: Trigger.new)
        {
            if(acc.ParentId == null)
                accList.add(acc);
            else {
                accListWP.add(acc);
            }
        }
        if(acclist.size()>0)
        {
            defaultBranchCode dbc = new defaultBranchCode(acclist);
            dbc.start();
        }
        if(accListWP.size()>0)
        {
            defaultBranchCode dbc = new defaultBranchCode(accListWP, 'with parent account');
            dbc.startWP();
        }    
    }
    //Delete Account Logic
    if(Trigger.isDelete)
    {
        List<Account> accList = new List<Account>(); // List of Accounts With ParentID
        List<Account> accCheckList = new List<Account>(); //List of All Accounts which are going to be deleted
        for(Account acc: Trigger.old) //Using Trigger.old to get all the records for which the trigger is fired
        {
            if(acc.ParentID != null) // If Account have parents then add to accList 
            {
                accList.add(acc);
            }
            accCheckList.add(acc); // All accounts are added here.
        }
        if(accList.size()>0)
        {
            changeBranchCode cbc = new changeBranchCode(accList); //Refreshing the Siblings
            cbc.deleteAccount();
        }
        List<Account> unparentChild = new List<Account>();
        if(accCheckList.size()>0)
        {
            changeBranchCode cbc = new changeBranchCode(accCheckList); // Getting List of all the childs
            unparentChild.addAll(cbc.searchchilds());
        }
        if(unparentChild.size()>0) // Updating all the childs with Initiated with delete
        {
            defaultBranchCode dbc = new defaultBranchCode(unparentChild);
            dbc.startWU();
            List<Account> upd = new List<Account>();
            for(Account a: unparentChild)
            {
                a.ByDelete__c = true;
                upd.add(a);
            }
            update upd;
            /*UpdateQueue uq = new UpdateQueue(unparentchild);
            System.enqueueJob(uq);*/
            UpdateMethods um = new UpdateMethods(unparentchild);
            um.UpdateChilds(unparentchild);
        }
    }

    if(Trigger.isUpdate)
    {
        if(Trigger.isAfter)
        {
            List<Account> acc = [SELECT ID, ParentID, branchcode__c, pbc__c FROM ACCOUNT];
            List<Account> child = new List<Account>();
            List<Account> temp = new List<account>();
            List<Account> FA = new List<Account>();
            for(Account a: Trigger.new)
            {
                temp.add(a);
            }
            child.addAll(changeBranchCode.searchchilds2(temp));
            if(child.size() >0)
            {
                List<Account> ab = new List<Account>();
                for(Account a: child)
                {
                    List<String> split = a.branchcode__c.split(' - ');
                    integer i = 0;
                    if(a.branchcode__c.length()>4)
                        i = Integer.valueOf(split[split.size()-1]);
                    if(i>0)
                        a.branchcode__c = a.pbc__c +' - '+ i;
                    else
                        a.branchcode__c = a.pbc__c;
                    ab.add(a);
                }
                fa.addAll(ab);
                //update ab;
            }
            List<Account> fud = new List<Account>();
            for(Account a: Trigger.old)
            {
                if(a.parentID != null)
                    fud.add(a);
            }
            if(fud.size()>0)
            {
                changeBranchCode cbc = new changeBranchCode(fud);
                cbc.deleteAccount();
            }
            update fa;
        }
        if(Trigger.isBefore)
        {
            List<Account> accListWP = new List<Account>();
            Map<ID, Account> oldmap = Trigger.oldmap;
            for(Account a: Trigger.new)
            {
                if(a.ByDelete__c == false)
                {
                    Account old = oldmap.get(a.Id);
                    if(a.pbc__c != old.pbc__c)
                    {
                        accListWP.add(a);
                    }
                    else
                    {
                        List<String> split = a.branchcode__c.split(' - ');
                        integer i = 0;
                        
                        if(a.branchcode__c.length()>4)
                            i = Integer.valueOf(split[split.size()-1]);
                        if(i>0)
                            a.branchcode__c = a.pbc__c +' - '+ i;
                        else
                            a.branchcode__c = a.pbc__c;
                    }
                    
                    System.debug(a.branchcode__c);
                }
                else
                {
                    a.ByDelete__c = false;
                }
            }
            if(accListWP.size()>0)
            {
                defaultBranchCode dbc = new defaultBranchCode(accListWP, 'with parent account');
                dbc.startWP();
            }
        }
        
    }
}
DefaultBranchCode.apxc
public class defaultBranchCode 
{
    List<Account> acc_list;
    List<Account> accList = [SELECT branchcode__c, parentID FROM Account];
    List<String> temp = new List<String>();
    // For Base Account
    public defaultBranchCode(List<Account> acc_list) 
    {
        this.acc_list = acc_list;
    }

    String createBranchCode(Account a)
    {
        List<String> split = a.Name.split(' ');
        String ret = '';
        for(integer i = 0; i<split.size(); i++)
        {
            ret+=split[i].substring(0, 1);
        }
        if(ret.length()>2)
        {
            ret = ret.substring(0,2);
        }
        else if(ret.length()<2)
        {
            ret = ret+ret;
        }
        return ret.toUpperCase();
    }

    String verifiedBranchCode(String branchCode)
    {
        Integer size = accList.size();
        for(integer i = 0; i<size; i++)
        {
            if(accList[i].branchcode__c == branchCode)
            {
                if(branchCode.length()>2)
                {
                    String val = branchCode.substring(2, branchCode.length());
                    Integer k = Integer.valueOf(val);
                    k = k+1;
                    branchCode = branchCode.substring(0, 2) + k;
                }
                else 
                {
                    branchCode = branchCode+1;    
                }
                i = 0;
            }
        }
        return branchCode;
    }

    public void start()
    {
        for(Account acc : acc_list)
        {
            String branchCode = createBranchCode(acc);
            branchCode = verifiedBranchCode(branchCode);
            acc.BranchCode__C = branchCode;
            temp.add(branchCode);
        }
    }

    //For Accounts w/ parents
    Map<Id, integer> currentvalue = new Map<Id, integer>(); 
    public defaultBranchCode(List<Account> acc_list, String temp) 
    {
        this.acc_list = acc_list;
    }

    Integer counter(String pid)
    {
        integer count = 0;
        for(Account acc : accList)
        {
            System.debug(acc.ParentId);
            if(acc.ParentID == pid)
                count++;
            System.debug(count);
        }
        return count;
    }

    public void startWP()
    {
        for(Account acc : acc_list)
        {
            String pid = acc.ParentID;
            if(!currentvalue.containsKey(pid))
                currentvalue.put(pid, counter(pid));
            integer current = currentvalue.get(pid);
            current = current+1;
            currentvalue.put(pid, current);
            acc.BranchCode__C = acc.pbc__C + ' - ' + current;
        }
    }

//For Delete function
    public void startWU()
    {
        List<Account> ltoupdate = new List<Account>();
        for(Account acc : acc_list)
        {
            String branchCode = createBranchCode(acc);
            branchCode = verifiedBranchCode(branchCode);
            acc.BranchCode__C = branchCode;
            ltoupdate.add(acc);
        }
        update ltoupdate;
    }

}



ChangeBranchCode.apxc
public class changeBranchCode {
    List<Account> listacc = new List<Account>();
    List<Account> allaccount = [SELECT branchcode__c, parentID,pbc__C, Id FROM Account];
    public changeBranchCode(List<Account> listacc) 
    {
        this.listacc = listacc;
    }
    Map<Account, List<Account>> map_PC = new Map<Account, List<Account>>();
    void createMap()
    {
        for(Account acc: allaccount)
        {
            Account parentaccount = findparent(acc.parentID);
            if(map_PC.containsKey(parentaccount)){
                List<Account> temp = map_PC.get(parentaccount);
                temp.add(acc);
                map_PC.put(parentaccount, temp);
            }
            else {
                List<Account> temp = new List<Account>();
                temp.add(acc);
                map_PC.put(parentaccount, temp);
            }
        }
    }
    Account findparent(ID pid)
    {
        Account acc;
        for(Account t : allaccount)
            if(t.Id == pid)
                acc = t;
        return acc;
    }
    
    static Map<Account, List<Account>> map_PC1 = new Map<Account, List<Account>>();
    static List<Account> allaccount1 = [SELECT branchcode__c, parentID,pbc__C, Id FROM Account];
    static void createMap1()
    {
        for(Account acc: allaccount1)
        {
            Account parentaccount = findparent2(acc.parentID);
            if(map_PC1.containsKey(parentaccount)){
                List<Account> temp = map_PC1.get(parentaccount);
                temp.add(acc);
                map_PC1.put(parentaccount, temp);
            }
            else {
                List<Account> temp = new List<Account>();
                temp.add(acc);
                map_PC1.put(parentaccount, temp);
            }
        }
    }
    static Account findparent2(ID pid)
    {
        Account acc;
        for(Account t : allaccount1)
            if(t.Id == pid)
                acc = t;
        return acc;
    }
    
    
    /*static Account findparent1(ID pid, List<Account> allaccount)
    {
        Account acc;
        for(Account t : allaccount)
            if(t.Id == pid)
                acc = t;
        return acc;
    }*/

    void rebase(Account acc, Account notinclude, integer f)
    {
        List<Account> child = map_PC.get(acc);
        List<Account> ListToupdate = new List<Account>();
        try {
            for(Account a : child)
            {
                if(a != notinclude)
                {
                    List<String> split = a.branchcode__c.split(' - ');
                    Integer i = 0;
                    if(a.branchcode__c.length()>4)
                        i = Integer.valueOf(split[split.size()-1]);
                    if(i>f)
                        i--;
                    Account up = new Account(ID = a.Id);
                    if(i>0)
                        up.branchcode__c = a.pbc__c +' - '+ i;
                    else
                        up.branchcode__c = a.pbc__c;
                    ListToupdate.add(up);
                }
            }
        } catch (NullPointerException e) {
            System.debug(e.getStackTraceString());
        }
        update ListToupdate;
    }

    public void deleteAccount()
    {
        createMap();
        for(Account acc : listacc)
        {
            Account parent = findparent(acc.parentID);
            List<String> split = acc.branchcode__c.split(' - ');
            Integer i = 0;
            if(acc.branchcode__c.length()>4)
                i = Integer.valueOf(split[split.size()-1]);
            //rebase(parent, acc, i);
            if(Trigger.isDelete)
                rebase(parent, acc, i);
            else {
                ID ta = parent.Id;
                ID ta2 = acc.Id;
				if(!System.isFuture())
                	rebase_2(ta, ta2, i);
                else
                    rebase(parent, acc, i);
            }
        }
    }

    @future static void rebase_2(ID ta, ID ta2, integer f)
    {
        //Account acc = [SELECT ID, Name, branchcode__c, parentID,pbc__C FROM ACCOUNT where ID=:ta];
        Account notinclude = [SELECT  ID, Name, branchcode__c, parentID,pbc__C FROM ACCOUNT where ID=:ta2];
        //List<Account> child = map_PC1.get(acc);
        List<Account> child = [SELECT  ID, Name, branchcode__c, parentID,pbc__C FROM ACCOUNT where ParentID = :ta];
        System.debug(child);
        List<Account> ListToupdate = new List<Account>();
        try{
            for(Account a : child)
            {
                if(a != notinclude)
                {
                    List<String> split = a.branchcode__c.split(' - ');
                    Integer i = 0;
                    if(a.branchcode__c.length()>4)
                        i = Integer.valueOf(split[split.size()-1]);
                    if(i>f)
                        i--;
                    Account up = new Account(ID = a.Id);
                    if(i>0)
                        up.branchcode__c = a.pbc__c +' - '+ i;
                    else
                        up.branchcode__c = a.pbc__c;
                   ListToupdate.add(up);
                }
            }
        } catch (NullPointerException e) {
            System.debug(e.getStackTraceString());
        }
        update ListToupdate;
    }

    public List<Account> searchchilds()
    {
        List<ID> lid = new List<ID>();
        for(Account a : listacc)
        {
            lid.add(a.id);
        }
        List<Account> childs = [SELECT Id, branchcode__c, Name, ParentID, pbc__c FROM Account WHERE ParentID = :lid];
        return childs;
    }
    
    public static List<Account> searchchilds2(List<Account> listac)
    {
        List<ID> lid = new List<ID>();
        for(Account a : listac)
        {
            lid.add(a.id);
        }
        List<Account> childs = [SELECT Id, branchcode__c, Name, ParentID, pbc__c FROM Account WHERE ParentID = :lid];
        return childs;
    }
    
}

UpdateMethods.apxc
public class UpdateMethods 
{
    List<Account> listacc = new List<Account>();
    List<Account> allaccount = [SELECT Name, branchcode__c, parentID,pbc__C, Id FROM Account];
    public UpdateMethods(List<Account> listacc) 
    {
        this.listacc = listacc;
    }
    public UpdateMethods()
    {

    }
    Map<Account, List<Account>> map_PC = new Map<Account, List<Account>>();
    void createMap()
    {
        for(Account acc: allaccount)
        {
            Account parentaccount = findparent(acc.parentID);
            if(map_PC.containsKey(parentaccount)){
                List<Account> temp = map_PC.get(parentaccount);
                temp.add(acc);
                System.debug(temp);
                map_PC.put(parentaccount, temp);
            }
            else {
                List<Account> temp = new List<Account>();
                temp.add(acc);
                map_PC.put(parentaccount, temp);
            }
        }
    }
    Account findparent(ID pid)
    {
        Account acc;
        for(Account t : allaccount)
            if(t.Id == pid)
                acc = t;
        return acc;
    }
    public void UpdateChilds(List<Account> fchilds)
    {
        createMap();
        List<Account> childs = findchilds(fchilds);
        List<Account> ListToupdate = new List<Account>();
        for(Account a: childs)
        {
            List<String> split = a.branchcode__c.split(' - ');
            integer i = 0;
            if(a.branchcode__c.length()>4)
                i = Integer.valueOf(split[split.size()-1]);
            Account up = new Account(ID = a.Id);
            if(i>0)
                up.branchcode__c = a.pbc__c +' - '+ i;
            else
                up.branchcode__c = a.pbc__c;
            System.debug(split);
            ListToupdate.add(up);
        }
        update ListToupdate;
    }
    
    List<Account> searchchilds(List<Account> fchilds)
    {
        List<Account> childs = new List<Account>();
        for(Account a : fchilds)
        {
            if (map_PC.get(a) != null)
                childs.addAll(map_PC.get(a));
        }
        return childs;
    }

    List<Account> findchilds(List<Account> fchilds)
    {
        List<Account> childs = new List<Account>();
        integer prev, current;
        for(integer i = 0 ; i<1; )
        {
            prev = childs.size();
            childs.addAll(searchchilds(fchilds));
            fchilds = childs;
            current = childs.size();
            if(prev == current)
                i = 1;
        }
        return childs;
    }
}