+ Start a Discussion
Team WorksTeam Works 

Apex Batch Job for looping thru the 3 lookup relationship

Hello All, Please suggest if the following Batch APex can be improved..It first defines the scope by selecting all the Master cities. It then finds all the cities associated to Master Cities. It then loops thru all the accounts in each cities and does the sum up calculations based on certain conditions. It also updates 2 account fields and updates fields on top level Master City object.
Many Thanks in advance ...
global class MasterCity_BatchJob  implements Database.Batchable<SObject>{

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([Select Id from Pseudo_City__c where RecordTypeId='012m00000004HZLAA2']);
        // where Id='a0Cm000000060Ai'
    }
       
    global void execute(Database.BatchableContext BC, List<SObject> mcityscope){      
        List<Pseudo_City__c> scope = (List<Pseudo_City__c>)mcityscope;//Casting sObject to Master City List
        system.debug('The Scope created in Execute method is >>>>>'+scope );
        MasterCityBatchJobHelper MChelper = new MasterCityBatchJobHelper();
        MChelper.citiesInMasterCity(scope);
    }
   
    global void finish(Database.BatchableContext BC){}
}
-----------------------------------------------------------------------------------------
//Initialize the variables which will store summaries to 0
          integer mtotalLiveAccount=0;
          integer mtotalfivestarHotels=0;
          integer mtotalfourstarHotels =0;
          integer mtotalthreestarHotels =0;         
          integer mTotalGTAconnectRegional = 0;
          integer mTotalGTAconnectGlobal = 0;
          integer mTotalGTAconnectIndependent = 0;          
          integer mtotalCityCenterAccount = 0;
          integer mtotalAirportAccount=0; 
          integer mtotalRegionAccount =0;
          integer mtotalPOIAccount=0;
          integer mtotalTwoStarorLess=0;
          double GrandTotalRNs2013=0;    
          integer mTotalUnCategorized =0;
        
          public Map<Id,City__c> mcitiesToUpdate = new Map<Id,City__c>();//Map to hold the cities
          List<Pseudo_City__c> masterCitiesToUpdate = new List<Pseudo_City__c>();//List of Master Cities to be updated
          List<Account> accToUpdateList = new List<Account>();
    //constructor
    public MasterCityBatchJobHelper(){}
   
   
    public PageReference analyzeAccountFromPage() {
          List<Pseudo_City__c> mcities = [select id from Pseudo_City__c where id = :ApexPages.currentPage().getParameters().get('id')];
          system.debug('The mCities in ANalyse Accounts from PageReference is  >>>>>'+ mcities  );
          citiesInMasterCity(mcities);
          return new Pagereference('/'+ApexPages.currentPage().getParameters().get('id'));
    }
   
  
    //Methods
    public void citiesInMasterCity(List<Pseudo_City__c> scope) {
         scope = [Select Id,City_Categorisation__c,Name,GTA_3_Hotels__c,GTA_4_Hotels__c,GTA_5_Hotels__c,GTA_2_or_less_Hotels__c,GTA_Hotels_2012__c,RN_Projection_2014_Top_Focus__c,GTA_Independant__c,GTA_Global_Chain_Hotels__c,GTA_Regional_Chain_Hotels__c,Suburbs_Airport__c,GTA_POI_Hotels__c,uncategorised_properties__c,GTA_City_Centre_Penetration__c from Pseudo_City__c where Id IN: scope];
         system.debug('The SCOPE in citiesInMasterCity is  >>>>>  '+ scope );
         for(Pseudo_city__c mcity : scope){
                 system.debug('The value in the mastercitiestoUpdate before update>>>>>>>>>>>> ' + mcity.id );       
                 masterCitiesToUpdate.add(analyzeMastercity(mCity));//Loads the list with Mastercities to be updated to List
                
        }
           
            Database.update(masterCitiesToUpdate);//Updates and commits the calculations in the List to the Database
    }


   
  
    private Pseudo_city__c analyzeMasterCity(Pseudo_city__c mCity) {
       
         for(City__c city :[Select Id, Name,Master_City_Cluster_This_Year__c,City_Location__c FROM City__c where Master_City_Cluster_This_Year__c =:mCity.Id]){
                   If(city.Master_City_Cluster_This_Year__c != null )
                      mcitiesToUpdate.put(city.id,city);
                 
          }   
                 system.debug('The cities within the Master cities are ::>>>> '+ mcitiesToUpdate ); 
                 return summarizeAccounts(mcitiesToUpdate, mCity);
    }
       
       
   
  
    private Pseudo_city__c summarizeAccounts(Map<Id,City__c> mcitiesToUpdate,Pseudo_City__c mCity){
  
             for(Account acc : [Select Id,Name,Property_Status__c,Master_City_Cluster_Tier_This_Year__c,Master_City_Name_This_Year__c,Location__c,recordTypeId,Star_Rating__c,GTA_Connect_Chain__c,DI_Master_Chain__c,ThresholdC__c,Grand_Total_RNs_2013__c,City_New__c from Account where (RecordType.developerName='Property' AND Property_Status__c='LIVE' AND City_New__c IN :mcitiesToUpdate.keySet())]){
                           mtotalLiveAccount += 1;
                   
                    if (acc.City_new__c != null){
                        acc.Master_City_Name_This_Year__c = mCity.Name;
                        acc.Master_City_Cluster_Tier_This_Year__c = mCity.City_Categorisation__c;
                        accToUpdateList.add(acc);
                        system.debug('The Account to be updated>>>>>>> ' +accToUpdateList);
                        }
                       
                   
                    if(mcitiesToUpdate.get(acc.City_New__c).City_Location__c != null){ 
                       if(mcitiesToUpdate.get(acc.City_New__c).City_Location__c == 'City Center')
                            mtotalCityCenterAccount+= 1;
                         
                       if(mcitiesToUpdate.get(acc.City_New__c).City_Location__c == 'Suburb & Airport')
                            mtotalAirportAccount+= 1;
                          
                       if(mcitiesToUpdate.get(acc.City_New__c).City_Location__c == 'Point of interest')
                            mtotalPOIAccount+= 1;
                     }
                   
                   
                   if ((acc.Star_Rating__c=='5 Star' || acc.Star_Rating__c=='5.5 Star')  && acc.Star_Rating__c != null)
                       mtotalfivestarHotels += 1;            
                   if ((acc.Star_Rating__c=='4 Star' || acc.Star_Rating__c=='4.5 Star' ) && acc.Star_Rating__c != null)
                       mtotalfourstarHotels += 1;            
                   if ((acc.Star_Rating__c=='3 Star' || acc.Star_Rating__c=='3 Star' ) && acc.Star_Rating__c != null  )
                       mtotalthreestarHotels += 1;            
                   if(acc.Star_Rating__c =='1 Star' || acc.Star_Rating__c=='2 Star' || acc.Star_Rating__c== 'NA' )
                       mtotalTwoStarorLess+=1; 
               
          
                   if (!((acc.DI_Master_Chain__c == 'ACCOR') || (acc.DI_Master_Chain__c == 'BW') || (acc.DI_Master_Chain__c == 'DESIGN') || (acc.DI_Master_Chain__c == 'EC') || (acc.DI_Master_Chain__c == 'FAIRMONT') || (acc.DI_Master_Chain__c == 'HILTON') || (acc.DI_Master_Chain__c == 'HYATT') || (acc.DI_Master_Chain__c == 'IHG') || (acc.DI_Master_Chain__c == 'JUMEIRAH') || (acc.DI_Master_Chain__c == 'KI') || (acc.DI_Master_Chain__c == 'LUXE') || (acc.DI_Master_Chain__c == 'MC') || (acc.DI_Master_Chain__c == 'MK') || (acc.DI_Master_Chain__c == 'MOHG') || (acc.DI_Master_Chain__c == 'SG') || (acc.DI_Master_Chain__c == 'WY') ) && (acc.GTA_Connect_Chain__c != null)  && !((acc.GTA_Connect_Chain__c == 'Intercontinental Hotels Group') || (acc.GTA_Connect_Chain__c == 'Accor Hotels') || (acc.GTA_Connect_Chain__c == 'Best Western International') || (acc.GTA_Connect_Chain__c == 'Carlson Hospitality') || (acc.GTA_Connect_Chain__c == 'Choice Hotels International') || (acc.GTA_Connect_Chain__c == 'Design Hotels') || (acc.GTA_Connect_Chain__c == 'Fairmont Raffles Swissotel Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Four Seasons Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Hilton Worldwide') || (acc.GTA_Connect_Chain__c == 'Hyatt Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Jumeirah International LLC') || (acc.GTA_Connect_Chain__c == 'Kempinski') || (acc.GTA_Connect_Chain__c == 'KEMPINSKI HOTELS & RESORTS') || (acc.GTA_Connect_Chain__c == 'Langham Hotels') || (acc.GTA_Connect_Chain__c == 'Luxe Worldwide Hotels') || (acc.GTA_Connect_Chain__c == 'Mandarin Oriental Hotel Group') || (acc.GTA_Connect_Chain__c == 'Marriott International Inc.') || (acc.GTA_Connect_Chain__c == 'Millennium & Copthorne Hotels plc') || (acc.GTA_Connect_Chain__c == 'Moevenpick Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Shangri-La Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Starwood Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'The Ascott Group') || (acc.GTA_Connect_Chain__c == 'Wyndham Hotel Group' ) || (acc.GTA_Connect_Chain__c == 'independent' )))
                        mTotalGTAconnectRegional+= 1;           
                   if (((acc.GTA_Connect_Chain__c == 'Intercontinental Hotels Group') || (acc.GTA_Connect_Chain__c == 'Accor Hotels') || (acc.GTA_Connect_Chain__c == 'Best Western International') || (acc.GTA_Connect_Chain__c == 'Carlson Hospitality') || (acc.GTA_Connect_Chain__c == 'Choice Hotels International') || (acc.GTA_Connect_Chain__c == 'Fairmont Raffles Swissotel Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Four Seasons Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Hilton Worldwide') || (acc.GTA_Connect_Chain__c == 'Hyatt Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Jumeirah International LLC') || (acc.GTA_Connect_Chain__c == 'Kempinski') || (acc.GTA_Connect_Chain__c == 'KEMPINSKI HOTELS & RESORTS') || (acc.GTA_Connect_Chain__c == 'Langham Hotels') || (acc.GTA_Connect_Chain__c == 'Luxe Worldwide Hotels') || (acc.GTA_Connect_Chain__c == 'Mandarin Oriental Hotel Group') || (acc.GTA_Connect_Chain__c == 'Marriott International Inc.') || (acc.GTA_Connect_Chain__c == 'Millennium & Copthorne Hotels plc') || (acc.GTA_Connect_Chain__c == 'Moevenpick Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Shangri-La Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Starwood Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'The Ascott Group') || (acc.GTA_Connect_Chain__c == 'Wyndham Hotel Group')) && !(acc.GTA_Connect_Chain__c == null))
                        mTotalGTAconnectGlobal+= 1;    
                   if(((acc.GTA_Connect_Chain__c == 'independent') &&  !((acc.DI_Master_Chain__c == 'ACCOR') || (acc.DI_Master_Chain__c == 'BW') || (acc.DI_Master_Chain__c == 'EC') || (acc.DI_Master_Chain__c == 'FAIRMONT') || (acc.DI_Master_Chain__c == 'HILTON') || (acc.DI_Master_Chain__c == 'HYATT') || (acc.DI_Master_Chain__c == 'IHG') || (acc.DI_Master_Chain__c == 'JUMEIRAH') || (acc.DI_Master_Chain__c == 'KI') || (acc.DI_Master_Chain__c == 'MC') || (acc.DI_Master_Chain__c == 'MK') || (acc.DI_Master_Chain__c == 'MOHG') || (acc.DI_Master_Chain__c == 'SG') || (acc.DI_Master_Chain__c == 'WY'))))
                        mTotalGTAconnectIndependent +=1;
                   if(((acc.GTA_Connect_Chain__c == null) &&  !((acc.DI_Master_Chain__c == 'ACCOR') || (acc.DI_Master_Chain__c == 'BW') || (acc.DI_Master_Chain__c == 'EC') || (acc.DI_Master_Chain__c == 'FAIRMONT') || (acc.DI_Master_Chain__c == 'HILTON') || (acc.DI_Master_Chain__c == 'HYATT') || (acc.DI_Master_Chain__c == 'IHG') || (acc.DI_Master_Chain__c == 'JUMEIRAH') || (acc.DI_Master_Chain__c == 'KI') || (acc.DI_Master_Chain__c == 'MC') || (acc.DI_Master_Chain__c == 'MK') || (acc.DI_Master_Chain__c == 'MOHG') || (acc.DI_Master_Chain__c == 'SG') || (acc.DI_Master_Chain__c == 'WY'))))
                        mTotalUnCategorized +=1;    
                   if(acc.ThresholdC__c=='Top Focus' && acc.ThresholdC__c!= null && acc.Grand_Total_RNs_2013__c != null)
                       GrandTotalRNs2013 = GrandTotalRNs2013 + acc.Grand_Total_RNs_2013__c;
                   
                      
             }
                       accountToUpdate(accToUpdateList);
                       mCity.GTA_Hotels_2012__c = mtotalLiveAccount;
                       mCity.GTA_City_Centre_Penetration__c=mtotalCityCenterAccount;
                       mCity.Suburbs_Airport__c= mtotalAirportAccount;
                       mCity.GTA_POI_Hotels__c= mtotalPOIAccount;
                      
                       mCity.GTA_Hotels_2012__c = mtotalLiveAccount;
                       mCity.GTA_5_Hotels__c= mtotalfivestarHotels;            
                       mCity.GTA_4_Hotels__c= mtotalfourstarHotels;             
                       mCity.GTA_3_Hotels__c = mtotalthreestarHotels;
                       mCity.GTA_2_or_less_Hotels__c=mtotalTwoStarorLess;
             
                       mCity.GTA_Global_Chain_Hotels__c=mTotalGTAconnectGlobal;
                       mCity.GTA_Regional_Chain_Hotels__c=  mTotalGTAconnectRegional;
                       mCity.GTA_Independant__c =    mTotalGTAconnectIndependent;                     
                       mCity.RN_Projection_2014_Top_Focus__c = GrandTotalRNs2013;
                       mCity.uncategorised_properties__c =mTotalUnCategorized ;
                                        
                      
                       system.debug('The Total number of accounts for this Master City is  '+ mtotalLiveAccount); 
                       system.debug('The no hotels in CityCenter : ' + mtotalCityCenterAccount);
                       system.debug('The no hotels in Airport : ' + mtotalAirportAccount); 
                       system.debug('The no of hotels in POI  is : ' + mtotalPOIAccount);
                       system.debug('The Total number of accounts for this Master City is  '+ mtotalLiveAccount); 
                       system.debug('The no hotels in CityCenter : ' + mtotalCityCenterAccount);
                       system.debug('The no hotels in Airport : ' + mtotalAirportAccount); 
                       system.debug('The no of hotels in POI  is : ' + mtotalPOIAccount);       
         
                       system.debug('The no of 3 star hotel here is : ' + mtotalthreestarHotels);
                       system.debug('The no of 4 star hotel here is : ' + mtotalfourstarHotels );
                       system.debug('The no of 5 star hotel here is : ' + mtotalfivestarHotels );
                       system.debug('The no of 2 star and less hotel  is : ' + mtotalTwoStarorLess);
         
                       system.debug('The no of GTAconnectGlobal hotel  is : ' + mTotalGTAconnectGlobal);
                       system.debug('The no of GTAconnectRegional hotel  is : ' + mTotalGTAconnectRegional);
                       system.debug('The no of GTAconnectIndependent hotel  is : ' + mTotalGTAconnectIndependent);
                       system.debug('The no hotels uncategorized : ' + mCity.uncategorised_properties__c);      
                  
                   return mCity;

   
       }       
      
      
       private void accountToUpdate(List<Account> account){
           Database.update(account);
          }
  }
Ashish_SFDCAshish_SFDC
Hi Namo, 


This code is very long to understand and visualise the flow, 

Can you explain how you are looking to Improvise - based on lines of code or Logic used or Test method based ?

Or is it that you are hitting any errors or governor limits on this ?


Regards,
Ashish