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 

While running batch class its creating records but getting communication failure No response from server the Records in lacs

While running batch class its creating records but getting communication failure No response from server..
here is my code
The class which calling Batch class
public class GenerateBalanceController {
 public string selectedYearMonth {get;set;} 
    
    
    public GenerateBalanceController(){
        //generate();
    }
      public PageReference go(){
       
             BatchGenerateBalance job = new BatchGenerateBalance(selectedYearMonth);
             Database.executeBatch(job, 10);
             
             PageReference pageRef1 = ApexPages.CurrentPage();
             ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Balance are generated succesfully');
             ApexPages.addMessage(myMsg); 
             return pageRef1;
             
         //}   
     }
    
    
       public List<selectOption> getVal() {
        List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
        //options.add(new selectOption('', '- None -')); //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
        Date endDate =Date.newInstance(System.today().year(),System.today().month(), 01);
        Date startDate = endDate.addDays(-365);
        
        for (integer i=0;i<=12;i++) { 
            
            Date dt= startDate.addMonths(i); 
            String sDt =dt.year()+'/'+dt.month();
            if(dt.month()<10){
                sDt =dt.year()+'/0'+dt.month();
            }
            options.add(new selectOption(sDt, sDt)); //for all records found - add them to the picklist options
        }
        return options; //return the picklist options
        
     }  
}
Batch class It create balance from cash advance and if its already exist then update it(Just wanted to confirm the records are in  lacs)
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('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);
            }
             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);
                
            }
             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())
        {
            insert balanceList;
            System.debug('Inserted All Balances Successfuly');
        }
    }
    global void finish(Database.BatchableContext BC) {

    }
}

Could anyone please help me with this..
Many thanks,
Saniya