function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yoni LegacyYoni Legacy 

Assign UserId from UserTerritory object as Owner of Account List record

public with sharing class Eisai_InsertAcctList_cls {
    
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>(); 
    Set<Id> AffFromAcctSet = new Set<Id>(); 
    Set<String> uniqueFieldSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs;
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
	
	//added Collections
	List<Id> fromAcctIdList = new List<Id>();
	List<TSF_vod__c> terr = new List<TSF_vod__c>();
	List<UserTerritory> userTerrInGroupAcct = new List<UserTerritory>();
	Set<String> terrSet = new Set<String>(); 
	Set<Id> terrIdSet = new Set<Id>();
	
    
    public Eisai_InsertAcctList_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE Parent_vod__c = True 
                                                         AND From_Account_RecType__c = 'Group_Practice_Account']);
                                                    //   AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
		
		//added SOQL Queries
		for(Affiliation_vod__c affFromAcct : allAffParentRecs){
				fromAcctIdList.add(affFromAcct.From_Account_vod__c);
		}
        
		for(TSF_vod__c terr : [SELECT Id, Territory_vod__c, Account_vod__c FROM TSF_vod__c WHERE Account_vod__c IN:fromAcctIdList]){
				terrSet.add(terr.Territory_vod__c);
		}
		
		System.debug('Territory count: ' + terrSet.size());
		
		for(Territory terrId : [SELECT Id, Name FROM Territory WHERE Name IN:terrSet]){
				terrIdSet.add(terrId.Id);
		}
		
		userTerrInGroupAcct = [SELECT TerritoryId, UserId FROM UserTerritory WHERE TerritoryId IN: terrIdSet];
        
        System.debug('No. of user owns the Group Practice Account: ' + userTerrInGroupAcct.size());
        
        //end of added SOQL Queries
		
		
        for(Account_List_vod__c xAcctListRecs  : [Select Name_Populate_Unique_Owner__c FROM Account_List_vod__c 
                                                  									   WHERE Name_Populate_Unique_Owner__c != Null])
                                                  									//   WHERE OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Name_Populate_Unique_Owner__c);
        }
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            for(UserTerritory userTerrId : userTerrInGroupAcct){
                if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                    Account_List_vod__c AccListRec = new Account_List_vod__c();    
                        AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                        AccListRec.Icon_Name_vod__c = '0';  
                        AccListRec.OwnerId = userTerrId.UserId;
                        AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                        newAccListRecList.add(AccListRec);
             	}
        	}
        }
        
        for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
        
        Database.SaveResult[] srList = Database.insert(InsertedAccList, false);

        for (Database.SaveResult sr: srList){
            if(sr.isSuccess()){
                System.debug('Inserted Account List count: ' + sr.getId());
            } else {
                for(Database.Error err : sr.getErrors()){
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                }
            }
        }
    }//end of 1st block
   
   /*         
   public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    } */
    
}// End of Class
How can I make the Owner of Account List to be the UserId returned in userTerrInGroupAcct (Set)

Here is the query:
userTerrInGroupAcct = [SELECT TerritoryId, UserId FROM UserTerritory WHERE TerritoryId IN: terrIdSet];

If there are 12 users returned on the query above, there should be 12 Account List created, the OwnerId should be each of the 12 users.

Thanks. 
 
GauravGargGauravGarg
Hi Yoni,

Could you please explain the problem you are facing currently with the code written above.

Thanks,
Gaurav
Email: gauravgarg.nmims@gmail.com
Skype: gaurav62990
Yoni LegacyYoni Legacy

Gaurav,

I just need to create an Account List records per UserId returned in userTerrInGroupAcct (Set).

Example there are 10 userIds in userTerrInGroupAcct (set) there should be 10 Account List records should be created as well where the owner is quel to userId..

Thanks
Marion




 

Yoni LegacyYoni Legacy
The UserId consist of different Users.
Yoni LegacyYoni Legacy
Here is my current code:
 
public class Eisai_InsertAcctList_TEST {
    
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>(); 
    Set<Id> AffFromAcctSet = new Set<Id>(); 
    Set<String> uniqueFieldSet = new Set<String>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
	
