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
Saniya Khan 2Saniya Khan 2 

How to write batch class?

Hi All,
How to write batch ?
I have one object called cash_advance want to create/update(If already exist) balance for all cash advance I written some code but its not creating balances for all cash_advance and I think breaking somewhere in middle and Communication failure no response from server message box popping..

Here is my code


Batch class

global class BatchGenerateBalance implements Database.Batchable <sObject> {
 
    public string selectedYearMonth {get;set;}
    public Decimal d;
    public Set<id> caList {get;set;}
    public List<Balance__c> balanceList=new List<Balance__c>();
    public List<Balance__c> updateBalanceList=new List<Balance__c>();
    
   
        private String query = 'Select Id,Name,Cash_Advance_Number__c,Customer_Number__c,Start_Date__c,Customer_Name__r.Name,Close_Date__c,Customer_Name__r.Trading_Address__c, Customer_Name__r.Email__c, Current_Outstanding__c,Holdback_Percentage__c,Repayment_Amount__c from Cash_Advance__c ';

    
    global void execute(SchedulableContext sc) {
        Database.executebatch(this);
    }

    
    global Database.QueryLocator start(Database.BatchableContext BC) {
      System.debug(query);
        return Database.getQueryLocator(query);
        //System.debug('checkcase---' + query); //debugging
    }

    public BatchGenerateBalance(String selectedYrMnth){
        this.selectedYearMonth = selectedYrMnth;        
    }
    
  
    global void execute(Database.BatchableContext BC, List <sObject> scope) {
        
        List <Cash_Advance__c> cashList = (List <Cash_Advance__c> ) scope; //List of cases
    
        System.debug('Size of cashList'+cashList.size());
        System.debug('checkcase---' + scope); 
        
        
        String sDate = selectedYearMonth;
        String monthName;
        System.debug(sDate);
        Integer month = Integer.valueOf(sDate.substring(5));
        Integer year = Integer.valueOf(sDate.substring(0,4));
        System.debug('month=='+ month);
        System.debug('year =='+ year );
        
        if(month==1)
        {
           monthName='Jan' ;
        }
        else if(month==2)
        {
            monthName='Feb';
        }
         else if(month==3)
        {
            monthName='Mar';
        }
         else if(month==4)
        {
            monthName='Apr';
        }
         else if(month==5)
        {
            monthName='May';
        }
         else if(month==6)
        {
            monthName='Jun';
        }
         else if(month==7)
        {
            monthName='Jul';
        }
         else if(month==8)
        {
            monthName='Aug';
        }
         else if(month==9)
        {
            monthName='Sep';
        }
         else if(month==10)
        {
            monthName='Oct';
        }
         else if(month==11)
        {
            monthName='Nov';
        }
         else if(month==12)
        {
            monthName='Dec';
        }
        
        Integer numberOfDays = Date.daysInMonth(year, month);
        Date firstDayOfMonth = Date.newInstance(year, month, 1);
        Date lastDayOfMonth = Date.newInstance(year, month, numberOfDays); 
        System.debug('Anujit==='+ sDate);
        
        System.debug('no.ofDays=='+ numberOfDays);
        System.debug('1stDay=='+ firstDayOfMonth);
        System.debug('lastDay=='+ lastDayOfMonth);
        
        
        for(Cash_Advance__c ca : cashList){
          String balanceName=ca.Cash_Advance_Number__c+'-'+monthName+''+year;
            List<Balance__c> checkAlreadyExist=[Select id,Date__c,name,Total_Daily_Payments_in_Month__c,Total_Adjustments_in_Month__c,Total_Refunds_in_Month__c,Beginning_Balance__c from balance__c where name=:balanceName and Cash_Advance__c=:ca.id];
            if(checkAlreadyExist.isEmpty())
            {
            Balance__c balance=new balance__c();
            
            balance.Cash_Advance__c=ca.ID;
            if(ca.Cash_Advance_Number__c!='')
            {
                 balance.Name=ca.Cash_Advance_Number__c+'-'+monthName+''+year;
            }
            else
            {
                balance.Name='';
            }
            balance.Date__c=monthName+''+year;
             AggregateResult[] result = [select sum(Payment_Amount__c) repamt,Repayment_Month__c from Repayment__c where Description__c ='Daily Repayment' and Cash_Advance__c=:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth  group by Repayment_Month__c ORDER BY Repayment_Month__c];
            
            //Summaries = new List<Summary>();
            Map<String,Decimal> DailyMap= new Map<String,Decimal>();           
            for (AggregateResult ar : result) {
                Decimal repaymentAmt= (Decimal)(ar.get('repamt'));
                String repaymentMonth= (String) ar.get('Repayment_Month__c');

                DailyMap.put(repaymentMonth,repaymentAmt);
            }
             //cashAdvance = [Select Id,Customer_Name__c,Amount_Advanced__c  from Cash_Advance__c where Id=:selectedId ];
            AggregateResult[] resultad1 = [select sum(Payment_Amount__c) repamt, Repayment_Month__c from Repayment__c where Description__c ='Adjustment' and Cash_Advance__c=:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth group by Repayment_Month__c ORDER BY Repayment_Month__c];  
        
           
            
            Map<String,Decimal> adjMap= new Map<String,Decimal>();           
            for (AggregateResult ar : resultad1 ) {
             Decimal repaymentAmt= (Decimal)(ar.get('repamt'));
             String repaymentMonth= (String) ar.get('Repayment_Month__c');

                adjMap.put(repaymentMonth,repaymentAmt);
            }
              AggregateResult[] resultre1 = [select sum(Payment_Amount__c) repamt, Repayment_Month__c from Repayment__c where Description__c ='Refund' and Cash_Advance__c=:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth  group by Repayment_Month__c ORDER BY Repayment_Month__c];  
        
            
            
            Map<String,Decimal> rfundMap= new Map<String,Decimal>();           
            for (AggregateResult ar : resultre1 ) {
             Decimal repaymentAmt= (Decimal)(ar.get('repamt'));
             String repaymentMonth= (String) ar.get('Repayment_Month__c');

                rfundMap.put(repaymentMonth,repaymentAmt);
            }
                Decimal totalOfAll=0;
             Set<String> yearMonthSet= new Set<String>();
            yearMonthSet.addAll(DailyMap.KeySet());
            yearMonthSet.addAll(adjMap.KeySet());
            yearMonthSet.addAll(rfundMap.KeySet());
            List<String> yearMonthList= new List<String>();
            yearMonthList.addAll(yearMonthSet);
            yearMonthList.sort();
            for(String ym: yearMonthList){ 
                 Decimal d1= DailyMap.get(ym);
                if(d1!= null){
                    Balance.Total_Daily_Payments_in_Month__c = d1;
                }else{
                    Balance.Total_Daily_Payments_in_Month__c =0;
                }
                Decimal d2= adjMap.get(ym);
                if(d2!= null){
                    Balance.Total_Adjustments_in_Month__c = d2;
                }else{
                    Balance.Total_Adjustments_in_Month__c= 0;
                }
                Decimal d3= rfundMap.get(ym);
                if(d3!= null){
                    Balance.Total_Refunds_in_Month__c = d3;
                }else{
                    Balance.Total_Refunds_in_Month__c= 0;
                }
                // Balance.Total_Payments_in_Month__c=(d1==null?0:d1)+(d2==null?0:d2)+(d3==null?0:d3);
                totalOfAll=d1+d2+d3;
                System.debug('Total of all is'+totalOfAll);
            }
             List<Repayment__c> rpmtList1 = [select Repayment_Date__c, Payment_Amount__c,Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth];
        Integer bal=0;
        
        List<Date> prevList = new List<Date>();
        for(Repayment__c rp:rpmtList1 ){
            prevList.add(rp.Repayment_Date__c);
        
        }
        prevList.sort();
        System.debug('BAL=========='+ prevList);
        bal=rpmtList1.size();
        
        if(!prevList.isEmpty()){
            List<Repayment__c> repp = [select Repayment_Date__c, Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c=:prevList[0] ORDER BY Previous_Balance__c DESC];
            List<Repayment__c> repp1 = [select Repayment_Date__c, Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c=:prevList[bal-1]];
        
            if(!repp.isEmpty()){
                Balance.Beginning_Balance__c = repp[0].Previous_Balance__c;     
                System.debug('OPEN =='+  balance.Beginning_Balance__c );                
            }
            
        

        } 


        else{
          List<Repayment__c> temprpmtList = [select Repayment_Date__c, Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c<:firstDayOfMonth ORDER BY Previous_Balance__c ASC];
          if(ca.Current_Outstanding__c == ca.Repayment_Amount__c){
                  balance.Beginning_Balance__c = ca.Repayment_Amount__c;
                  //scc.Ending_Balance__c = ca.Repayment_Amount__c;  
          } else if(temprpmtList.size() != 0){
            balance.Beginning_Balance__c = temprpmtList [0].balance__c;
           // scc.Ending_Balance__c = temprpmtList [0].balance__c;
         } else {
            balance.Beginning_Balance__c = ca.Repayment_Amount__c;
           // scc.Ending_Balance__c = ca.Repayment_Amount__c;   
         }
        }
        
        balanceList.add(Balance);
        
        }
            else
            {
                for(Balance__c updatebal:checkAlreadyExist) 
                {
                         AggregateResult[] result = [select sum(Payment_Amount__c) repamt,Repayment_Month__c from Repayment__c where Description__c ='Daily Repayment' and Cash_Advance__c=:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth  group by Repayment_Month__c ORDER BY Repayment_Month__c];
            
            //Summaries = new List<Summary>();
            Map<String,Decimal> DailyMap= new Map<String,Decimal>();           
            for (AggregateResult ar : result) {
                Decimal repaymentAmt= (Decimal)(ar.get('repamt'));
                String repaymentMonth= (String) ar.get('Repayment_Month__c');

                DailyMap.put(repaymentMonth,repaymentAmt);
            }
             //cashAdvance = [Select Id,Customer_Name__c,Amount_Advanced__c  from Cash_Advance__c where Id=:selectedId ];
            AggregateResult[] resultad1 = [select sum(Payment_Amount__c) repamt, Repayment_Month__c from Repayment__c where Description__c ='Adjustment' and Cash_Advance__c=:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth /*and Repayment_Date__c>=:startDate and Repayment_Date__c<=:endDate*/ group by Repayment_Month__c ORDER BY Repayment_Month__c];  
        
           
            
            Map<String,Decimal> adjMap= new Map<String,Decimal>();           
            for (AggregateResult ar : resultad1 ) {
             Decimal repaymentAmt= (Decimal)(ar.get('repamt'));
             String repaymentMonth= (String) ar.get('Repayment_Month__c');

                adjMap.put(repaymentMonth,repaymentAmt);
            }
              AggregateResult[] resultre1 = [select sum(Payment_Amount__c) repamt, Repayment_Month__c from Repayment__c where Description__c ='Refund' and Cash_Advance__c=:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth /*and Repayment_Date__c>=:startDate and Repayment_Date__c<=:endDate*/ group by Repayment_Month__c ORDER BY Repayment_Month__c];  
        
            
            
            Map<String,Decimal> rfundMap= new Map<String,Decimal>();           
            for (AggregateResult ar : resultre1 ) {
             Decimal repaymentAmt= (Decimal)(ar.get('repamt'));
             String repaymentMonth= (String) ar.get('Repayment_Month__c');

                rfundMap.put(repaymentMonth,repaymentAmt);
            }
             Set<String> yearMonthSet= new Set<String>();
            yearMonthSet.addAll(DailyMap.KeySet());
            yearMonthSet.addAll(adjMap.KeySet());
            yearMonthSet.addAll(rfundMap.KeySet());
            List<String> yearMonthList= new List<String>();
            yearMonthList.addAll(yearMonthSet);
            yearMonthList.sort();
            for(String ym: yearMonthList){ 
                 Decimal d1= DailyMap.get(ym);
                if(d1!= null){
                    updatebal.Total_Daily_Payments_in_Month__c = d1;
                }else{
                    updatebal.Total_Daily_Payments_in_Month__c =0;
                }
                Decimal d2= adjMap.get(ym);
                if(d2!= null){
                    updatebal.Total_Adjustments_in_Month__c = d2;
                }else{
                    updatebal.Total_Adjustments_in_Month__c= 0;
                }
                Decimal d3= rfundMap.get(ym);
                if(d3!= null){
                    updatebal.Total_Refunds_in_Month__c = d3;
                }else{
                    updatebal.Total_Refunds_in_Month__c= 0;
                }
                // Balance.Total_Payments_in_Month__c=(d1==null?0:d1)+(d2==null?0:d2)+(d3==null?0:d3);
                
            }
             List<Repayment__c> rpmtList1 = [select Repayment_Date__c, Payment_Amount__c,Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c>=:firstDayOfMonth and Repayment_Date__c<=:lastDayOfMonth];
        Integer bal=0;
        
        List<Date> prevList = new List<Date>();
        for(Repayment__c rp:rpmtList1 ){
            prevList.add(rp.Repayment_Date__c);
        
        }
        prevList.sort();
        System.debug('BAL=========='+ prevList);
        bal=rpmtList1.size();
        
        if(!prevList.isEmpty()){
            List<Repayment__c> repp = [select Repayment_Date__c, Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c=:prevList[0] ORDER BY Previous_Balance__c DESC];
            List<Repayment__c> repp1 = [select Repayment_Date__c, Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c=:prevList[bal-1]];
        
            if(!repp.isEmpty()){
                updatebal.Beginning_Balance__c = repp[0].Previous_Balance__c;     
                System.debug('OPEN =='+  updatebal.Beginning_Balance__c );                
            }
            
        

        } 


        else{
          List<Repayment__c> temprpmtList = [select Repayment_Date__c, Previous_Balance__c,Balance__c from Repayment__c where Cash_Advance__c =:ca.Id and Repayment_Date__c<:firstDayOfMonth ORDER BY Previous_Balance__c ASC];
          if(ca.Current_Outstanding__c == ca.Repayment_Amount__c){
                  updatebal.Beginning_Balance__c = ca.Repayment_Amount__c;
                  //scc.Ending_Balance__c = ca.Repayment_Amount__c;  
          } else if(temprpmtList.size() != 0){
            updatebal.Beginning_Balance__c = temprpmtList [0].balance__c;
           // scc.Ending_Balance__c = temprpmtList [0].balance__c;
         } else {
            updatebal.Beginning_Balance__c = ca.Repayment_Amount__c;
           // scc.Ending_Balance__c = ca.Repayment_Amount__c;   
         }
        }
         updateBalanceList.add(updatebal);
                }
                
            }
       }
        if(!updateBalanceList.isEmpty())
        {
            update updateBalanceList;
            System.debug('Updated All Balances Successfuly');
        }
        if(!balanceList.isEmpty())
        {
            System.debug('Size of Balance List'+balanceList.size());
            insert balanceList;
            System.debug('Inserted All Balances Successfuly');
        }
    }
    global void finish(Database.BatchableContext BC) {

    }
}

Can anyone please help me for this?
Many thanks,
Saniya