Retrieve Top Level RoleIds, Role Names And Below RoleIds,Role Names in Salesforce


Below code is to fetch Top Level RoleIds, Role Names And Below RoleIds,Role Names based on given user. To achieve the requirement, a batchable and a iterable have been written.

here is the code for batchable class. Through this code, IC_UserRole_Hierarchy__c object record gets inserted. This object has various fields like Role Above Current User Role,Role Below Current User Role,Role Ids Above Role,Role Ids Below Role,Current User Role,Current User Role Id. When batch runs and current user value is passed then it will insert the IC_UserRole_Hierarchy__c  record having all the information about above and below roles of a user.


public class InvestCloudRoleHierarchyBatchable implements Database.Batchable<User>, Database.Stateful { //Implementation Batchable.Start method //Method to get the Set of Users of specified Roles public String userId {get; set;} public InvestCloudRoleHierarchyBatchable (String userId){ this.userId = userId; } public InvestCloudRoleHierarchyBatchable (){ } public Iterable<User> start(Database.BatchableContext BC){ System.debug(Logginglevel.INFO, 'Inside Start Method'); try { List<String> excludeIds = null; for(IC_Role_Hierarchy_Constants__mdt icRHConst : [SELECT value__c, label FROM                 IC_Role_Hierarchy_Constants__mdt WHERE Label = :ConstantUtils.EXCLUDED_ROLE_IDS ]){ if (String.IsNotBlank(icRHConst.value__c )) excludeIds = icRHConst.value__c.split(','); } List<User> userSet; if (String.IsNotBlank(userId)){ userSet = [SELECT Id,FirstName,LastName,CRD__c,Person_Party_ID__c,UserRoleId                             FROM User where isactive = true and UserRoleId != Null and                             id = :userId ]; //0051400000CCdeo //00530000004pAmU } else { userSet = [SELECT Id,FirstName,LastName,CRD__c,Person_Party_ID__c,                             UserRoleId FROM User where isactive = true and UserRoleId != Null                             AND UserRoleId NOT IN :excludeIds ]; } return userSet; } catch (Exception e) { System.debug(Logginglevel.ERROR, 'Error in InvestCloudRoleHierarchyBatchable.start() ---> ' +e); } return null; } // Implementation Batchable.execute method // Method used to create an instance of Iterable class and for bulk Database insert operation. public void execute(Database.BatchableContext BC, List<User> scope){ System.debug(Logginglevel.INFO, 'Inside Execute Method'); System.debug(Logginglevel.DEBUG, 'Records fetched from start method >> ' + scope.size()); try{ if (null == scope && scope.IsEmpty()){ system.debug('User List is empty..'); return; } Map<Id,String> mapRoleIdName = null; Map<Id,Id> mapRoleIdParentId = null; Map<Id, List<Id>> mapRoleIdChildId = null; InvestCloudRoleHierarchyIterable icRoleHierarchyIterable= null; icRoleHierarchyIterable= new InvestCloudRoleHierarchyIterable(); mapRoleIdName = new Map<Id,String>(); mapRoleIdParentId = new Map<Id,Id>(); mapRoleIdChildId = new Map<Id,List<Id>>(); List<Id> childRoleIdList = null; for (UserRole userRole : [select id, name, ParentRoleID from UserRole]){ mapRoleIdName.put(userRole.id, userRole.name); if (String.IsNotBlank(userRole.ParentRoleID)) { mapRoleIdParentId.put(userRole.id, userRole.ParentRoleID); if (mapRoleIdChildId.containsKey(userRole.ParentRoleID)) { childRoleIdList = mapRoleIdChildId.get(userRole.ParentRoleID); childRoleIdList.add(userRole.id); mapRoleIdChildId.put(userRole.ParentRoleID, childRoleIdList); } else { mapRoleIdChildId.put(userRole.ParentRoleID, new List<Id>{userRole.id}); } } } icRoleHierarchyIterable.mapRoleIdName = mapRoleIdName; icRoleHierarchyIterable.mapRoleIdParentId = mapRoleIdParentId; icRoleHierarchyIterable.mapRoleIdChildId = mapRoleIdChildId ; icRoleHierarchyIterable.userList = scope; //Database Insertion List<IC_UserRole_Hierarchy__c> iUserRoleHierarchyList = new List<IC_UserRole_Hierarchy__c>(); List<InvestCloudRoleHierarchyIterable.ICUserDataWrapper>         icUserDataWrapperList = icRoleHierarchyIterable.getUserDataWrapper(); if (null != icUserDataWrapperList && !icUserDataWrapperList.IsEmpty()) { iUserRoleHierarchyList = new List<IC_UserRole_Hierarchy__c>(); String currentDateTime = DateTime.now() + ''; currentDateTime = currentDateTime.replaceAll('[^0-9]',''); for(InvestCloudRoleHierarchyIterable.ICUserDataWrapper iDataWrapper : icUserDataWrapperList ){ IC_UserRole_Hierarchy__c iUserRoleHierarchy = new IC_UserRole_Hierarchy__c(); iUserRoleHierarchy.System_Id__c = currentDateTime; iUserRoleHierarchy.User__c = iDataWrapper.userId; iUserRoleHierarchy.First_Name__c = iDataWrapper.firstName; iUserRoleHierarchy.Last_Name__c = iDataWrapper.lastName; iUserRoleHierarchy.CRD__c = iDataWrapper.userCRD; if (String.IsNotBlank(iDataWrapper.personPartyId)) iUserRoleHierarchy.Person_Party_Id__c = iDataWrapper.personPartyId; iUserRoleHierarchy.Current_User_Role_Id__c =iDataWrapper.currentUserRoleId; iUserRoleHierarchy.Current_User_Role__c =iDataWrapper.currentRole; iUserRoleHierarchy.Role_Above_Current_User_Role__c = iDataWrapper.roleNameAboveCurrentUserRole; iUserRoleHierarchy.Role_Below_Current_User_Role__c = iDataWrapper.roleNameBelowCurrentUserRole; iUserRoleHierarchy.Role_Ids_Above_Role__c = iDataWrapper.roleIdAboveCurrentUserRole; iUserRoleHierarchy.Role_Ids_Below_Role__c = iDataWrapper.roleIdBelowCurrentUserRole; iUserRoleHierarchyList.add(iUserRoleHierarchy); } System.debug(Logginglevel.DEBUG,'Size of iUserRoleHierarchyList '+iUserRoleHierarchyList.size()); if(iUserRoleHierarchyList.size()>0){ Database.SaveResult[] saveResultList = Database.insert(iUserRoleHierarchyList, false); for (Database.SaveResult sr : saveResultList) { if (!sr.isSuccess()) { // Operation was successful, so get the ID of the record that was processed System.debug('Successfully inserted Record ' + sr.getId()); } else { // Operation failed, so get all errors for(Database.Error err : sr.getErrors()) { System.debug('The following error has occurred.'); System.debug(err.getStatusCode() + ': ' + err.getMessage()); System.debug(' ICUserRoleHierarchy fields that affected this error: ' + err.getFields()); } } } } } } catch(exception ex){ System.debug(Logginglevel.ERROR, 'Error in InvestCloudRoleHierarchyBatchable.execute() '+ex); } } // Finish the Batch Job public void finish(Database.BatchableContext BC){ System.debug(Logginglevel.INFO, 'Finish method executed'); } } Here is code for Iterable class:- public class InvestCloudRoleHierarchyIterable implements Iterator<ICUserDataWrapper> { public Map<Id, String> mapRoleIdName = null; public Map<Id, String> mapRoleIdParentId = null; public Map<Id, List<Id>> mapRoleIdChildId = null; public List<User> userList; Set<UserRole> roleSet =null; List<String> topMostRoleIds = null; List<ICUserDataWrapper> userDataWrapperList ; Map<String, String> mapMaxRoleIds = null; String strMaxRoleIds = null; //List<String> strMaxRoleIds = null; public List<ICUserDataWrapper> getUserDataWrapper() { try{ for(IC_Role_Hierarchy_Constants__mdt icRH : [select value__c, label from                                                             IC_Role_Hierarchy_Constants__mdt where Label = :ConstantUtils.MAX_ROLE_IDS]){ if (String.IsNotBlank(icRH.value__c )){ mapMaxRoleIds = new map<String, String>(); strMaxRoleIds = icRH.value__c; for (String eId : icRH.value__c.split(',')){ mapMaxRoleIds.put(eId.trim(), eId.trim()); } } } userDataWrapperList= new List<ICUserDataWrapper>(); system.debug(Logginglevel.DEBUG, 'userList --->'+userList.size()); for(User currentUser:UserList ){ Set<Id> allSubRoleIdsBelow =getAllSubRoleIdsForBelowRoles(currentUser.UserRoleId); String allSubRoleIdsBelowInString = getFormattedIdsInString(allSubRoleIdsBelow); Set<String> allSubRoleNamesBelow = getUserRoleName(allSubRoleIdsBelow); String allSubRoleNamesBelowInString = getFormattedNamesInString(allSubRoleNamesBelow ); Set<Id> allSubRoleIdsAbove =getAllSubRoleIdsForAboveRoles(currentUser.UserRoleId); String allSubRoleIdsAboveInString = getFormattedIdsInString(allSubRoleIdsAbove ); Set<String> allSubRoleNamesAbove = getUserRoleName(allSubRoleIdsAbove); String allSubRoleNamesAboveInString = getFormattedNamesInString(allSubRoleNamesAbove); ICUserDataWrapper iUserDataWrapper= new ICUserDataWrapper(); iUserDataWrapper.userId= currentUser.id ; iUserDataWrapper.firstName= currentUser.firstName; iUserDataWrapper.lastName=currentUser.lastName; iUserDataWrapper.userCRD=currentUser.CRD__c; iUserDataWrapper.currentUserRoleId=currentUser.UserRoleId; if (null != currentUser.Person_Party_ID__c) iUserDataWrapper.personPartyId=currentUser.Person_Party_ID__c+''; iUserDataWrapper.currentRole=getUserRoleNameById(currentUser.UserRoleId); iUserDataWrapper.roleNameAboveCurrentUserRole=allSubRoleNamesAboveInString; iUserDataWrapper.roleNameBelowCurrentUserRole=allSubRoleNamesBelowInString; iUserDataWrapper.roleIdAboveCurrentUserRole=allSubRoleIdsAboveInString; iUserDataWrapper.roleIdBelowCurrentUserRole=allSubRoleIdsBelowInString; userDataWrapperList.add(iUserDataWrapper); } } catch(exception ex){ System.debug(Logginglevel.ERROR, 'Error While fetching Current Role --->'+ex); } return userDataWrapperList; } public Boolean hasNext() { return true; } public ICUserDataWrapper next() { return userDataWrapperList[0]; } // Method to get all Parent role Ids for Current Role Ids public Set<ID> getAllSubRoleIdsForAboveRoles(Id roleId) { Set<ID> currentRoleIdsAboveRole = null; try { //Declaring Variables. String parentRoleId = null; currentRoleIdsAboveRole = new Set<ID>(); if (mapRoleIdParentId.containsKey(roleId)) { parentRoleId = mapRoleIdParentId.get(roleId); currentRoleIdsAboveRole.add(parentRoleId ); if (String.IsNotBlank(parentRoleId) && String.IsNotBlank(strMaxRoleIds)                     && !strMaxRoleIds.contains(parentRoleId )) { currentRoleIdsAboveRole.addAll(getAllSubRoleIdsForAboveRoles(parentRoleId )); } } } catch(exception ex){ System.debug(Logginglevel.ERROR,'Error While fetching Parent Role Ids --->'+ex); } /* else { for(UserRole userRole :[SELECT ParentRoleId from UserRole Where Id = :roleId AND ParentRoleID != null]){ // R003, R002 if (String.IsNotBlank(userRole.ParentRoleId) && !parentRoleIds.contains(userRole.ParentRoleId) ) { currentRoleIdsAboveRole.add(userRole.ParentRoleId); currentRoleIdsAboveRole.addAll(getAllSubRoleIdsForAboveRoles(userRole.ParentRoleId)); } } } */ return currentRoleIdsAboveRole; } // Method to get all sub role Ids for Current Role Ids public Set<ID> getAllSubRoleIdsForBelowRoles(Id roleId) { //Declaring Variable. Set<ID> currentRoleIds = null; try { currentRoleIds = new Set<ID>(); if (mapRoleIdChildId.containsKey(roleId)) { List<Id> childRoleIdList = null; childRoleIdList = mapRoleIdChildId.get(roleId); if (!childRoleIdList.IsEmpty()) { for (Id childRoleId : childRoleIdList) { currentRoleIds.add(childRoleId); currentRoleIds.addAll(getAllSubRoleIdsForBelowRoles(childRoleId)); } } } } catch(exception ex){ System.debug(Logginglevel.ERROR, 'Error While fetching Sub Role Ids--->'+ex); } /* else { for(UserRole userRole :[SELECT Id from UserRole Where ParentRoleId = :roleId AND ParentRoleID != null]){ currentRoleIds.add(userRole.Id); currentRoleIds.addAll(getAllSubRoleIdsForBelowRoles(userRole.Id)); } } */ return currentRoleIds; } //Method to get all RoleNames in string public string getFormattedNamesInString(Set<String> roleNames){ String rolenameswithcomma =String.join(new List<String>(roleNames), ','); return rolenameswithcomma; } //Method to get all RoleIds in string public string getFormattedIdsInString(Set<Id> roleIds){ String roleIdswithcomma =String.join(new List<Id>(roleIds), ','); return roleIdswithcomma; } //Method to get RoleName with respect to RoleIds public set<String> getUserRoleName(Set<id> roleIds){ Set<string> roleNames = new Set<string>(); try { for(Id roleId : roleIds) { if (null != mapRoleIdName && mapRoleIdName.containsKey(roleId)) roleNames.add(mapRoleIdName.get(roleId)); } } catch(exception ex){ System.debug(Logginglevel.ERROR, 'Error While fetching Current Role Name ### '+ex); } return roleNames; } //Method to get RoleName with respect to RoleId public String getUserRoleNameById(Id roleId){ if (null != mapRoleIdName && mapRoleIdName.containsKey(roleId)) return mapRoleIdName.get(roleId); return roleId; } public class ICUserDataWrapper{ //declaring variables. public String userId{get; set;} public String firstName{get; set;} public String lastName{get; set;} public String userCRD{get; set;} public String personPartyId{get; set;} public String currentRole{get; set;} public String currentUserRoleId{get; set;} //Below variables will store the comma separated user role names above the current user role public String roleNameAboveCurrentUserRole{get; set;} public String roleNameBelowCurrentUserRole{get; set;} public String roleIdAboveCurrentUserRole{get; set;} public String roleIdBelowCurrentUserRole{get; set;} } } 1.To run,batch process for all users- run following command in developer console Id batchjobid= database.executebatch(new InvestCloudRoleHierarchyBatchable(), 200); 2.To run,batch process for specific user- run following command in developer console Id batchjobid= database.executebatch(new InvestCloudRoleHierarchyBatchable('<<SF User Id>>'), 200); When batch runs,record gets inserted in IC_UserRole_Hierarchy__c object like this. It can extracted through reports on IC_UserRole_Hierarchy__c object.




Comments

Popular posts from this blog

Salesforce Lightning - How To Fire Component Event