	//added Collections
	List<TSF_vod__c> tsfRecsList = new List<TSF_vod__c>();
	List<UserTerritory> userTerrInGroupAcct = new List<UserTerritory>();
	List<Account> gpAcctIds = new List<Account>();
	Set<String> terrSet = new Set<String>(); 
	Set<Id> terrIdSet = new Set<Id>();
	
    
    public Eisai_InsertAcctList_TEST(){

        
		gpAcctIds = [SELECT Id FROM Account WHERE Account_Type__c = 'Group Practice' AND Account_Hide_Reason_esi__c = Null];
		
		//added SOQL Queries
        
		for(TSF_vod__c tsf : [SELECT Id, Territory_vod__c, Account_vod__c FROM TSF_vod__c WHERE Account_vod__c IN:gpAcctIds]){
				tsfRecsList.add(tsf);
				terrSet.add(tsf.Territory_vod__c);
		}
		
		System.debug('Territory count: ' + terrSet.size());
		
		for(Territory terrId : [SELECT Id, Name FROM Territory WHERE Name IN:terrSet]){
				terrIdSet.add(terrId.Id);
		}
		
		userTerrInGroupAcct = [SELECT TerritoryId, UserId FROM UserTerritory WHERE IsActive = True 
																			 AND TerritoryId IN: terrIdSet];
        
        System.debug('No. of user owns the Group Practice Account: ' + userTerrInGroupAcct.size());
        
        //end of added SOQL Queries
		
		
        for(Account_List_vod__c xAcctListRecs  : [Select Name_Populate_Unique_Owner__c FROM Account_List_vod__c 
                                                  									   WHERE Name_Populate_Unique_Owner__c != Null
                                                  									   AND OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Name_Populate_Unique_Owner__c);
        }
        
        for(TSF_vod__c terrInAcct :tsfRecsList){
              for(Integer i = 0; i < userTerrInGroupAcct.size(); i++){
                        Account_List_vod__c AccListRec = new Account_List_vod__c();    
                            AccListRec.Name = 'HO_' + terrInAcct.Account_vod__c; 
                            AccListRec.Icon_Name_vod__c = '0';  
                            AccListRec.OwnerId = userTerrInGroupAcct[i].UserId;
                            newAccListRecList.add(AccListRec);
              }
        } 
        
       for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
        
        Database.SaveResult[] srList = Database.insert(InsertedAccList, false);

        for (Database.SaveResult sr: srList){
            if(sr.isSuccess()){
                System.debug('Inserted Account List count: ' + sr.getId());
            } else {
                for(Database.Error err : sr.getErrors()){
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                }
            }
        }
    }//end of 1st block
           
   public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
    
}// End of Class



But I'm getting this error below:

User-added image

Any assistance is appreciated.

Thanks
Marion

 
GauravGargGauravGarg
Yoni,

Do you need to multiple account object record having same owner Id? Please contact me on skype: gaurav62990 or email: gauravgarg.nmims@gmail.com

Thanks,
Gaurav
 
GauravGargGauravGarg

Yoni,

As per the above code, you are getting error on line 41. I can just think that number of Account getting queried over here are too much. Is it possible you can limit the size of account record get queried. 

For example try to limit 1000 and run again. If that works

Thanks,

Gaurav

VineetKumarVineetKumar
Seems like you need to optimise your queries, perhaps the queries are returning more records than expected :
  • Try to put more fiters to your query, using WHERE clause ( maybe a date filter or something like that..)
  • As a best practise please put a LIMIT clause of 50000 records in your query if it returns more than 50000 records.                                     Eg.. SELECT Id FROM Account WHERE Id != NULL LIMIT 50000
Let me know if that helped.
Yoni LegacyYoni Legacy
Hi sorry to get back just now. I tried to work on the code, it's working on if there is one affiliation record when I tested.

Here is the code:
 
