• hunt dutt
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Here is my class:

public with sharing class BusinessUnitTriggerHandler 
{
    public static void checkDuplicate(List<BusinessUnits__c> units, Map<Id, BusinessUnits__c> oldMap, Boolean isInsert ) 
    {
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();

      // Get System Admin profile Id
      Id profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1].Id;
      System.debug('UAC: profileId' + profileId);

      //Get current User Profile ID
      Id userProfileId = UserInfo.getProfileId() ;
    System.debug('UAC: userProfileId' + userProfileId);

    // Iterate over all business records 
        for( BusinessUnits__c bu : units )
        {  
          // When current user Non-Admin OR these fields are updated 
          if(  profileId != userProfileId &&
            ( isInsert || ( !isInsert && ( bu.LineOfBusiness__c != oldMap.get(bu.Id).LineOfBusiness__c || bu.Contact__c != oldMap.get(bu.Id).Contact__c))) ) 
          {
            lineOfBusiness.add(bu.LineOfBusiness__c);
            contactIds.add(bu.Contact__c);
            unitsToProcess.add(bu);
            businessUnitMap.put(bu.LineOfBusiness__c+bu.Contact__c, 0);
          }
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Get existing Business records 
        for( BusinessUnits__c bu : [SELECT Id, LineOfBusiness__c, Contact__c FROM BusinessUnits__c 
                      WHERE Contact__c IN :contactIds AND LineOfBusiness__c IN :lineOfBusiness AND ID NOT IN :units ])
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          businessUnitMap.put( key, (businessUnitMap.get(key)+1) ) ;
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Iterate again over inserted/updated records 
        for( BusinessUnits__c bu : unitsToProcess )
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          // When Already exists then show error
          if( businessUnitMap.containsKey(key) && businessUnitMap.get(key) > 0 ) bu.addError('Sorry. A Business Relationship for this Business Unit already exists for this Contact.');
        }
    }

    public static void changeOwner(List<BusinessUnits__c> units )
    {
        for(BusinessUnits__c bu : units )
        {
            if( bu.Sales_Rep__c != null && bu.OwnerId != bu.Sales_Rep__c  ) bu.OwnerId = bu.Sales_Rep__c ; 
        }
    }

    public static Map<String, BusinessUnitRulesManagement__c> lobAndUserRoleToBusinessUnitCS
    {
        get
        {
            if(lobAndUserRoleToBusinessUnitCS == null )
            {
                lobAndUserRoleToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    lobAndUserRoleToBusinessUnitCS.put( cs.LineofBusiness__c + '' + cs.RoleDeveloperName__c, cs);
                }
            }
            //for(String key : lobAndUserRoleToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobAndUserRoleToBusinessUnitCS.get(key) );
            return lobAndUserRoleToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    updateContactFromCS()
    *   @Purpose:   When BusinessUnit is Updated then update SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static Boolean RUN_ONCE_UCFCS = true ; 
    public static void updateContactFromCS(List<BusinessUnits__c> units, Map<Id,BusinessUnits__c> oldMap, Boolean isInsert )
    {
        System.debug('UAC: BU updateContactFromCS START ' );
        Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
        Map<Id,Contact> existingContacts = new Map<Id,Contact>();
        Set<Id> contactIdsAddedForUpdate = new Set<Id>();
        List<Contact> contactsToUpdate = new List<Contact>();
        Set<Id> contactIds = new Set<Id>();
        Set<Id> userIds = new Set<Id>();
        Map<Id, String> userIdToUserRole = new Map<Id, String>();

        for(BusinessUnits__c bu : units)
        {
            BusinessUnits__c old =  !isInsert ? oldMap.get(bu.Id) : NULL ; 
            if( isInsert || ( !isInsert && (bu.Sales_Rep__c != old.Sales_Rep__c || bu.Escrow_Officer__c != old.Escrow_Officer__c)) ) 
            {
                if(bu.Sales_Rep__c != null ) userIds.add(bu.Sales_Rep__c);
                if(bu.Escrow_Officer__c != null && bu.Sales_Rep__c != bu.Escrow_Officer__c ) userIds.add(bu.Escrow_Officer__c);
                businessUnitToContactId.put(bu, bu.Contact__c);
                contactIds.add(bu.Contact__c);
            }
        }
        System.debug('UAC: businessUnitToContactId ' + businessUnitToContactId );

        for(User u : [SELECT Id, UserRole.DeveloperName FROM User WHERE ID IN :userIds ])
        {
            userIdToUserRole.put(u.Id, u.UserRole.DeveloperName );
        }
        System.debug('UAC: userIdToUserRole ' + userIdToUserRole );
        
        for(Contact con : Database.query( 'SELECT ' + getFields('Contact') + ' FROM Contact WHERE ID IN :contactIds ') )
        {
            existingContacts.put(con.Id, con);
        }

        for(BusinessUnits__c bu : businessUnitToContactId.keyset() )
        {
            String validUserRole = 
                //ContactTriggerHandler.currentUserRole == 'Administration' && 
                userIdToUserRole.containsKey(bu.Sales_Rep__c) ? userIdToUserRole.get(bu.Sales_Rep__c) : ContactTriggerHandler.currentUserRole ;

            // When no custom setting found for current User Role then Go Back
            if(!lobAndUserRoleToBusinessUnitCS.containsKey(bu.LineOfBusiness__c + '' + validUserRole)) continue ; 

            // Get Custom setting record
            BusinessUnitRulesManagement__c cs = lobAndUserRoleToBusinessUnitCS.get(bu.LineOfBusiness__c + '' + validUserRole);
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 
            
            // Get related Contact 
            Contact con = existingContacts.get(businessUnitToContactId.get(bu));

            // When SalesRep or EscrowOfficer changed 
            if((bu.Sales_Rep__c != con.get(cs.SalesRepFieldonContactAPIName__c) || bu.Escrow_Officer__c != con.get(cs.EscrowOfficerFieldonContactAPIName__c) ) 
                    && !contactIdsAddedForUpdate.contains(con.Id) )
            {
                contactIdsAddedForUpdate.add(con.Id);
                Contact newContact = new Contact();
                newContact.Id = con.Id;
                System.debug('UAC: bu.Sales_Rep__c ' + bu.Sales_Rep__c );
                System.debug('UAC: bu.Escrow_Officer__c ' + bu.Escrow_Officer__c );
                if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) newContact.put(cs.SalesRepFieldonContactAPIName__c, bu.Sales_Rep__c);
                if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) newContact.put(cs.EscrowOfficerFieldonContactAPIName__c, bu.Escrow_Officer__c);
                contactsToUpdate.add(newContact);
            } 
        }

        System.debug('UAC: contactsToUpdate ' + contactsToUpdate );

        // Update Contacts 
        if(contactsToUpdate.size() > 0 ) 
        {
            ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = false ;
            update contactsToUpdate ;
            ContactTriggerHandler.RUN_ONCE_UBUFCS = true ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = true ;
        }

        System.debug('UAC: BU updateContactFromCS END ' );
    
    }

    /**
    *   @Method:    getFields()
    *   @Purpose:   Use to get all fields of passing object  
    *   @Param:     String objName for which you want to get fields
    *   @Return:    Comma seprated fields
    *   @Date:      05/18/2017
    *
    *   @Updates: 
    */
    private static String getFields(String objectName)
    {
        //Broke this out of formatQuery because it could be used separately
        String fields = '';
        
        // Get All Objects List
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        
        // Get object detail which passed as argument
        SObjectType objectType = gd.get(objectName);

        // Get passed object detail
        Schema.DescribeSObjectResult r = objectType.getDescribe();

        //Get all fields for passed object 
        Map<String, Schema.SObjectField> fieldMap = r.fields.getMap();

        // Itterate over all fields and check one by one 
        for (String f: fieldMap.keySet())
        { 
            // Get current field 
            Schema.SObjectField sof = fieldMap.get(f);
            // Get current field detail
            Schema.DescribeFieldResult dfr = sof.getDescribe();

            // when current field is accessible, creatable and defaultonCreare then concatinate in field string
            if( dfr.isAccessible() )
            {
                String fname = dfr.getName(); 
                fields += fname + ', '; 
            }
        }
        
        // remove last comma
        fields = fields.substring(0, fields.length() - 2);
        return fields;
    }


    public static Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS
    {
        get
        {
            if(lobToBusinessUnitCS == null )
            {
                lobToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    if(!lobToBusinessUnitCS.containsKey(cs.LineofBusiness__c)) lobToBusinessUnitCS.put( cs.LineofBusiness__c, cs);
                }
            }
            //for(String key : lobToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobToBusinessUnitCS.get(key) );
            return lobToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    clearValueOnContact()
    *   @Purpose:   When BusinessUnit is Updated then update and clearOut SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static void clearValueOnContact(List<BusinessUnits__c> units)
    {
        System.debug('UAC: BU clearValueOnContact START ' );
     
        
     
        Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();

        // Iterate over BusinessUnit 
        for(BusinessUnits__c bu : units )
        {
            if(bu.Contact__c != null) contactIdToLOB.put(bu.Contact__c, bu.LineOfBusiness__c);
        }
        System.debug('UAC: BU contactIdToLOB ' + contactIdToLOB );
        if(contactIdToLOB.size() == 0) 
           return ; 

        // Get related Contacts 
        contacts = new Map<Id, Contact>( [SELECT Id FROM Contact WHERE ID IN :contactIdToLOB.keyset() ]);

        // Iterate over ContactIds 
        for(Id contactId : contactIdToLOB.keyset() )
        {   
            // Get Custom Setting Business Unit
            BusinessUnitRulesManagement__c cs = lobToBusinessUnitCS.get(contactIdToLOB.get(contactId));
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 

            // Get Contact 
            Contact con = contacts.get(contactId);

            // Clear Out Values on Contact 
            if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) con.put(cs.SalesRepFieldonContactAPIName__c, null);
            if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) con.put(cs.EscrowOfficerFieldonContactAPIName__c, null);
            System.debug('UAC: con ' + con );
        }

        // Update Contact
        ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;
        update contacts.values() ;
        ContactTriggerHandler.RUN_ONCE_UBUFCS = true ; 

        System.debug('UAC: BU clearValueOnContact End ' );
    }

}

