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
bheemudu neelibheemudu neeli 

Batch Class to update a custom field on User object(i.e: count the number of accounts at account owner level)

It is urgent requiremnet,
count the number of accounts at account owner level.
 I mean the accounts they are the ownerof. the requiremnet is only count of accouts not a name.
for example: account, contain 100 records on same account owner. then this count of 100 sholud be display on that Users custom field.

Here is the code,

global class NumberOfBPsClass implements Database.Batchable<sObject> {
   
    List<Account> acc= new List<Account>();
   //String query;
    Set<Id> userIds =new Set<Id>();
   User currentUser=new User();
     //currentUserId = UserInfo.getUserId();
    //List<User> currentUser=[SELECT Number_of_Business_Partners__c,Number_of_BPs_in_Team__c FROM User WHERE Id=:currentUserId];
    
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        
        return Database.getQueryLocator([SELECT Number_of_Business_Partners__c,Number_of_BPs_in_Team__c FROM User]);
    }
   
    global void execute(Database.BatchableContext BC, List<sObject> scope)
      {
          List<Account> accns = new List<Account>();
       List<user> lstcon= new List<user>();
         for(sObject s : scope)
         {
                 Account a = (Account)s;
                 user c = new user();
        c.Number_of_Business_Partners__c=accns.size();
                  lstcon.add(c);
                  }
          
      insert lstcon;
      }
    global void finish(Database.BatchableContext BC) {
    }
}


thnaks in advance
Best Answer chosen by bheemudu neeli
Suraj GharatSuraj Gharat
Hi Bheemudu,

If need all the accounts owned by you or each user, you may simply go to Accounts tab and select List View named My Accounts.

Yet if you need to have the count on each user record using Batch Apex you may use below code (Though I'm not aware why you want to use Batch here instead of Trigger)
 
public Database.Querylocator start(Database.BatchableContext bc){
	return new Database.Querylocator([SELECT Number_of_Business_Partners__c FROM User]);
}

public void execute(Database.BatchableContext bc,List<SObject> lstScope){
	Map<Id,Account> mapIdToAccount=new Map<Id,Account>((List<Account>)lstScope);
	// Get count for each owner
	for(AggregateResult result:[Select OwnerId,Count(id) FROM Account WHERE OwnerId IN :mapIdToAccount.keyset() GROUP BY OwnerId LIMIT 2000]){
		User u=mapIdToAccount.get(result.get('OwnerId'));
		// If count is changed then only update it
		if(u.Number_of_Business_Partners__c!=(Decimal)result.get('expr0'))
			u.Number_of_Business_Partners__c=(Decimal)result.get('expr0');
		else
			mapIdToAccount.remove(u.Id);
	}
	update mapIdToAccount.values();
}
public void finish(Database.BatchableContext bc){
}

HTH,
Suraj
 

All Answers

Suraj GharatSuraj Gharat
Hi Bheemudu,

If need all the accounts owned by you or each user, you may simply go to Accounts tab and select List View named My Accounts.

Yet if you need to have the count on each user record using Batch Apex you may use below code (Though I'm not aware why you want to use Batch here instead of Trigger)
 
public Database.Querylocator start(Database.BatchableContext bc){
	return new Database.Querylocator([SELECT Number_of_Business_Partners__c FROM User]);
}

public void execute(Database.BatchableContext bc,List<SObject> lstScope){
	Map<Id,Account> mapIdToAccount=new Map<Id,Account>((List<Account>)lstScope);
	// Get count for each owner
	for(AggregateResult result:[Select OwnerId,Count(id) FROM Account WHERE OwnerId IN :mapIdToAccount.keyset() GROUP BY OwnerId LIMIT 2000]){
		User u=mapIdToAccount.get(result.get('OwnerId'));
		// If count is changed then only update it
		if(u.Number_of_Business_Partners__c!=(Decimal)result.get('expr0'))
			u.Number_of_Business_Partners__c=(Decimal)result.get('expr0');
		else
			mapIdToAccount.remove(u.Id);
	}
	update mapIdToAccount.values();
}
public void finish(Database.BatchableContext bc){
}

HTH,
Suraj
 
This was selected as the best answer
bheemudu neelibheemudu neeli
Hello Suraj Thank and Greatly appriciated....

I have one more field on User, i.e: Number_of_Items__c, this is represents that current users role, so many users contain same role right.,

then my requirement is, I have one role 'XYZ', this is same for 5 users, then each user have 10 account records, then finally  5*10=50 is the result, ok,
this final result should be my output. and this is need on user field i.e: Number_of_Items__c

I hope you can understand.

thanks

 
Suraj GharatSuraj Gharat
Hi Bheemudu,

I see you need count of total accounts/partners role wise, on user record. If I'm not wrong, then in your above example, all five users with "XYZ" role will have value 50 in their "Number_of_Items__c" fields. For this you may refer below script:
 
public Database.Querylocator start(Database.BatchableContext bc){
	return new Database.Querylocator([SELECT Number_of_Business_Partners__c,Role__c FROM User]);
}

public void execute(Database.BatchableContext bc,List<SObject> lstScope){

	Map<Id,User> mapIdToUser=new Map<Id,User>((List<Account>)lstScope);
	// This map will hold the mapping of user role to account count
	Map<String,Integer> mapRoleCount=new Map<String,Integer>();
	// Get count for each owner
	for(AggregateResult result:[Select OwnerId,Count(id) FROM Account WHERE OwnerId IN :mapIdToUser.keyset() GROUP BY OwnerId LIMIT 2000]){
		User u=mapIdToUser.get(result.get('OwnerId'));
		// If count is changed then only update it
		if(u.Number_of_Business_Partners__c!=(Decimal)result.get('expr0'))
			u.Number_of_Business_Partners__c=(Decimal)result.get('expr0');
		else
			mapIdToUser.remove(u.Id);
		
		// Compute total number of accounts on Role basis
		if(mapRoleCount.contains(u.Role__c))
			mapRoleCount.put(u.Role__c,(mapRoleCount.get(u.Role__c)+u.Number_of_Business_Partners__c));
		else
			mapRoleCount.put(u.Role__c,u.Number_of_Business_Partners__c);
	}
	
	// Update User field "Number_of_Items__c" by computed number of accounts for that role
	for(User u:mapIdToUser.values())
		if(mapRoleCount.contains(u.Role__c))
			u.Number_of_Items__c=mapRoleCount.get(u.Role__c);
	
	update mapIdToUser.values();
}
public void finish(Database.BatchableContext bc){
}

Hope this helps!!