Sunday, November 21, 2021

Parent Status Update when all child's status updated to inactive

 public static void updateAccountB2BStatus(List<Contact> lstNewContacts){

    

        map<id,Account> mapUpdateAcc = new map<id,Account>();

        set<id> accIds = new set<id>();

        for(contact con : lstNewContacts){

            if(con.AccountId != null)

                accIds.add(con.accountid); 

        }

        Id CommercialPartnerId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Commercial Partner').getRecordTypeId();

            

        Id OutletId  = [SELECT Id, SobjectType, Name, DeveloperName FROM RecordType WHERE SobjectType='Account'

                        and DeveloperName='Retail_Account' LIMIT 1].Id;

       

        for(account acc : [Select Id,B2B_Status__c,(Select id,ivybat__B2B_Portal_User_Status__c,accountid from Contacts

                                                    where (ivybat__B2B_Portal_User_Status__c ='Active' OR ivybat__B2B_Portal_User_Status__c='Pending Deactivation')) from Account 

                           where id IN: accIds and (RecordTypeID =: CommercialPartnerId OR RecordTypeID =: OutletId)]){

                               if(acc.contacts.size()>0 && acc.B2B_Status__c != 'Active'){

                                   acc.B2B_Status__c = 'Active';

                                   mapUpdateAcc.put(acc.id,acc);

                               } else if(acc.contacts.size() == 0 && (acc.B2B_Status__c == 'Active' || acc.B2B_Status__c == null)){

                                   acc.B2B_Status__c = 'Inactive';

                                   mapUpdateAcc.put(acc.id,acc);

                               }

                           }

        if(mapUpdateAcc.size()>0){

            update mapUpdateAcc.values();

        }

    }

No comments:

Post a Comment