global class HistoryTaskBatch implements Database.Batchable { global Database.QueryLocator start(Database.BatchableContext BC) { String soql = 'SELECT Activity_Date__c,Event__c,Id,Daily_Report__c,Event__r.ActivityDate__c,Event__r.Daily_Report__c FROM task__c WHERE Daily_Report_Status__c = null AND Activity_Date__c!=null'; return Database.getQueryLocator(soql); } global void execute(Database.BatchableContext BC,List tasks) { List taskIds = new List(); Map taskMaps = new Map(); List updateTask = new List(); for(task__c task : tasks){ if(task.Event__c == null){ taskIds.add(task.Id); taskMaps.put(task.Id, task); }else{ task.Activity_Date__c = task.Event__r.ActivityDate__c; task.Daily_Report__c = task.Event__r.Daily_Report__c; updateTask.add(task); } } if (taskIds.size() > 0) { List events = [SELECT EventC_ID__c,Task_ID__c,Id FROM Event WHERE Task_ID__c IN :taskIds]; Map eventC2TaskMaps = new Map(); List eventcIds = new List(); for(Event e : events){ System.debug(e.EventC_ID__c+'------'+taskMaps.containsKey(e.Task_ID__c)+'-----'+taskMaps); if (e.EventC_ID__c != null && taskMaps.containsKey(e.Task_ID__c)) { eventcIds.add(e.EventC_ID__c); eventC2TaskMaps.put(e.EventC_ID__c, taskMaps.get(e.Task_ID__c)); } } if (eventcIds.size() > 0) { List eventcs = [SELECT ActivityDate__c,Daily_Report__c FROM Event__c WHERE Id IN :eventcIds]; for(Event__c ec : eventcs){ if (eventC2TaskMaps.containsKey(ec.Id)) { eventC2TaskMaps.get(ec.Id).Event__c = ec.Id; eventC2TaskMaps.get(ec.Id).Activity_Date__c = ec.ActivityDate__c; eventC2TaskMaps.get(ec.Id).Daily_Report__c = ec.Daily_Report__c; updateTask.add(eventC2TaskMaps.get(ec.Id)); } } } } if (updateTask.size() > 0) { update updateTask; } } global void finish(Database.BatchableContext BC) { } @TestVisible private void test() { Integer i = 0; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; i++; } }