Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
22 kB
3
Indexable
/** * * * * * * * * * * * *
* 
*  Class Name          : AccountTriggerHandler
*  Purpose             : Handler for AccountTrigger
*  Author              : Dhana Prasad
*  Created Date        : 31-Mar-2020
*  Modified By and Date :   
* 
** * * * * * * * * * * * */
public with sharing class AccountTriggerHandler {
    /*
* Method Name : afterUpdate
* Description : works on trigger after update
* Created on and by : 31 -03-2020 Dhana Prasad
* Modified on and by :
*/
    public static void afterUpdate(List<Account> newList, Map<Id,Account> oldMap){
        checkIsPartnerChanged(newList, oldMap);
        //checkOrgSidsChanged(newList, oldMap); //Added by Phani Meda
        AccountTriggerHandler.updateAccountGapRecords(newList, oldMap); // added for SE Amount Update
    }
    /*
* Method Name : checkIsPartnerChanged
* Description : checks if partner is changed nad retrives the latest adventure of account which has same partner type
* Created on and by : 31 -03-2020 Dhana Prasad
* Modified on and by :
*/
    public static void checkIsPartnerChanged(List<Account> newList, Map<Id,Account> oldMap){
        Set<Id> accIdSet = new Set<Id>();
        Map<Id,Id> mapOfAccountIdAndAdventureId = new Map<Id,Id>();
        Map<String,Id> mapOfIdAndPartnerType = new Map<String,Id>();
        for(Account acc: newList){
            if(acc.IsPartner == true && oldMap.get(acc.Id).IsPartner == false && acc.Partner_Type__c != null){
                mapOfIdAndPartnerType.put(acc.Partner_Type__c,acc.Id);
            }
        }
        List<Adventure__c> recentAdventure = null;
        if(mapOfIdAndPartnerType.isEmpty()) return; 
        else{
            recentAdventure =  [SELECT Id, Account__c,Partner_Type__c, CreatedDate  FROM Adventure__c 
                                WHERE Partner_Type__c IN: mapOfIdAndPartnerType.keySet() 
                                AND Template__c =true
                                ORDER BY CreatedDate DESC
                                LIMIT 1]; 
        }
        
        if(recentAdventure !=null){
            for(Adventure__c adventure : recentAdventure){
                mapOfAccountIdAndAdventureId.put(adventure.Id,mapOfIdAndPartnerType.get(adventure.Partner_Type__c));
            }
        }
        system.debug('mapOfAccountIdAndAdventureId'+mapOfAccountIdAndAdventureId);
        if(mapOfAccountIdAndAdventureId.size()>0){
            for(Id advId : mapOfAccountIdAndAdventureId.keySet())
            {
                Id  test =  x7s_Adventure_CloneProjectAssignment.cloneAdventureWithAccount(advId,mapOfAccountIdAndAdventureId.get(advId));
            }
        }
        
    }
    
    /*
    * Method Name : updateConsumerOnAccountMerge
    * Description : This method will delete the Consumer Trust records having lesser priority after Account merging is performed
    * @params : masterAccountIds - This list will have the Master Account ids post account merging
    * Created on and by : 17-02-2021 Devam Gupta
    * Modified on and by :
    */
    public static void updateConsumerOnAccountMerge(List<Id> masterAccountIds){
        
        List<Consumer_Trust__c> consumerRecordsDeleted = new List<Consumer_Trust__c>();
        List<Consumer_Trust__c> consumerRecordsUpdated = new List<Consumer_Trust__c>();
        
        for(Account accountRec : [select id,(Select id,Consumer_trust_category__c,Account__c,Account__r.Name from Consumer_Trust__r)
                                            from Account where id in : masterAccountIds]){
            if(accountRec.Consumer_Trust__r.size() > 1){
                List<ConsumerTrustPriorityWrapper> consTrustWrapperList = new List<ConsumerTrustPriorityWrapper>();
                for(Consumer_Trust__c consumerRec : accountRec.Consumer_Trust__r){
                    consTrustWrapperList.add(new ConsumerTrustPriorityWrapper(consumerRec,
                                                                              ConsumerTrustConstants.CONSUMER_TRUST_PRIORITY_MAP.get(consumerRec.Consumer_Trust_Category__c)));
                }
                consTrustWrapperList.sort();
                //Updating Name,Account_ID__c on the single CT record to reflect the Master Account details
                consTrustWrapperList[0].consumerTrust.Name = 'CT' + ' - ' + consTrustWrapperList[0].consumerTrust.Account__r.Name.left(75);
                consTrustWrapperList[0].consumerTrust.Account_ID__c = consTrustWrapperList[0].consumerTrust.Account__c;
                consumerRecordsUpdated.add(consTrustWrapperList[0].consumerTrust);
                //Removing the highest priority Consumer trust record from the List and others will be deleted 
                consTrustWrapperList.remove(0);
                for(ConsumerTrustPriorityWrapper eachWrapRec : consTrustWrapperList){
                    consumerRecordsDeleted.add(eachWrapRec.consumerTrust);
                }
            }
        }
        if(!consumerRecordsDeleted.isEmpty()){
            try{
                delete consumerRecordsDeleted;
            }catch (DmlException e) {
                System.debug('The following exception has occurred when deleting consumer trust records from AccountTriggerHandler' + e.getMessage());
                ApexHandlerException.LogDMLException(e);
            }
        }
        //For updating Name & Account_ID__c Field on CT records as the Workflow on CT object will not get fired post Account Merge
        if(!consumerRecordsUpdated.isEmpty()){
            try{
                update consumerRecordsUpdated;
            }catch (DmlException e) {
                System.debug('The following exception has occurred when updating consumer trust records from AccountTriggerHandler' + e.getMessage());
                ApexHandlerException.LogDMLException(e);
            }
        }
    }
    
    /***************************************************
    Added by Sai Kalikota
    Description: This method updates the CSM field on Account to match CSM portfolio's
                 CSM & also updates Date Assigned to CSM to Today's date
                 if there is a change of CSM Portfolio on Account
    Date: June 4, 2021
    Test Class: TerritoryTriggerHandlerTest
    DoveTail URL: https://twlo.lightning.force.com/lightning/r/Workstream__c/a181W0000041RnAQAU/view
    ****************************************************/
    public static void updateAccountCSMonTerritoryChange(List<Account> newAccounts,Map<Id,Account> oldAccountMap){
        List<Account> accountsToUpdate=new List<Account>();
        Set<Id> territoryIds=new Set<Id>();
        for(Account acc:newAccounts){
            if(acc.CSM_Portfolio__c!=null){
                if(oldAccountMap!=null && acc.CSM_Portfolio__c!=oldAccountMap.get(acc.Id).CSM_Portfolio__c){
                    accountsToUpdate.add(acc);
                    territoryIds.add(acc.CSM_Portfolio__c);
                }
            }else{
                if(oldAccountMap!=null && acc.CSM_Portfolio__c!=oldAccountMap.get(acc.Id).CSM_Portfolio__c){
                    acc.FY_17_CSM__c=null;
                    acc.Date_Assigned_to_CSM__c=null;
                }
            }
        }
        if(!territoryIds.isEmpty()){
            Map<Id,Territory__c> territoryMap=new Map<Id,Territory__c>([Select Id,CSM__c from Territory__c where Id in:territoryIds]);
            for(Account acc:accountsToUpdate){
                if(territoryMap.containsKey(acc.CSM_Portfolio__c)){
                    acc.FY_17_CSM__c=territoryMap.get(acc.CSM_Portfolio__c).CSM__c; 
                    acc.Date_Assigned_to_CSM__c=System.today(); 
                }
            }
        }
    }
   /*****************************************************
    * Added by Abhishek Swain for  Clean account 
      Dovetail : https://twlo.lightning.force.com/lightning/r/Workstream__c/a181W000004d2wAQAQ/view
      Test Class : TerritoryTriggerHandlerTest
    *******************************************************/
    public static void updateCleanAccountfield(List<Account> newAccounts,Map<Id,Account> oldAccountMap)
        
    {
        String acCleanName ;
        String acName;
        List<Remove_endings__c> endlist = Remove_endings__c.getall().values();
        for (Account accnt:newAccounts){
            acName = accnt.name;
            if(acName.endsWithIgnoreCase(' **partner main**')){
                accnt.clean_account_name__c = acName.removeEndIgnoreCase(' **partner main**');
            }
            else if (acName.endsWithIgnoreCase(' *partner main*')){
                accnt.clean_account_name__c = acName.removeEndIgnoreCase(' *partner main*');
            } 
            for (Remove_endings__c re : endlist)
            {
                acCleanName = accnt.clean_account_name__c;
                
                if (acCleanName != NULL && acCleanName.endswithIgnorecase(re.Removal_Extensions__c))
                {
                    accnt.clean_account_name__c = acCleanName.removeEndIgnoreCase(re.Removal_Extensions__c);
                    break;
                }
                
            }
        }
    }
    
    public static void updateSubRegionOnInsert(List<Account> newAccounts)
    {
        List<Country_to_Sub_region_mapping__mdt> lstCountryToRegion = Country_to_Sub_region_mapping__mdt.getAll().values();
        Map<string,string> countryPicklistValue = new Map<string, string>();

        // start commented for testing  manjunath 01-10-2021
        Map<String,string> regionCountry = new Map<string ,String>();
        for(Country_to_Sub_region_mapping__mdt regionToCountry: lstCountryToRegion){
            for(String country: regionToCountry.GTM_Country__c.split(':')){
                regionCountry.put(country.toLowerCase(),regionToCountry.Sub_Region__c);
            }
        }
        for(Account objAcnt: newAccounts){
            objAcnt.Sub_Region__c='Unknown';
            if(objAcnt.GTM_Country__c!=null && objAcnt.GTM_Country__c.containsignorecase('Unknown')){
                objAcnt.Sub_Region__c='Unknown';
                objAcnt.Territory_Planning_Region_Segment__c=null;
                break;
            }
            else if(objAcnt.BillingCountryCode!=null && objAcnt.BillingCountryCode.containsignorecase('Unknown')){
                objAcnt.Sub_Region__c='Unknown';
                objAcnt.Territory_Planning_Region_Segment__c=null;
                break;
            }
            system.debug('objAcnt.GTM_Country__c ::: '+objAcnt.GTM_Country__c);
            system.debug('objAcnt.BillingCountryCode ::: '+objAcnt.BillingCountryCode);
            if(objAcnt.GTM_Country__c!=null || objAcnt.BillingCountryCode!=null){
                countryPicklistValue = getCountryPicklistCodeValue();
                String actcountry = objAcnt.GTM_Country__c==null ? countryPicklistValue.get(objAcnt.BillingCountryCode) : objAcnt.GTM_Country__c;
                if(actcountry!=null && regionCountry.containsKey(actcountry.toLowerCase())){
                    objAcnt.Sub_Region__c=regionCountry.get(actcountry.toLowerCase());
                }
            }
            if((objAcnt.BillingState!=null && objAcnt.BillingState.equalsignorecase('Puerto rico')) && objAcnt.GTM_Country__c!=null && objAcnt.GTM_Country__c.equalsignorecase('United States')){
                objAcnt.Sub_Region__c='LATAM_ROL';
            }
        }
    }
    
    public static void updateSubRegion(List<Account> newAccounts, Map<id,Account> oldacc)
    {        
        Map<Account,String> updateAccounts = new Map<Account,String>();
        Map<string,string> countryPicklistValue = new Map<string, string>();
        for(Account acc: newAccounts){
            if(acc.BillingCountryCode!=oldacc.get(acc.id).BillingCountryCode || acc.GTM_Country_Override__c!=oldacc.get(acc.id).GTM_Country_Override__c ||
              acc.BillingCountry!=oldacc.get(acc.id).BillingCountry || acc.BillingState!=oldacc.get(acc.id).BillingState ||
              acc.BillingStateCode!=oldacc.get(acc.id).BillingStateCode){
                acc.Sub_Region__c='Unknown';
                  if(acc.GTM_Country_Override__c!=null){
                      updateAccounts.put(acc,acc.GTM_Country_Override__c);
                  }else if(acc.BillingCountryCode!=null){
                      countryPicklistValue = getCountryPicklistCodeValue(); 
                      updateAccounts.put(acc,countryPicklistValue.get(acc.BillingCountryCode));
                  }if((acc.BillingState!=null && acc.BillingState.equalsignorecase('Puerto rico')) && updateAccounts.get(acc)!=null && updateAccounts.get(acc).equalsignorecase('United States')){
                      acc.Sub_Region__c='LATAM_ROL';
                  }
            }
        }
        if(updateAccounts!=null && updateAccounts.size()>0){
            
            List<Country_to_Sub_region_mapping__mdt> lstCountryToRegion = Country_to_Sub_region_mapping__mdt.getAll().values();
            // start commented for testing  manjunath 01-10-2021
            Map<String,string> regionCountry = new Map<string ,String>();
            for(Country_to_Sub_region_mapping__mdt regionToCountry: lstCountryToRegion){
                for(String country: regionToCountry.GTM_Country__c.split(':')){
                    regionCountry.put(country.toLowerCase(),regionToCountry.Sub_Region__c);
                }
            }
            for(Account objAcnt: updateAccounts.keyset()){
                if(updateAccounts.get(objAcnt)!=null && updateAccounts.get(objAcnt).containsignorecase('Unknown')){
                    objAcnt.Sub_Region__c='Unknown';
                    objAcnt.Territory_Planning_Region_Segment__c=null;
                    break;
                }
                
                if(updateAccounts.get(objAcnt)!=null && regionCountry.containsKey(updateAccounts.get(objAcnt).toLowerCase())){
                    objAcnt.Sub_Region__c=regionCountry.get(updateAccounts.get(objAcnt).toLowerCase());
                }
                if((objAcnt.BillingState!=null && objAcnt.BillingState.equalsignorecase('Puerto rico')) && updateAccounts.get(objAcnt)!=null && updateAccounts.get(objAcnt).equalsignorecase('United States')){
                    objAcnt.Sub_Region__c='LATAM_ROL';
                }
                
            }
        }
    }
    
    public static Map<string,string> getCountryPicklistCodeValue(){
        Map<string,string> countryPicklistValue = new Map<string, string>();
        Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry f : ple){
            countryPicklistValue.put(f.getValue(),f.getLabel());
        }
        return countryPicklistValue;
    }
    
    /*****************************************************
    * Added by Mia Cui for org Account on 10/12/21
    * Description : enrich Account's org eligibility fields based on Legal_Entity_Type__c value, refe
    				referencing IAP_Custom_Setting__c 
      Dovetail : https://twlo.lightning.force.com/lightning/r/Workstream__c/a181W000004d2wAQAQ/view
      Test Class : 
    *******************************************************/
     public static void enrichAccountOrgData(List<Account> accountList) {
        List<IAP_Custom_Setting__c> IAPlst = IAP_Custom_Setting__c.getAll().values();
        if(IAPlst == NULL || IAPlst.size() == 0) return;
        for(Account acc: accountList) {
            if(acc.Legal_Entity_Type__c != NULL) {
                for(IAP_Custom_Setting__c IAP: IAPlst) {
                    if(IAP.Object__c == 'Account' && IAP.Legal_entity_type__c == acc.Legal_entity_type__c) {
                        acc.put(IAP.Field_API_Name__c, IAP.value__c);
                    }
                }
            }
        }
        //update accountList;
    }
    
    public static void enrichAccountOrgData(List<Account> accountList, Map<Id,Account>oldMap) {
        List<Account> filterRec = new List<Account>();
        for(Account acc: accountList) {
            Account oldAcc = oldMap.get(acc.id);
            if (oldMap.get(acc.id) != null && acc.Legal_Entity_Type__c != oldAcc.Legal_Entity_Type__c) {
                filterRec.add(acc);
            }
        }
        if(filterRec.size() > 0){enrichAccountOrgData(filterRec);}
    }
    
    /**
    * ──────────────────────────────────────────────────────────────────────────────────────────────────
    * @author			Manjunath C S     <msarashetti@twilio.com>
    * @description		This is used to update all the Account Gap Records when account Current_ARR_Based_on_Last_6_Months__c get changeds
    * @return        	void
    * @params        	Accountlist and oldmap
    * @createdDate   	01-March-2022
    * ──────────────────────────────────────────────────────────────────────────────────────────────────
    **/
    public static void updateAccountGapRecords (List<Account> accountList, Map<Id,Account>oldMap){
        List<Account> filterRec = new List<Account>();
        Map<id,Account > mapAcc= new Map<id,Account>();
        for(Account acc: accountList) {
            Account oldAcc = oldMap.get(acc.id);
            if (oldMap.get(acc.id) != null && acc.Current_ARR_Based_on_Last_6_Months__c != oldAcc.Current_ARR_Based_on_Last_6_Months__c) {
                mapAcc.put(acc.id,acc);
            }
        }
        List<SE_Account_Gap__c> accGapRecords= new List<SE_Account_Gap__c>();
        List<SE_Account_Gap__c> updateSERecords= new List<SE_Account_Gap__c>();
        if(mapAcc.size()>0){
            accGapRecords= [Select id,Solution_Gap_Account_Amount__c,Account__c from SE_Account_Gap__c where Account__c in:mapAcc.keyset() ];
            for(SE_Account_Gap__c seAccountGapRec: accGapRecords){
                if(mapAcc.containskey(seAccountGapRec.Account__c) && seAccountGapRec.Solution_Gap_Account_Amount__c!=mapAcc.get(seAccountGapRec.Account__c).Current_ARR_Based_on_Last_6_Months__c ){
                    seAccountGapRec.Solution_Gap_Account_Amount__c = mapAcc.get(seAccountGapRec.Account__c).Current_ARR_Based_on_Last_6_Months__c;
                    updateSERecords.add(seAccountGapRec);
                }
            }
            if(updateSERecords!=null && updateSERecords.size()>0){
                update updateSERecords;
            }
        }
    }
    
    /*
    *********************************************************
    @Method Name    : checkOrgSidsChanged
    @author         : Phani Meda
    @description    : method is used to send an HIPAA event to Monkey on Org SID change on BAA Signed Accounts
    @param          : old and new values of acc sid details
    @return         : void (null)
    ********************************************************
    */
    /*
    public static void checkOrgSidsChanged(List<Account> newList, Map<Id,Account> oldMap)
    {
        List<HIPAA_Event__e> hipaaEvents = new List<HIPAA_Event__e >();
        for(Account acc: newList)
        {
            if(String.isNotBlank(acc.Org_SIDs__c) && (acc.Org_SIDs__c!=oldMap.get(acc.Id).Org_SIDs__c))
            {
                if(acc.Org_SIDs__c.contains(';'))
                {
                    for(String str:acc.Org_SIDs__c.split(';'))
                    {
                        hipaaEvents.add(new HIPAA_Event__e(Org_Sid__c=str, Event_Type__c='BAA_SIGNED'));
                    }
                }
                else
                {
                    hipaaEvents.add(new HIPAA_Event__e(Org_Sid__c=acc.Org_SIDs__c, Event_Type__c='BAA_SIGNED'));
                }
            }
        }
        
        if(!hipaaEvents.isEmpty())
        {
            List<Database.SaveResult> results = EventBus.publish(hipaaEvents);
        }
    }*/
    
    /**
    * ──────────────────────────────────────────────────────────────────────────────────────────────────
    * @author			Mia Cui     <ncui@twilio.com>
    * @description		This is used to formart SE Notes and stamp history notes
    * @return        	void
    * @params        	Accountlist and oldmap
    * @createdDate   	26-April-2023
    * ──────────────────────────────────────────────────────────────────────────────────────────────────
    **/
    public static void updateSEnotesFields(List<Account> accNewlist, Map<id,Account> accOldMap){
        for (Account accNewRec: accNewlist) {
            Account accOldRec = accOldMap.get(accNewRec.id);
            if (accOldRec.SE_Notes__c != accNewRec.SE_Notes__c ) {
                AccountTriggerHandler.updateSEnotesFields(accOldRec,accNewRec);
            }
        }
    }
    public static void updateSEnotesFields(Account accOldRec, Account accNewRec){
        if(String.isBlank(accNewRec.SE_Notes__c )){
          accNewRec.SE_Notes__c  = accOldRec.SE_Notes__c ;
        }
        else{
          accNewRec.SE_Notes__c  = OpportunityTriggerHelperTF.getFieldValueToUpdate(accOldRec.SE_Notes__c ,accNewRec.SE_Notes__c );
          accNewRec.SE_Notes_Histroy__c  = OpportunityTriggerHelperTF.getHistoryFieldValue(accOldRec.SE_Notes__c , accNewRec.SE_Notes_Histroy__c);
        }
  }
}