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
Andreea TAndreea T 

Help with batch class

I want to make one batch class for the following:
I need to create 2 fields in account: AllRevenue and Ytd.
AllRevenue is the SUM of all the Amounts of all Invoices of the Account WHERE Category_Invoice__c != 'Monthly' AND Status__c != 'invoice_canceled' .
Ytd is the SUM of all the Amounts of all Invoices of the Account WHERE Category_Invoice__c != 'Monthly' AND Status__c != 'invoice_canceled' AND Date_Invoice__c= THIS_YEAR AND Date_Invoice__c <= TODAY.
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Imo

      As per your statement AllRevenue and Ytd is the collective amount of all invoices and I m not sure of what you actually meant in the statement
              need to create 2 fields in account: AllRevenue and Ytd.
 
if you want to store the calculated amount in a field added in account (to be created field AllRevenue and Ytd) then, on which Account record you will set the calculated amount.

The following batch will do the calculation. 
global class BatchAccountCalc implements Database.Batchable<SObject>, Database.Stateful{

     public Decimal AllRevenue = 0;
     public Decimal Ytd = 0;

     global Database.QueryLocator start (Database.BatchableContext bc){
          
          String query = 'SELECT Id, Amount, Date_invoice__c from Account WHERE Category_Invoice__c != \'Monthly\' and Status__c != \'invoice_cancelled\' ';
          return Database.getQueryLocator(query);
     }

     global void execute (Database.BatchableContext bc, List<Account> accList){
          
          List<Acccount> invoiceDateAccList = new List<Account>(); 
          Date fromDate = Date.newInstance(System.today().Year(), 01,01);
          for(Account acc : accList){ 
               AllRevenue += acc.Amount;
               if(acc.Date_Invoice__c >= fromDate && acc.Date_Invoice__c <= System.today()){
                    Ytd += acc.Amount;
               }
          }
     }

     global void finish (Database.BatchableContext bc){

           System.debug('Sum of all account ' + AllRevenue);
           System.debug('Sum of all account based on invoice date  ' + Ytd);
           //if you want to update to one particular account you can do it here
     }
}
 
Calling Part

BatchAccountCalc cal = new BatchAccountCalc();
Database.executeBatch(cal,200);

//based on the no of accounts you have set the batch size. Max 2000

I hope the answer is helpful for you

Regards
Karthik