public with sharing class Eisai_InsertAcctList_cls {
    
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>(); 
    Set<Id> AffFromAcctSet = new Set<Id>(); 
    Set<String> uniqueFieldSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs;
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
	
	//added Collections
	List<Id> fromAcctIdList = new List<Id>();
	List<TSF_vod__c> terr = new List<TSF_vod__c>();
	List<UserTerritory> userTerrInGroupAcct = new List<UserTerritory>();
    List<Account_List_vod__c> accListToInsert = new List<Account_List_vod__c>();
	Set<String> terrSet = new Set<String>(); 
	Set<Id> terrIdSet = new Set<Id>();
    Set<String> fromAcctValList = new Set<String>();
	
    
    public Eisai_InsertAcctList_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE Parent_vod__c = True
                                                    	 AND From_Account_vod__c = '0011200001EURv0'
                                                         AND From_Account_RecType__c = 'Group_Practice_Account'
                                                 	     AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Id '+ allAffParentRecs.size());
		
		//added SOQL Queries
		for(Affiliation_vod__c affFromAcct : allAffParentRecs){
            if(!AffFromAcctSet.contains(affFromAcct.From_Account_vod__c)){
				fromAcctIdList.add(affFromAcct.From_Account_vod__c);
            	fromAcctValList.add(affFromAcct.From_Account_Value__c);
            	AffFromAcctSet.add(affFromAcct.From_Account_vod__c);
            }
		}
        
        
        
		for(TSF_vod__c terr : [SELECT Id, Territory_vod__c, Account_vod__c FROM TSF_vod__c 
                               											   WHERE Account_vod__c IN:fromAcctIdList]){
				terrSet.add(terr.Territory_vod__c);
		}
		
		System.debug('Territory count: ' + terrSet.size());
		
		for(Territory terrId : [SELECT Id, Name FROM Territory 
                                				WHERE Name IN:terrSet]){
				terrIdSet.add(terrId.Id);
		}
		
		userTerrInGroupAcct = [SELECT UserId FROM UserTerritory 
                                       		 WHERE TerritoryId IN: terrIdSet];

       System.debug('No. of user owns the Group Practice Account: ' + userTerrInGroupAcct.size());
        
        //end of added SOQL Queries
		
		
        for(Account_List_vod__c xAcctListRecs  : [Select Name_Populate_Unique_Owner__c FROM Account_List_vod__c 
                                                  									   WHERE Name_Populate_Unique_Owner__c != Null
                                                  									   AND OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Name_Populate_Unique_Owner__c);
        }
        
        for(String allParentAffRecs: fromAcctValList){
                   for(Integer i = 0; i < userTerrInGroupAcct.size(); i++){
                        Account_List_vod__c AccListRec = new Account_List_vod__c();    
                            AccListRec.Name = 'HO_' + allParentAffRecs; 
                            AccListRec.Icon_Name_vod__c = '0';  
                            AccListRec.OwnerId = userTerrInGroupAcct[i].UserId; 
                        	newAccListRecList.add(AccListRec);
                   }
        }
        
        for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
            
        Database.SaveResult[] srList = Database.insert(InsertedAccList, false);

        for (Database.SaveResult sr: srList){
            if(sr.isSuccess()){
                System.debug('Inserted Account List count: ' + sr.getId());
            } else {
                for(Database.Error err : sr.getErrors()){
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                }
            }
        }
    }//end of 1st block
            
   public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
    
}// End of Class

Here is the log of that code:

User-added image

But when I removed or comment out the line below, it's not working:
AND From_Account_vod__c = '0011200001EURv0'

This is my confussion if there are 20 rows (Record) returned in my initial query, will it process one by one, or by bulk like 10 at a time?

Thanks
Marion
VineetKumarVineetKumar
First you should not be hardcoding the Id's in your code, it is not as per the best practice.
Since you are looping around the records, it will process it one by one.
Yoni LegacyYoni Legacy
I think the challenge is to where I can pull the Account Name (Line 70 ) to put in AccListRec.Name = 'HO_' + allParentAffRecs; (Line 73).
I can't think of a way, because there is no identical (Unique) field in UserTerritory object to objects where there is Account field, so that I can use MAP
Yoni LegacyYoni Legacy
VineetKumar,

I just hardcoded the Affiliation Id to process only single record (For Testing purposes)

My concern is how can I get the Account (From_Account_vod__c) and make it the Name of each Account List.
VineetKumarVineetKumar
How many records do you have in Affiliation_vod__c object?
Yoni LegacyYoni Legacy
As I queried the records,

SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE Parent_vod__c = True
                                                         AND From_Account_RecType__c = 'Group_Practice_Account'
                                                         AND OwnerId IN(SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%'
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%')
                                      AND IsActive = TRUE)

The total records is 365. Thanks
 
Yoni LegacyYoni Legacy
Hi VineetKumar and GauravGarg are you guys there?
GauravGargGauravGarg

Hi Yoni,

This need to be optimized, can you pleae contact me on below details.

Thanks,

Gaurav
Email: gauravgarg.nmims@gmail.com
Skype: gaurav62990

Yoni LegacyYoni Legacy
can't be in here GauravGarg?