Test class:

@isTest
private class BusinessUnitTriggerHandlerTest 
{
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();
      Set<Id> userIds = new Set<Id>();
      Map<Id, String> userIdToUserRole = new Map<Id, String>();
     Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
     Map<Id,Contact> existingContacts = new Map<Id,Contact>();
     Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS;
       Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();
    static testMethod void testCheckDuplicate() 
    {
         
   
        Profile profile = [Select Id from Profile where name = 'ORT Direct Sales User'];
        //UserRole ur = [Select Id from UserRole where UserRole.DeveloperName = 'Central_Direct_Agency'];

        User nonAdminUser = new User( ProfileId = profile.Id, Username = System.now().millisecond() + 'test2@test.com.dev',UserRoleId = '00E1G000000IWzyUAG',
                                    Alias = 'batman', Email='bruce.wayne@wayneenterprises.com', EmailEncodingKey='UTF-8',Firstname='Bruce',
                                    Lastname='Wayne',LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Chicago' );
        System.runAs(new User( Id = UserInfo.getUserId() ))
        {
            Database.insert(nonAdminUser);
        }

        Account acc = TestUtility.createAccount( TestUtility.default_account_rt, false );
        acc.Name = 'sfdcpoint';
        acc.Account_Status__c = 'Active';
        acc.AccountNumber = '001';
        insert acc; 
    
        System.runAs(nonAdminUser)
        {
            Contact cont = TestUtility.createContact( TestUtility.default_contact_rt , acc, false ); 
            cont.MailingStreet = 'Test Street' ;
            cont.MailingCity = 'Minneapolis';
            cont.MailingState = 'MN';
            cont.MailingPostalCode = '55347';
            cont.MailingCountry = 'United States' ; 
            insert cont;
            
            
            BusinessUnitRulesManagement__c cs = new BusinessUnitRulesManagement__c();
            cs.Name = 'AgencyManager';
            cs.EscrowOfficerFieldonContactAPIName__c = 'Text';
            cs.LineofBusiness__c = 'testlob';
            cs.RoleDeveloperName__c = 'uniquetest';
            cs.SalesRepFieldonContactAPIName__c = 'conttext';
            cs.Status__c = 'alltext';
            insert cs;
            Id userId = UserInfo.getUserId() ;
          

            BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
          
            insert bu ; 
  
            try
            {
                BusinessUnits__c bu1 = new BusinessUnits__c( Contact__c = cont.Id,LineOfBusiness__c = 'Western Title Division',Sales_Rep__c = UserId  );
                insert bu1 ;  
            }
            catch(DmlException de )
            {

            } 
  

        }
    

    }