+ Start a Discussion
F SmoakF Smoak 

batch apex to combine all batch records processed to insert record

I am creating a batch class that queries on a call object and filters all the latest call records to populate this information on a custom object. My call records satisfying query is 6000 records so what happens is that the call records are divided across 3 batches and creates 3 records whereas I want this combined in single record. I tried to implement stateful method and insert in finish method. But this does not help,please help on this!
global class CMS_Batch_Alert_Submitted_Call implements Database.Batchable<sObject>,Database.Stateful{
    List<Alert_vod__c> alertsubmittedcalllist = new List<Alert_vod__c>();
    global Database.QueryLocator start(Database.BatchableContext BC) {
       
        List<String> countrycodeList = new List<String>();
        for(Pfizer_Country_Code_Setting__mdt mdt:[Select Label from Pfizer_Country_Code_Setting__mdt]){
            countrycodeList.add(mdt.Label);
        }
        String query = 'SELECT id,CMS_Submitted_DateTime__c,Account_vod__c,Account_vod__r.name,ownerid,owner.name,Detailed_Products_vod__c FROM Call2_vod__c where Status_vod__c = \'Submitted_vod\' AND CMS_Submitted_DateTime__c = LAST_N_DAYS:7 and Account_vod__c !=null and CMS_Country_Code__c in : countrycodeList';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject>scope) {
        List<Call2_vod__c> callList = (List<Call2_vod__c>) scope;
        system.debug('call list>>>>'+calllist);
        List<Pfizer_Submitted_Call_Alert_Text_Values__mdt> langlist = new List<Pfizer_Submitted_Call_Alert_Text_Values__mdt>();
        for(Pfizer_Submitted_Call_Alert_Text_Values__mdt langmdt : [Select Id,CMS_Submitted_Call_Alert_Header__c,CMS_Submitted_Call_Alert_Text_Header__c,CMS_Submitted_Call_By__c,CMS_Submitted_Call_Language_Key__c,CMS_Seen__c from Pfizer_Submitted_Call_Alert_Text_Values__mdt]){
            langlist.add(langmdt);
        } 
        //List<Alert_vod__c> alertsubmittedcalllist = new List<Alert_vod__c>();
        Map<Id,Call2_vod__c> callmap = new Map<Id,Call2_vod__c>();
        for(Call2_vod__c c:calllist){
            if(!callmap.containsKey(c.account_vod__c)){
                callmap.put(c.Account_vod__c,c);
            }
            else{
                Call2_vod__c cc = callmap.get(c.account_vod__c);
                if(cc.CMS_Submitted_DateTime__c < c.CMS_Submitted_DateTime__c) {
                    callmap.remove(c.account_vod__c);
                }
                callmap.put(c.account_vod__c,c);
            }}
        system.debug('callmap>>>'+callmap);
        Set<String> terrname = new set<String>();
        List<Cycle_Plan_Target_vod__c> cptlist = [SELECT Cycle_Plan_Account_vod__c,Cycle_Plan_vod__r.Territory_vod__c FROM Cycle_Plan_Target_vod__c WHERE Cycle_Plan_Account_vod__c IN:callmap.keyset() AND Cycle_Plan_vod__r.active_vod__c = true];
        system.debug('cptlist>>>'+cptlist);
        for(Cycle_Plan_Target_vod__c cpt: cptlist){
            terrname.add(cpt.Cycle_Plan_vod__r.Territory_vod__c);
        }system.debug('terrname>>'+terrname);
        Map<string,id> utmap = new Map<string,id>();
        for(territory ut: [Select id,name from Territory where territory.name in : terrname]){
            utmap.put(ut.name,ut.id);
        }
        Map<id,List<id>> useraccmap = new Map<id,List<id>>();
        Map<id,List<id>> accterrmap = new Map<id,List<id>>();
        Map<id,List<Call2_vod__c>> finalmap = new Map<id,List<Call2_vod__c>>();
        for(Cycle_Plan_Target_vod__c cpt: cptlist){
            if(utmap.containskey(cpt.Cycle_Plan_vod__r.Territory_vod__c)){
                if(!accterrmap.containsKey(utmap.get(cpt.Cycle_Plan_vod__r.Territory_vod__c))){
                    accterrmap.put(utmap.get(cpt.Cycle_Plan_vod__r.Territory_vod__c), new List<String>{cpt.Cycle_Plan_Account_vod__c});
                }else{
                    List<id> i = new List<id>();
                    i = accterrmap.get(utmap.get(cpt.Cycle_Plan_vod__r.Territory_vod__c));
                    i.add(cpt.Cycle_Plan_Account_vod__c);
                    accterrmap.put(utmap.get(cpt.Cycle_Plan_vod__r.Territory_vod__c),i);
                    
                }
            } }system.debug('accterrmap>>'+accterrmap);
        Map<id,List<Call2_vod__c>> terrcallmap = new Map<id,List<Call2_vod__c>>();
        for(Id tempid: accterrmap.keyset()){
            List<id> tempidlist = accterrmap.get(tempid);
            for(id i:tempidlist){
                if(callmap.containsKey(i)){
                    if(!terrcallmap.containsKey(tempid)){
                        List<Call2_vod__c> i1 = new List<Call2_vod__c>();
                        i1.add(callmap.get(i));
                        terrcallmap.put(tempid,i1);
                    }
                    else{
                        List<Call2_vod__c> i2 = new List<Call2_vod__c>();
                        i2=terrcallmap.get(tempid);
                        i2.add(callmap.get(i));
                        terrcallmap.put(tempid,i2);
                    }
                }
            }
        }system.debug('terrcallmap>>'+terrcallmap);
        
        List<UserTerritory> utlist =[Select userid, territoryid from UserTerritory where territoryid in: terrcallmap.keyset()];
        
        Map<id,id> useridterridmap = new Map<id,id>();
        for(UserTerritory ut: utlist){
            useridterridmap.put(ut.territoryid,ut.userid);
        }system.debug('useridterridmap>>'+useridterridmap);
        for(id i3: terrcallmap.keyset()){
            if(useridterridmap.containskey(i3)){
                finalmap.put(useridterridmap.get(i3),terrcallmap.get(i3));          
            }
        }system.debug('finalmap>>>'+finalmap);
        
        for(id i4: finalmap.keyset()){
            system.debug('i4>>>'+i4);
            String userlang = [Select languagelocalekey from User where id =: i4].languagelocalekey;
            String concatenatedtext='';
            String submittedCallHeader='';
            Integer size = 0;
            for(Pfizer_Submitted_Call_Alert_Text_Values__mdt lmdt : langlist){
               if(lmdt.CMS_Submitted_Call_Language_Key__c == userlang){
                  submittedCallHeader = lmdt.CMS_Submitted_Call_Alert_Header__c;
                   concatenatedText=lmdt.CMS_Submitted_Call_Alert_Text_Header__c+'\n';
           for(Call2_vod__c c:finalmap.get(i4)){ 
               if(c.ownerid != i4){
                   size=size+1;
               concatenatedText+=c.Account_vod__r.name+' '+lmdt.CMS_Seen__c+' '+c.CMS_Submitted_DateTime__c.format('MMMMM').substring(0,3)+' '+c.CMS_Submitted_DateTime__c.day()+' '+lmdt.CMS_Submitted_Call_By__c+' '+c.owner.name+'\n';            
               if(c.Detailed_Products_vod__c != null){
                 concatenatedText= concatenatedText.removeEnd('\n');
                    concatenatedText+=  '('+c.Detailed_Products_vod__c+')'+'\n';
                }
               }}
               concatenatedText = concatenatedText.removeEnd('\n');
               }}
            if(size>0){
            Alert_vod__c alert = new Alert_vod__c();
            alert.Name = submittedCallHeader;
            alert.Activation_Date_vod__c = system.now();
            alert.Alert_Text_vod__c = concatenatedText;
            alert.Expiration_Date_vod__c = system.now()+1;
            alert.Public_vod__c = true;
            alert.ownerid=i4;
            alert.Priority_vod__c = 'Normal';
            alert.Dismissible_vod__c = true;
            alertsubmittedcalllist.add(alert);
            }}
        
    }
   
    global void finish(Database.BatchableContext BC) {
        if(alertsubmittedcalllist.size()>0)
        {
            insert alertsubmittedcalllist;
            system.debug('alert list>>>>'+alertsubmittedcalllist +alertsubmittedcalllist.size());
        }
    }
}