• ranga babu vangalapudi 2
  • NEWBIE
  • 40 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 5
    Replies
Hi ,

I have written the following Rest api, WHILE testing it using postman i am getting an error: "Apex:System CPU Limit exceeded."

Can any one help me with this.

@RestResource (urlMapping='/Outletmasters/*')
//https://cs73.salesforce.com/services/apexrest/Outletmasters/
global with sharing class OutletRestClass {  
    @HttpGet
    global static list<Account> getAccounts(){
           DateTime dt= system.today();
           DateTime starttime = dt.addMinutes(+90);
        DateTime endtime = dt.addMinutes(+990);     
        //where ((LastModifiedDate >=: starttime AND LastModifiedDate <=: endtime) OR (CreatedDate >=: starttime AND CreatedDate <=: endtime)) AND Ipas_Flag__c !=true  
        String query = 'Select Id,Name, Active__c,Address__c,Beat_Code__r.Name, Beat_Name__c,Channel_type__c,Cluster__c,Cluster_Code__r.Cluster_Code__c,Contract_type__c, Country_liquor_sold__c,District__c,Geo_Location__latitude__s,Geo_Location__longitude__s,Goegraphy_state__c,Group_Outlet__c,Group_Name__c,Group_ID_1_del__c,Location_Type__c,Lower_Prestige__c,Luxury_Core__c,Market_Type__c,Micro_channel__c,Mid_Prestige__c,MSL_Town_Tier__c,O_L_Id__c,Outlet_Contact_Person__c,Outlet_License_Code__c,Outlet_License_Name__c,Outlet_Mobile__c,Overall_Segmentation__c,Perfect_Outlet__c,Pincode__c,Premium_Core__c,Primary_Occasion__c,Primary_Customer_Name__r.Name,Primary_Customer_ID_del__c,RPC__c,RPC_Code__c,Secondary_Occasion__c,TL_Code__r.Name,Town__c,Town_code__c,TSE_Code__r.Name,TL_Territory_Name__c,TSE_Name__c,USL_Outlet_ID__c,Upper_Prestige__c,Visit_Frequency__c FROM Account where Ipas_Flag__c !=true LIMIT 1700';
        RestRequest req = RestContext.request; 
        RestResponse res = RestContext.response; 
        list<Account> acc_toUpdate = new list<Account>();
        list<Account> acc_tosend = new list<Account>();
           list<Account> accList = Database.query(query);         
        for(Account a: accList){
            a.Ipas_Flag__c = true;
            acc_toUpdate.add(a);
        } 
        update acc_toUpdate;
        for(Account ac: accList){
            if(ac.Name == NULL || ac.Name == '') ac.Name ='null';
            if(ac.Active__c == NULL || ac.Active__c == '') ac.Active__c ='null';
            if(ac.Address__c == NULL || ac.Address__c == '') ac.Address__c ='null';
            if(ac.Beat_Code__r.Name == NULL || ac.Beat_Code__r.Name == '') ac.Beat_Code__r.Name ='null';
            if(ac.Channel_type__c == NULL || ac.Channel_type__c == '') ac.Channel_type__c ='null';
            if(ac.Cluster_Code__r.Cluster_Code__c == NULL || ac.Cluster_Code__r.Cluster_Code__c == '') ac.Cluster_Code__r.Cluster_Code__c ='null';
            if(ac.Contract_type__c == NULL || ac.Contract_type__c == '') ac.Contract_type__c ='null';
            if(ac.Country_liquor_sold__c == NULL || ac.Country_liquor_sold__c == '') ac.Country_liquor_sold__c ='null';
            if(ac.District__c == NULL || ac.District__c == '') ac.District__c ='null';
            if(ac.Geo_Location__Latitude__s == NULL || ac.Geo_Location__Longitude__s == NULL ){
                ac.Geo_Location__Latitude__s = null;
                ac.Geo_Location__Longitude__s = null;
            }
            if(ac.Goegraphy_state__c == NULL || ac.Goegraphy_state__c == '') ac.Goegraphy_state__c ='null';
            if(ac.Group_Outlet__c == NULL || ac.Group_Outlet__c == '') ac.Group_Outlet__c ='null';
            if(ac.Group_Name__c == NULL || ac.Group_Name__c == '') ac.Group_Name__c ='null';
            //if(ac.Group_Lead_TL__c == NULL || ac.Group_Lead_TL__c == '') ac.Group_Lead_TL__c ='null';
            if(ac.Location_Type__c == NULL || ac.Location_Type__c == '') ac.Location_Type__c ='null';
            if(ac.Lower_Prestige__c == NULL || ac.Lower_Prestige__c == '') ac.Lower_Prestige__c ='null';
            if(ac.Luxury_Core__c == NULL || ac.Luxury_Core__c == '') ac.Luxury_Core__c ='null';
            if(ac.Market_Type__c == NULL || ac.Market_Type__c == '') ac.Market_Type__c ='null';
            if(ac.Micro_channel__c == NULL || ac.Micro_channel__c == '') ac.Micro_channel__c ='null';
            if(ac.Mid_Prestige__c == NULL || ac.Mid_Prestige__c == '') ac.Mid_Prestige__c ='null';
            if(ac.MSL_Town_Tier__c == NULL || ac.MSL_Town_Tier__c == '') ac.MSL_Town_Tier__c ='null';
            if(ac.O_L_Id__c == NULL || ac.O_L_Id__c == '') ac.O_L_Id__c ='null';
            if(ac.Outlet_Contact_Person__c == NULL || ac.Outlet_Contact_Person__c == '') ac.Outlet_Contact_Person__c ='null';
            if(ac.Outlet_License_Code__c == NULL || ac.Outlet_License_Code__c == '') ac.Outlet_License_Code__c ='null';
            if(ac.Outlet_License_Name__c == NULL || ac.Outlet_License_Name__c == '') ac.Outlet_License_Name__c ='null';
            if(ac.Outlet_Mobile__c == NULL || ac.Outlet_Mobile__c == '') ac.Outlet_Mobile__c ='null';
            if(ac.Overall_Segmentation__c == NULL || ac.Overall_Segmentation__c == '') ac.Overall_Segmentation__c ='null';
            if(ac.Perfect_Outlet__c == NULL || ac.Perfect_Outlet__c == '') ac.Perfect_Outlet__c ='null';
            if(ac.Pincode__c == NULL || ac.Pincode__c == '') ac.Pincode__c ='null';
            if(ac.Premium_Core__c == NULL || ac.Premium_Core__c == '') ac.Premium_Core__c ='null';
            if(ac.Primary_Occasion__c == NULL || ac.Primary_Occasion__c == '') ac.Primary_Occasion__c ='null';
            if(ac.Primary_Customer_Name__c == NULL || ac.Primary_Customer_Name__c == '') ac.Primary_Customer_Name__c =null;
            if(ac.Secondary_Occasion__c == NULL || ac.Secondary_Occasion__c == '') ac.Secondary_Occasion__c ='null';
            if(ac.TL_Code__r.Name == NULL || ac.TL_Code__r.Name == '') ac.TL_Code__r.Name ='null';  
            if(ac.Town__c == NULL || ac.Town__c == '') ac.Town__c ='null';  
            if(ac.Town_code__c == NULL || ac.Town_code__c == '') ac.Town_code__c ='null';  
            if(ac.TSE_Code__r.Name == NULL || ac.TSE_Code__r.Name == '') ac.TSE_Code__r.Name ='null';  
            if(ac.USL_Outlet_ID__c == NULL || ac.USL_Outlet_ID__c == '') ac.USL_Outlet_ID__c ='null';  
             if(ac.Upper_Prestige__c == NULL || ac.Upper_Prestige__c == '') {ac.Upper_Prestige__c ='null';}            
                   acc_tosend.add(ac);  
            }
        return acc_tosend;
        }       
    }
===============================================
i know this may happened becaused i used many if conditions in a for loop. please help me to reduce this.

Regards,
Ranga.V
Hi, 
Below is my Rest api
@RestResource (urlMapping='/Outletmasters/*')
global with sharing class OutletRestClass {  
    @HttpGet
    global static list<Account> getAccounts(){
        String query = 'Select Id,Name, Active__c,Address__c,Beat_Code__r.Name, Beat_Name__c,Channel_type__c,Cluster__c,Cluster_Code__r.Cluster_Code__c,Contract_type__c, Country_liquor_sold__c,District__c,Geo_Location__latitude__s,Geo_Location__longitude__s,USL_Outlet_ID__c FROM Account  where (LastModifiedDate = TODAY OR CreatedDate = TODAY) AND Ipas_Flag__c != true LIMIT 1700';
        RestRequest req = RestContext.request; 
        RestResponse res = RestContext.response; 
        list<Account> acc_tosend = new list<Account>();
           list<Account> accList = Database.query(query);
        for(Account ac: accList){
            if(ac.Geo_Location__Latitude__s == NULL || ac.Geo_Location__Longitude__s == NULL || ac.Group_Name__c == NULL || ac.Lower_Prestige__c == NULL){
                ac.Geo_Location__Latitude__s = null;
                ac.Geo_Location__Longitude__s = null;
                ac.Group_Name__c ='null';
                ac.Lower_Prestige__c ='null';
                   acc_tosend.add(ac);
            }
        }
        return acc_tosend;
    }
}

Below is the Test class, it is covering only 30% of the code:

@isTest
public class OutletMastersRestClass {
    public static testMethod void getOutletDetails() {
        Test.startTest();
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/Outletmasters'; 
        req.httpMethod = 'GET';
        req.addHeader('Content-Type', 'application/json'); 
        RestContext.request = req;
        RestContext.response = res;
        list<Account> acc = OutletRestClass.getAccounts();
   Test.stopTest();   
    }
}

your help is greatly appreciated.

Thanks,
Ranga.V
Following is my code to upload csv file

public class importDataFromCSVController {
  public transient string csvAsString{get;set;}
  public transient String[] csvFileLines{get;set;}
  public  boolean secondBlock{get;set;}
  public  List<account> acclist{get;set;}
  public  String newline{get;set;}
  public  String coma{get;set;}
  public transient String listAccount{get;set;}
  public  String selectedValue{get;set;}
  public static string CSVfromJS;
  
  public importDataFromCSVController(){
    newline = '\n';
    coma = ',';
    csvFileLines = new String[]{};
    acclist = New List<Account>(); 
  }
  
  public List<SelectOption> getFSEOptions() {
       List<SelectOption> FSEoptions = new List<SelectOption>();
       FSEoptions.add(new SelectOption('Outlet Master','Outlet Master'));
       //FSEoptions.add(new SelectOption('Brand Master','Brand Master'));
       return FSEoptions;
  }
  
  Public List<String> headerValues{get;set;}
  public Map<String,String> fldsWithData{get;set;}
  public List<Account> onLoadLimitData{get;set;}
  public void importCSVFile(){
      fldsWithData = New Map<String,String>();
      onLoadLimitData = New List<Account>();
      secondBlock = true;
      headerValues = New List<String>();
      Boolean boolsizecheck = true;
          try{
           csvAsString = listAccount;
           //csvFileLines = csvAsString.split('\n');
           Utility_RowIterator r = New Utility_RowIterator(csvAsString,'\n'); 
            Integer i1 = 0;
            List<String> tempList = new List<String>();
            while(r.hasNext()){
              //system.debug('x : ' +r.next());
              //csvFileLines[i1++] = r.next();
                 // From here the code is not covered
              if(tempList.size()>2001 && boolsizecheck){
                  ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.error,'The records to load is high in number, maximum number of records you can load is 2000' );
                  ApexPages.addMessage(errorMessage);
                  boolsizecheck = false;
                  break;
              }
              else
              tempList.add(r.next());
            } 
            csvFileLines = tempList;
           //system.debug('====csvFileLines' + csvFileLines.size());
        
           List<String> headerValues1 = csvFileLines[0].split(',');
              
           for(integer i=0;i<headerValues1.size();i++){
               if(headerValues1[i].trim().length()>0){
                   headerValues.add(headerValues1[i].trim());
               }
           }
            
              if(boolsizecheck){
                  for(Integer i=1;i<csvFileLines.size();i++){
                      Account accObj = new Account() ;
                      List<string> csvRecordDataCommaNotConsdrd = csvFileLines[i].split(',');
                      List<string> csvRecordData = new List<String>();
                      string temp = '';
                      for(string str : csvRecordDataCommaNotConsdrd){
                          if(str.contains('"') || temp != ''){
                              if(str.contains('"') && temp != '' && temp.contains('"')){
                                  temp += str;
                                  csvRecordData.add(temp.replace('"',''));
                                  temp = '';
                                  continue;
                              }
                              if(str.contains('"')){
                                  temp += str+',';
                                  continue;
                              }
                              if(!str.contains('"')){
                                  temp += str+',';
                              }
                          }
                          else{
                              csvRecordData.add(str);
                          }
                      }
                      for(integer j=0;j<headerValues.size();j++){           
                          if(headerValues[j].trim().length()>0){
                              //system.debug('headerValues[j].trim()'+headerValues[j].trim() + csvRecordData[j].trim());
                              if(!(headerValues[j].trim() == 'ID' &&( csvRecordData[j].trim() == '' || csvRecordData[j].trim() =='"'))){
                                  accObj.put(headerValues[j].trim(),csvRecordData[j].trim().replaceAll('"',''));//.replaceAll('"','')
                              }
                          }
                      }
                      accList.add(accObj);
                  } 
                  if(accList.size()>500){
                      integer limitOnCount = 0;
                      ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.info,'Count is more than 500 showing only 500');
                      for(integer i=0;i<accList.size();i++){
                          if(limitOnCount <= 500){
                              onLoadLimitData.add(accList[i]);
                              limitOnCount = limitOnCount + 1;
                          }
                      }
                  }else{
                      onLoadLimitData.addAll(accList);
                  }
              }
           }catch(Exception e){
                   ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.error,'Something went wrong please resave your .csv file and try again. If error still exist please contact system admin' + e);
                   ApexPages.addMessage(errorMessage);
           }
          
  }
  
  public list<Account> faultRecords{get;set;}
  public boolean thirdblock{get;set;}
  public String myListString {get;set;}
  public void uploadData(){
     thirdblock = true;
     Integer successfullCount = 0;
     Integer failureCount = 0;
     Database.UpsertResult[] srList = Database.upsert(acclist, false);
     faultRecords = New List<Account>();
     for(integer i=0;i<srList.size();i++){
         if (!srList[i].isSuccess()) {
             failureCount = failureCount + 1;
            // errorIndex.put(i,'error messge');
             Account errorfile = acclist.get(i);
             Database.Error error = srList.get(i).getErrors().get(0);
             errorfile.Error_File__c =  'Error:'+ string.valueOf(error.getMessage());
             faultRecords.add(errorfile);
             headerValues.add('Error_File__c');
         }else{
             Account succesfile = acclist.get(i);
             succesfile.id = srList[i].getId();
            succesfile.Error_File__c = 'Success';
             headerValues.add('Error_File__c');
             headerValues.add('Id');
         }
     }
      Set<String> allFlds = New Set<String>();
      allFlds.addAll(headerValues);
      headerValues.clear();
      headerValues.addAll(allFlds);
      myListString = string.join(headerValues,',');
      successfullCount = srList.size() - failureCount;
      
      ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.error,'Error Count Records:'+failureCount);
      ApexPages.addMessage(errorMessage);
      
      ApexPages.Message successMessage = new ApexPages.Message(ApexPages.severity.info,'successfull Count Records:'+successfullCount);
      ApexPages.addMessage(successMessage);
      
  }
  
  
    public pageReference downloadPage(){
        exportCSVController();
        EmailTemplate temp = [Select Id, Name from EmailTemplate where Name = 'ErrorFileTemplate'];
        pagereference pagRef = New pagereference('/apex/ExportErrorFile');
        Blob csvBlob;
        if (Test.IsRunningTest())
        {
            csvBlob=Blob.valueOf('UNIT.TEST');
        }
        else{
            csvBlob = pagRef.getContent();
        }
            
        
        try{
            // Sends the email
            //Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            return pagRef;
        }
        catch(exception e){
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.error,'Something went wrong please contact administrator');
            ApexPages.addMessage(errorMessage);
        }    
        return null;
    }
    
     public List<List<Account>> myList {get;set;}
    
    public void exportCSVController() {
        myList = new List<List<Account>>();
        List<Account> temp = New List<Account>();
        for(Integer i = 0; i < acclist.size(); i++){
            if(temp.size() < 1000){
                Account m = acclist[i];
                temp.add(m);
            }
            else{
                myList.add(temp);
                temp = new List<Account>();
                Account m = acclist[i];
                temp.add(m);
            }
        }
        myList.add(temp);
    }
 }

Below is the test class which covered only 64% of code

@isTest
public class importDataFromCSVTest {

     static testMethod void test1(){
         list<String> tempList = new list<String>();
         String str = '';
          Id RecordTypeId = Schema.SObjectType.Masters__c.getRecordTypeInfosByName().get('Cluster').getRecordTypeId();
        Masters__c master = New Masters__c();
        master.Cluster_Name__c='RPCSCL004';
        master.Geographic_State__c='ANDHRA PRADESH';
        master.RecordTypeid=RecordTypeId;
        insert master; 
        
    //Create one more master record to pass the condition  "aa.Cluster_Code__c!=dup.Cluster_Code__c" in IF.
    Masters__c master2 = New Masters__c();
    master2.Cluster_Name__c='RPCSCL004';
    master2.Geographic_State__c='Telangana';
    master2.RecordTypeid=RecordTypeId;
    insert master2;         
        
        TL_Master__c tl1= new TL_Master__c();
        tl1.Name='APTL004';
        tl1.TL_Territory_Name__c='NORTH COASTAL';
        tl1.Cluster__c=master.id;
        insert tl1;
        
    //Create one more master record to pass the condition  "aa.TL_Code__c!=dup.TL_Code__c" in IF.        
    TL_Master__c tl2= new TL_Master__c();
    tl2.Name='APTL004';
    tl2.TL_Territory_Name__c='NORTH COASTALL';
    tl2.Cluster__c=master2.id;
    insert tl2;
        
        TSE_Master__c oldTse2 = new TSE_Master__c();
        oldTse2.Name = 'APTS033';
        oldTse2.TSE_Territory_Name__c = 'VISAKHAPATNAM - III AREA-I';
        oldTse2.TL_Code__c=tl1.id;
        insert oldTse2;
        
        Beat_TSE_Mapping__c NewBte1 = new Beat_TSE_Mapping__c();
        NewBte1.Beat_Name__c = 'BEAT 03';
        NewBte1.Name = 'ABBT1130';
        NewBte1.TSE_Code__c = oldTse2.id;
        insert NewBte1;
        
        Outlets_Groups_Primary_Customer__c newGrp = new Outlets_Groups_Primary_Customer__c();
        newGrp.Name = 'mygroup';
        newGrp.Type__c = 'Groups';
        newGrp.State_Group_PC__c = 'ANDHRA PRADESH';        
        //newGrp.Lead_TL__c = null -> so that "if(outgrps.Lead_TL__c == NULL || outgrps.Lead_TL__c == '')" will be true.
        newGrp.Lead_TL__c = null;        
        insert newGrp;
        
        Account OldAcc = new Account();        
        OldAcc.Beat_Code__c = NewBte1.Id;
        //OldAcc.Beat_Name__c = oldBte.Beat_Name__c ;
        OldAcc.TSE_Code__c = oldTse2.id;
        //OldAcc.TSE_ID__c = oldBte.TSE_ID__c;
        //OldAcc.TSE_Name__c = oldBte.TSE_Name__c;
        OldAcc.District__c = 'Test District';
        OldAcc.Goegraphy_state__c = 'ANDHRA PRADESH';
        OldAcc.Town__c = 'Test Town';
        OldAcc.Name = 'Test name';
        OldAcc.Market_Type__c = 'Corporation';
        OldAcc.MSL_Town_Tier__c= 'BTNTest';
        OldAcc.Cluster_Code__c=master.Id;
        OldAcc.TSE_Code__c=oldTse2.id;
        OldAcc.Outlet_Type__c='D';
        OldAcc.Beat_Code__c= NewBte1.Id;
        OldAcc.TL_Code__c = tl1.Id;
        OldAcc.Address__c = 'testadd';
        OldAcc.Stock_List__c = 'Tier 1';
        OldAcc.Channel_type__c = 'PrOP';
        OldAcc.Micro_channel__c = 'Prestige Bar';
        OldAcc.Perfect_Outlet__c = 'Yes';
        OldAcc.Group_Outlet__c='Yes';
        oldAcc.Group_Name1__c = newGrp.Id;
        OldAcc.Contract_type__c = 'Open';
        insert OldAcc;
         
         Account NewAcc = new Account();        
        NewAcc.Beat_Code__c = NewBte1.Id;
        //OldAcc.Beat_Name__c = oldBte.Beat_Name__c ;
        NewAcc.TSE_Code__c = oldTse2.id;
        //OldAcc.TSE_ID__c = oldBte.TSE_ID__c;
        //OldAcc.TSE_Name__c = oldBte.TSE_Name__c;
        NewAcc.District__c = 'Test District';
        NewAcc.Goegraphy_state__c = 'ANDHRA PRADESH';
        NewAcc.Town__c = 'Test Town';
        NewAcc.Name = 'Test name';
        NewAcc.Market_Type__c = 'Corporation';
        NewAcc.MSL_Town_Tier__c= 'BTNTest';
        NewAcc.Cluster_Code__c=master.Id;
        NewAcc.TSE_Code__c=oldTse2.id;
        NewAcc.Outlet_Type__c='D';
        NewAcc.Beat_Code__c= NewBte1.Id;
        NewAcc.TL_Code__c = tl1.Id;
        NewAcc.Address__c = 'testadd1';
        NewAcc.Stock_List__c = 'Tier 2';
        NewAcc.Channel_type__c = 'PrOP';
        NewAcc.Micro_channel__c = 'Prestige Bar';
        NewAcc.Perfect_Outlet__c = 'Yes';
        NewAcc.Group_Outlet__c='Yes';
        NewAcc.Group_Name1__c = newGrp.Id;
        NewAcc.Contract_type__c = 'Open';
        insert NewAcc;
         List<Account> AccLst = new List<Account>();
         AccLst.add(OldAcc);
         AccLst.add(NewAcc);
         try{
         for(Integer i=0;i<=2002;i++){
         Account a = new Account();
             a.Name= 'newAccount'+i;
            AccLst.add(a);
         }
             system.assert(true,'You can not inactivate this account ');
        }
          catch(Exception e)
        {
        Boolean expectedExceptionThrown =  e.getMessage().contains('The records to load is high in number, maximum number of records you can load is 2000') ? true : false;
            System.assertEquals(expectedExceptionThrown, false);
        }
         //AccLst = [Select Id, Name From Account];
         test.startTest();
         importDataFromCSVController ctrl = new importDataFromCSVController();
         ctrl.acclist = AccLst;
         //ctrl.listAccount = String.valueOf(acc) + '\n,'+ String.valueOf(acc1);
         ctrl.getFSEOptions();
         ctrl.importCSVFile();
         ctrl.uploadData();
         ctrl.downloadPage();
         ctrl.selectedValue = '';
         test.stopTest();
     }
     }

your help is greatly appreciated. Thanks
Following is my Before trigger:

trigger GroupClusterMap on Account (before insert, before update) {
    set<string> groupId = new set<string>();
    list<Account> listAccs= new list<Account>();
    list<Outlets_Groups_Primary_Customer__c> groupOutlets = new list<Outlets_Groups_Primary_Customer__c>();
    for(Account acc:trigger.new) {
        if(acc.Group_Name1__c!=NULL)
            groupId.add(acc.Group_Name1__c);
        }
    listAccs = [Select Id, Cluster_Code__c,Group_Name1__c,TL_Code__c from Account where Group_Name1__c IN: groupId limit 1];
    groupOutlets = [Select Id, Lead_TL__c,Name from Outlets_Groups_Primary_Customer__c where Id IN: groupId limit 1];
    if(trigger.isinsert) {
        for(Account aa:trigger.new) {
            for(Account dup:listAccs) {
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.Cluster_Code__c!=dup.Cluster_Code__c)){
                    aa.adderror('Group is mapped to a Cluster');
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.TL_Code__c!=dup.TL_Code__c)){
                    for(Outlets_Groups_Primary_Customer__c outgrps: groupOutlets){
                        if(outgrps.Lead_TL__c == NULL || outgrps.Lead_TL__c == '')
                            aa.adderror('Please do a Lead TL mapping in the Group');
                    }
                }                    
                }
                }
            }
        }
    if(trigger.isupdate) {
        for(Account aa:trigger.new){
            for(Account dup:listAccs) {                             
               // if ((aa.Group_Name1__c==dup.Group_Name1__c && aa.Group_Name1__c !=trigger.oldmap.get(aa.id).Group_Name1__c) && (aa.Cluster_Code__c!=dup.Cluster_Code__c && aa.Cluster_Code__c !=trigger.oldmap.get(aa.id).Cluster_Code__c))
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.Cluster_Code__c!=dup.Cluster_Code__c)){
                    aa.adderror('Group is mapped to a Cluster');
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.TL_Code__c!=dup.TL_Code__c)){
                    for(Outlets_Groups_Primary_Customer__c outgrps: groupOutlets){
                        if(outgrps.Lead_TL__c == NULL || outgrps.Lead_TL__c == '')
                            aa.adderror('Please do a Lead TL mapping in the Group');
                    }
                  }                    
                }
            } 
        }
    }
}
=========================================================
Following is the test class i had written for it - it only covers 57% code.

@IsTest
public class GroupClusterMapTest {   
    
    static testMethod void GroupClusterMapTest(){
        Id RecordTypeId = Schema.SObjectType.Masters__c.getRecordTypeInfosByName().get('Cluster').getRecordTypeId();
        Masters__c master = New Masters__c();
        master.Cluster_Name__c='RPCSCL004';
        master.Geographic_State__c='ANDHRA PRADESH';
        master.RecordTypeid=RecordTypeId;
        insert master;        
        
        TL_Master__c tl1= new TL_Master__c();
        tl1.Name='APTL004';
        tl1.TL_Territory_Name__c='NORTH COASTAL';
        tl1.Cluster__c=master.id;
        insert tl1;
        
        TSE_Master__c oldTse2 = new TSE_Master__c();
        oldTse2.Name = 'APTS033';
        oldTse2.TSE_Territory_Name__c = 'VISAKHAPATNAM - II AREA-I';
        oldTse2.TL_Code__c=tl1.id;
        insert oldTse2;
        
        Beat_TSE_Mapping__c NewBte1 = new Beat_TSE_Mapping__c();
        NewBte1.Beat_Name__c = 'BEAT 03';
        NewBte1.Name = 'ABBT1130';
        NewBte1.TSE_Code__c = oldTse2.id;
        insert NewBte1;
        
        Outlets_Groups_Primary_Customer__c newGrp = new Outlets_Groups_Primary_Customer__c();
        newGrp.Name = 'mygroup';
        newGrp.Type__c = 'Groups';
        newGrp.State_Group_PC__c = 'ANDHRA PRADESH';
        newGrp.Lead_TL__c = tl1.Id;
        insert newGrp;
        
        Account OldAcc = new Account();        
        OldAcc.Beat_Code__c = NewBte1.Id;
        //OldAcc.Beat_Name__c = oldBte.Beat_Name__c ;
        OldAcc.TSE_Code__c = oldTse2.id;
        //OldAcc.TSE_ID__c = oldBte.TSE_ID__c;
        //OldAcc.TSE_Name__c = oldBte.TSE_Name__c;
        OldAcc.District__c = 'Test District';
        OldAcc.Goegraphy_state__c = 'ANDHRA PRADESH';
        OldAcc.Town__c = 'Test Town';
        OldAcc.Name = 'Test name';
        OldAcc.Market_Type__c = 'Corporation';
        OldAcc.MSL_Town_Tier__c= 'BTNTest';
        OldAcc.Cluster_Code__c=master.Id;
        OldAcc.TSE_Code__c=oldTse2.id;
        OldAcc.Outlet_Type__c='D';
        OldAcc.Beat_Code__c= NewBte1.Id;
        OldAcc.TL_Code__c = tl1.Id;
        OldAcc.Address__c = 'testadd';
        OldAcc.Stock_List__c = 'Tier 1';
        OldAcc.Channel_type__c = 'PrOP';
        OldAcc.Micro_channel__c = 'Prestige Bar';
        OldAcc.Perfect_Outlet__c = 'Yes';
        OldAcc.Group_Outlet__c='No';
        oldAcc.Group_Name1__c = newGrp.Id;
        OldAcc.Contract_type__c = 'Open';
        insert OldAcc;
        
         Account NewAcc = new Account();
        NewAcc.id = OldAcc.id;
        NewAcc.Beat_Code__c = NewBte1.ID;
        //  NewAcc.Beat_Name__c = NewBte.Beat_Name__c ; 
        //NewAcc.TSE_Code__c = oldTse3.id;
        // NewAcc.TSE_ID__c = NewBte.TSE_ID__c;
        // NewAcc.TSE_Name__c = NewBte.TSE_Name__c;
        NewAcc.District__c = 'Test District1';
        NewAcc.Town__c = 'Test Town1';
        NewAcc.Name = 'Test name1';
        oldAcc.Group_Name1__c = newGrp.Id;
        update NewAcc;
    }

}

Your help is greatly appreciated...Thank you !!!
 
I want users to edit some particular field only on every friday,

For this i used following validation:

CASE( WEEKDAY(DATEVALUE(CreatedDate)),
2, ISCHANGED(Age_in_Years__c),
3, ISCHANGED(Age_in_Years__c),
4, ISCHANGED(Age_in_Years__c),
5, ISCHANGED(Age_in_Years__c),
NOT(ISCHANGED(Age_in_Years__c)))

but it is throwing an error: "Incorrect argument type for function 'CASE()'"

Can any one help me on this.

Thanks,
Ranga.V
iam unable to cover maps in test classes
 Below is the Trigger:
trigger JKT_triggerOnBeatTSEMapping on Beat_TSE_Mapping__c (before insert,before update,after update) {
    
    if (Trigger.IsAfter && Trigger.IsUpdate){
        
        Map<String, String> mapOldNewValue = New Map<String, String>();
        Map<String, String> mapOldNewValue1 = New Map<String, String>();
        Map<String, String> mapOldNewValue2 = New Map<String, String>();
        Map<String, String> mapOldNewValue3 = New Map<String, String>();
        Map<String, String> mapOldNewValue4 = New Map<String, String>();
        Map<String,String> mapOldNewValue5 = New Map<String,String>();
        List<string> lstofBeatNames = New List<string>();
        List<string> lstofBeatCodes = New List<string>();
        
        for(Beat_TSE_Mapping__c oldTseMasterRecord : Trigger.Old){
            if(Trigger.NewMap.get(oldTseMasterRecord.Id).Name != oldTseMasterRecord.Name && oldTseMasterRecord.Name != null){
                mapOldNewValue.put(oldTseMasterRecord.Name, Trigger.NewMap.get(oldTseMasterRecord.Id).Name);
            }
            
        }
        for(Beat_TSE_Mapping__c oldTseMasterRecord1 : Trigger.Old){
            if(Trigger.NewMap.get(oldTseMasterRecord1.Id).Beat_Name__c != oldTseMasterRecord1.Beat_Name__c && oldTseMasterRecord1.Beat_Name__c != null){
                mapOldNewValue1.put(oldTseMasterRecord1.Beat_Name__c, Trigger.NewMap.get(oldTseMasterRecord1.Id).Beat_Name__c);
            }
            
        }
        for(Beat_TSE_Mapping__c newTseMasterRecord2 : Trigger.new){  
            if(newTseMasterRecord2.TSE_Territory_Name__c !=trigger.oldmap.get(newTseMasterRecord2.ID).TSE_Territory_Name__c ) {
                lstofBeatNames.add(newTseMasterRecord2.Beat_Name__c);
                lstofBeatCodes.add(newTseMasterRecord2.Name);
                mapOldNewValue2.put(trigger.oldmap.get(newTseMasterRecord2.ID).TSE_Territory_Name__c , newTseMasterRecord2.TSE_Territory_Name__c); 
                mapOldNewValue3.put(trigger.oldmap.get(newTseMasterRecord2.ID).TSE_ID__c , newTseMasterRecord2.TSE_ID__c);
                mapOldNewValue4.put(trigger.oldmap.get(newTseMasterRecord2.ID).TSE_Code__c , newTseMasterRecord2.TSE_Code__c);
                
                
            }
        }  
        list<Account> listAccountToUpdate = new list<Account>();
        for(Account objAccount : [SELECT Id,Beat_Code__c FROM Account WHERE Beat_Code__c IN: mapOldNewValue.keySet()] ){
            objAccount.Beat_Code__c = mapOldNewValue.get(objAccount.Beat_Code__c);
            listAccountToUpdate.add(objAccount);
        }
        list<Account> listAccountToUpdate1 = new list<Account>();
        for(Account objAccount1 : [SELECT Id,Beat_Name__c FROM Account WHERE Beat_Name__c IN: mapOldNewValue1.keySet()] ){
            //objAccount1.Beat_Name__c = mapOldNewValue1.get(objAccount1.Beat_Name__c);
            listAccountToUpdate1.add(objAccount1);
        }
        
        List<TSE_Master__c> OldTseCodes = New List<TSE_Master__c>();
        List<TSE_Master__c> NewTseCodes = New List<TSE_Master__c>();
        OldTseCodes = [SELECT Name,TSE_Territory_Name__c FROM TSE_Master__c WHERE  Id IN : mapOldNewValue4.keySet() LIMIT 1 ];
        NewTseCodes = [SELECT Name,TSE_Territory_Name__c FROM TSE_Master__c WHERE  Id IN : mapOldNewValue4.values() LIMIT 1];
        if(!OldTseCodes.isEmpty()){
            string OldTse = string.ValueOf(OldTseCodes[0].get('Name'));
            string NewTse = string.valueOf(NewTseCodes[0].get('Name'));
            mapOldNewValue5.put(OldTse, NewTse);
        }
        
        list<Account> listAccountToUpdate2 = new list<Account>();
        for(Account objAccount2 : [SELECT Id,Name,TSE_Code__c,Beat_Name__c,Beat_Code__c,TSE_ID__c FROM Account WHERE  Beat_Name__c IN : lstofBeatNames AND Beat_Code__c IN : lstofBeatCodes and TSE_Code__c != null]){      
            //objAccount2.TSE_Name__c = mapOldNewValue2.get(objAccount2.TSE_Name__c);
            //  objAccount2.TSE_ID__c =  mapOldNewValue3.get(objAccount2.TSE_ID__c);
            if(mapOldNewValue5.containsKey(objAccount2.TSE_Code__c) && mapOldNewValue5.get(objAccount2.TSE_Code__c) != null && mapOldNewValue5.get(objAccount2.TSE_Code__c) != ''){
                objAccount2.TSE_Code__c = mapOldNewValue5.get(objAccount2.TSE_Code__c);
                listAccountToUpdate2.add(objAccount2);
            }
        }
        
        
        if(listAccountToUpdate2.size()>0){
            update listAccountToUpdate2;
        }   
        DuplicateBeatNameCheck beatObj= new DuplicateBeatNameCheck();
        beatObj.dupchecker(Trigger.new ,'Update',Trigger.oldMap);
        beatObj.BeatNameValidation(Trigger.new,Trigger.oldMap);
    }
    
    if (trigger.IsBefore && Trigger.IsInsert){
        DuplicateBeatNameCheck beatObj= new DuplicateBeatNameCheck();
        beatObj.dupchecker(Trigger.new,'Insert',Trigger.oldMap);
       //beatObj.dupbeatnamechecker(Trigger.new);
        CustomBeatCode.autogenerateBeatcode(Trigger.new);        
    }        
}
======================================================================
This is the test class i written
@istest
public with sharing class JKT_BeatCodeconttrollerTest {
    static testMethod Void BeatCodeconttrollerMethod(){
         test.StartTest();          
         Profile prfile = [select Id,name from Profile limit 1];
         USer objUser = new User();
         objUser.Username = 'TestMyName@jkt.com';
         objUser.LastName = 'testuser';
         objUser.Email = 'test@gmail.com';
         objUser.Alias = 'test1';
         objUser.CommunityNickname = 'testcommunity';
         objUser.TimeZoneSidKey = 'America/Chicago';     
         objUser.LocaleSidKey = 'en_US';
         objUser.EmailEncodingKey = 'UTF-8';
         objUser.ProfileId =prfile.Id;
         objUser.Division = 'NORTH' ;
         objUser.LanguageLocaleKey = 'en_US';
         insert objUser ;
         Id RecordTypeId = Schema.SObjectType.Masters__c.getRecordTypeInfosByName().get('Cluster').getRecordTypeId();
         Masters__c masters=new Masters__c();
         //masters.Name='A-0320';
         masters.Cluster_Name__c='ANDHRA PRADESHTest';
         masters.RecordTypeid=RecordTypeId;
         insert masters;
        
        ClusterCode__c beatCustomCode=new ClusterCode__c();
         beatCustomCode.name='ANDHRA PRADESHTest';
         beatCustomCode.GEOGRAPHIC_STATE__c='ANDHRA PRADESHTest';
         beatCustomCode.Cluster_Abbr__c='AP';
         beatCustomCode.CountValue__c=10;
         insert beatCustomCode;
         
         ClusterCodeTL__c TlCustomCode=new ClusterCodeTL__c();
         TlCustomCode.name='ANDHRA PRADESHTest';
         TlCustomCode.GEOGRAPHIC_STATE__c='ANDHRA PRADESHTest';
         TlCustomCode.Cluster_Abbr__c='AP';
         TlCustomCode.CountValue__c=10;
         insert TlCustomCode;
         
         ClusterCodeTSE__c TseCustomCode=new ClusterCodeTSE__c();
         TseCustomCode.name='ANDHRA PRADESHTest';
         TseCustomCode.GEOGRAPHIC_STATE__c='ANDHRA PRADESHTest';
         TseCustomCode.Cluster_Abbr__c='AP';
         TseCustomCode.CountValue__c=10;
         insert TseCustomCode;
        
          TL_Master__c tl= new TL_Master__c();
         tl.Name='APTL999';
         tl.TL_Territory_Name__c='CENTRAL COASTALTest';
         tl.Cluster__c=masters.id;
         insert tl;
                 
        TSE_Master__c oldTse1 = new TSE_Master__c();
        oldTse1.Name = 'APTS999';
        oldTse1.TSE_Territory_Name__c = 'AMALAPURAMTest';
        oldTse1.TL_Code__c=tl.id;
        insert oldTse1;
         
        Beat_TSE_Mapping__c NewBte = new Beat_TSE_Mapping__c();
        NewBte.Beat_Name__c = 'Beat_1234';
        NewBte.Name = 'KABT9999';
        NewBte.TSE_Code__c = oldTse1.id;
        insert NewBte;
        List <Beat_TSE_Mapping__c> BeatName = new List <Beat_TSE_Mapping__c>();
        BeatName.add(NewBte);
         Test.setCurrentPage(Page.Beatcodegeneration); 
         PageReference pRef = Page.Beatcodegeneration;
        pRef.getParameters().put('id', NewBte.TSE_Code__c);
        pRef.getParameters().put('BeatCode', oldTse1.Name);
       
        Test.setCurrentPage(pRef);

        JKT_BeatCodeconttroller BeatObj=new  JKT_BeatCodeconttroller(new ApexPages.StandardController(NewBte));
         DuplicateBeatNameCheck newBEat = new DuplicateBeatNameCheck();
       BeatObj.Save();
         BeatObj.clonerequest='1';
         BeatObj.edit=false;
        // NewBte.TSE_Code__c = oldTse1.id;
         BeatObj.Cancel();
         JKT_BeatCodeconttroller.countCalculation(1);
         JKT_BeatCodeconttroller.countCalculation(20);
         JKT_BeatCodeconttroller.countCalculation(388);     
           
         pRef.getParameters().put('clustervalue',[SELECT Name FROM TSE_Master__c  Limit 1][0].name); 
         BeatObj.autoGeneratebitCode();
         newBEat.dupbeatnamechecker(BeatName);
        Test.stopTest();
    }
}

I checked in some sites and they used "system.assertEquals",  but iam not sure how it works.
 your help is greatly appreciated.
I have a parent object and child object, in which a parent record shouldn't have duplicate child records.the following trigger is working fine but it is checking only the records in the database.

But my issue is? user is inserting two duplicate records at a time using .csv file and since my trigger is only validating the records in the database.
hence these duplicate records are also getting inserted.

How can I check duplicate in the .csv file itself ? or how to overcome this issue.

Can any one help me on this.
Trigger:
trigger BeatNameDuplicateCheck on Beat_TSE_Mapping__c (before insert, before update) {
        set<Id>TSEID= new set<ID>();
        set<string>bitname=new set<string>();
        map<string,Beat_TSE_Mapping__c> bitmap= new map<string,Beat_TSE_Mapping__c> ();
               for(Beat_TSE_Mapping__c beat:Trigger.new)
        {
            TSEID.add(beat.TSE_Code__c);
            bitname.add(beat.Beat_Name__c); 
        }
        if (!TSEID.isEmpty() ){
             List<Beat_TSE_Mapping__c> TSElist=new List<Beat_TSE_Mapping__c>();
        TSElist=[select id,Beat_Name__c,TSE_Code__c from Beat_TSE_Mapping__c where Beat_Name__c In: bitname and TSE_Code__c In: TSEID];
                       
        if (TSElist.size()>0) {
            for(Beat_TSE_Mapping__c beat:TSElist)
            {
              bitmap.put(beat.Beat_Name__c, beat);
            }     
        } 
                  }
        for (Beat_TSE_Mapping__c beat:Trigger.new)
                    {
            If (bitmap.containsKey(beat.Beat_Name__c ))
            {
                beat.Beat_Name__c.AddError('Beat Name Already Exist. Please try with another BeatName. ');
           }
        } 
}
Hi,
when Iam trying to export data in the form of excel using batch apex and sent a mail attachement.
iam able to extract it in the form of excel but issue is when iam sending an email attachement it is going as an html, after opening that html only i can able to open the excel
 attaching the mail notification for your reference
Mail Notification what i am getting
following is the code:
global class AccountBatchExport implements Database.Batchable<sObject>,Database.Stateful {
       global final String query='Select Id,Name,AccountNumber,Type,Active__c from Account where CreatedDate<Today';   
    Public String generatedCSVFile ='';
    Public string[] Lines;
    global Database.QueryLocator start(Database.BatchableContext BC){
        lines = new String[0];
      return Database.getQueryLocator(query);        
   }
   global void execute(Database.BatchableContext BC,List<Account> scope){
           for(Account a: scope){            
        string fileRow = '';
        fileRow = fileRow +'\t'+ a.Id;
            fileRow = fileRow +'\t'+ a.Name;
        fileRow = fileRow +'\t'+ a.AccountNumber;
            fileRow = fileRow +'\t'+ a.Type;
        fileRow = fileRow +'\t'+ a.Active__c;
        fileRow = fileRow.replaceFirst('\t','');
            lines.add(fileRow);
        }        
   }
   global void finish(Database.BatchableContext BC){
        generatedCSVFile = generatedCSVFile + string.join(lines, '\n');
           lines=null;
           String today = Datetime.now().format('dd-MM-yyyy');
        Blob csvBlob = blob.valueOf(generatedCSVFile);
        String csvName = 'Accounts Data as on '+today+'.xls';
           Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
        csvAttachment.setFileName(csvName);
        csvAttachment.setBody(csvBlob);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'myemail@gmail.com'};
        String subject = 'Accounts Data as on '+today+'';
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody('Accounts Data as on '+today+'');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});       
   }
}

Thanks & Regards,
Ranga
This is my Schedule class:

global class OutletExporter implements System.Schedulable {
    global void execute(SchedulableContext sc) {
        String today = Datetime.now().AddDays(-1).format('dd-MM-yyyy');
        List<Account> accList = [Select RPC__c,Cluster__c,TL_Territory_Name__c,Team_Lead_Employee_ID__c,TSE_Name__c,TSE_ID__c,TSE_Code__r.Outlet_Count__c  from Account where CreatedDate =Yesterday LIMIT 50000];
        //List<Account> latestModiaccList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where LastModifiedDate=TODAY AND CreatedDate !=TODAY];
        
        String header = 'Accounts inserted Today \r\n\n'+ 'RPC, Cluster, TLTerritory Name, TL EMP ID,TSE Territory Name,TSE EMP ID,Outlet Count \r\n';
        //String header1 ='\r\n\bAccounts Modified Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
        String generatedCSVFile = header+'';
        List<String> queryFields = new List<String>{'RPC__c','Cluster__c','TL_Territory_Name__c','Team_Lead_Employee_ID__c','TSE_Name__c','TSE_ID__c','Outlet Count'};
        String fileRow = '';
        system.debug('My Account List:'+accList);
        for(Account a: accList){
        fileRow = '';
        fileRow = fileRow +','+ a.RPC__c;
        fileRow = fileRow +','+ a.Cluster__c;
        fileRow = fileRow +','+ a.TL_Territory_Name__c;
        fileRow = fileRow +','+ a.Team_Lead_Employee_ID__c;
        fileRow = fileRow +','+ a.TSE_Name__c;
        fileRow = fileRow +','+ a.TSE_ID__c;
           fileRow = fileRow +','+ a.TSE_Code__r.Outlet_Count__c;
        fileRow = fileRow.replaceFirst(',','');
        generatedCSVFile = generatedCSVFile + fileRow + '\n';
        }
        Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
        Blob csvBlob = blob.valueOf(generatedCSVFile);
        String csvName = 'Outlets inserted and modified on '+today+'.csv';
        csvAttachment.setFileName(csvName);
        csvAttachment.setBody(csvBlob);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'ranga.vangalapudi@diageo.com','jayalakshmi.t@ivymobility.com','jennifer.b@ivymobility.com','Pradeep.Shiggavi@diageo.com','Nithyananda.Alva@diageo.com','Rajat.Yadav@diageo.com'};
        String subject = 'Outlets inserted and modified on '+today+'';
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody('Outlets inserted and modified on '+today+'');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
       }
}

This is the my test class
@isTest
public class OutletExporterTest {
     
    static testmethod void testoutlets(){        
       Id RecordTypeId = Schema.SObjectType.Masters__c.getRecordTypeInfosByName().get('Cluster').getRecordTypeId();
        Masters__c master = New Masters__c();
        master.Cluster_Name__c='RPCSCL004';
        master.RecordTypeid=RecordTypeId;
        insert master;
        TL_Master__c tl= new TL_Master__c();
        tl.Name='APTL001';
        tl.TL_Territory_Name__c='CENTRAL COASTAL';
        tl.Cluster__c=master.id;
        insert tl;
        
        TSE_Master__c oldTse1 = new TSE_Master__c();
        oldTse1.Name = 'APTS001';
        oldTse1.TSE_Territory_Name__c = 'AMALAPURAM';
        oldTse1.TL_Code__c=tl.id;
        insert oldTse1;
        
        Beat_TSE_Mapping__c NewBte = new Beat_TSE_Mapping__c();
        NewBte.Beat_Name__c = 'Beat_1';
        NewBte.Name = 'KABT0564';
        NewBte.TSE_Code__c = oldTse1.id;
        insert NewBte;
        
        
        Account acc = new Account();
        acc.name = 'test name';
        //acc.RPC__c = 'RPC-N' ;
        acc.Active__c = 'Waiting Approval';
        acc.Pincode__c = '560068';
        // acc.Beat_Name__c = 'testBeat';
        acc.Town__c = 'testTown';
        acc.Outlet_License_Name__c = 'testOl';
        acc.Address__c = 'testadd';
        acc.Stock_List__c = 'Tier 1';
        acc.Channel_type__c = 'Off';
        acc.Micro_channel__c = 'Browsable PTO';
        acc.Perfect_Outlet__c = 'Yes';
        acc.Contract_type__c = 'Open';
        //acc.TL_Territory_Name__c = 'Gurgaon 3';
        //acc.RH_Territory_Name__c = 'Haryana 3';
        //acc.Cluster__c = 'Haryana 1' ;
        acc.District__c = 'Gurgaon 3';
        acc.Goegraphy_state__c = 'Haryana';
        acc.Market_Type__c='Bond Market';
        acc.MSL_Town_Tier__c='Uncovered';
        acc.Beat_Code__c= NewBte.Id;
        acc.Cluster_Code__c=master.Id;
        acc.TSE_Code__c=oldTse1.id;
        acc.TL_Code__c=tl.Id;
        acc.Outlet_Type__c='D';
        acc.Group_Outlet__c='No';
        insert acc ; 
        Account NewAcc = new Account();
        NewAcc.id = acc.id;
        NewAcc.Beat_Code__c = NewBte.ID;
        //  NewAcc.Beat_Name__c = NewBte.Beat_Name__c ; 
        //NewAcc.TSE_Code__c = oldTse3.id;
        // NewAcc.TSE_ID__c = NewBte.TSE_ID__c;
        // NewAcc.TSE_Name__c = NewBte.TSE_Name__c;
        NewAcc.District__c = 'Test District1';
        NewAcc.Town__c = 'Test Town1';
        NewAcc.Name = 'Test name1';
        update NewAcc;
            Test.startTest();
            OutletExporter  objTest = new OutletExporter();
            String sch = '0 0 7 ? * * *';
            system.schedule('Test Schdule', sch, objTest); 
            Test.stopTest();
    }
}

Please help me on this?
Hi ,

I have written the following Rest api, WHILE testing it using postman i am getting an error: "Apex:System CPU Limit exceeded."

Can any one help me with this.

@RestResource (urlMapping='/Outletmasters/*')
//https://cs73.salesforce.com/services/apexrest/Outletmasters/
global with sharing class OutletRestClass {  
    @HttpGet
    global static list<Account> getAccounts(){
           DateTime dt= system.today();
           DateTime starttime = dt.addMinutes(+90);
        DateTime endtime = dt.addMinutes(+990);     
        //where ((LastModifiedDate >=: starttime AND LastModifiedDate <=: endtime) OR (CreatedDate >=: starttime AND CreatedDate <=: endtime)) AND Ipas_Flag__c !=true  
        String query = 'Select Id,Name, Active__c,Address__c,Beat_Code__r.Name, Beat_Name__c,Channel_type__c,Cluster__c,Cluster_Code__r.Cluster_Code__c,Contract_type__c, Country_liquor_sold__c,District__c,Geo_Location__latitude__s,Geo_Location__longitude__s,Goegraphy_state__c,Group_Outlet__c,Group_Name__c,Group_ID_1_del__c,Location_Type__c,Lower_Prestige__c,Luxury_Core__c,Market_Type__c,Micro_channel__c,Mid_Prestige__c,MSL_Town_Tier__c,O_L_Id__c,Outlet_Contact_Person__c,Outlet_License_Code__c,Outlet_License_Name__c,Outlet_Mobile__c,Overall_Segmentation__c,Perfect_Outlet__c,Pincode__c,Premium_Core__c,Primary_Occasion__c,Primary_Customer_Name__r.Name,Primary_Customer_ID_del__c,RPC__c,RPC_Code__c,Secondary_Occasion__c,TL_Code__r.Name,Town__c,Town_code__c,TSE_Code__r.Name,TL_Territory_Name__c,TSE_Name__c,USL_Outlet_ID__c,Upper_Prestige__c,Visit_Frequency__c FROM Account where Ipas_Flag__c !=true LIMIT 1700';
        RestRequest req = RestContext.request; 
        RestResponse res = RestContext.response; 
        list<Account> acc_toUpdate = new list<Account>();
        list<Account> acc_tosend = new list<Account>();
           list<Account> accList = Database.query(query);         
        for(Account a: accList){
            a.Ipas_Flag__c = true;
            acc_toUpdate.add(a);
        } 
        update acc_toUpdate;
        for(Account ac: accList){
            if(ac.Name == NULL || ac.Name == '') ac.Name ='null';
            if(ac.Active__c == NULL || ac.Active__c == '') ac.Active__c ='null';
            if(ac.Address__c == NULL || ac.Address__c == '') ac.Address__c ='null';
            if(ac.Beat_Code__r.Name == NULL || ac.Beat_Code__r.Name == '') ac.Beat_Code__r.Name ='null';
            if(ac.Channel_type__c == NULL || ac.Channel_type__c == '') ac.Channel_type__c ='null';
            if(ac.Cluster_Code__r.Cluster_Code__c == NULL || ac.Cluster_Code__r.Cluster_Code__c == '') ac.Cluster_Code__r.Cluster_Code__c ='null';
            if(ac.Contract_type__c == NULL || ac.Contract_type__c == '') ac.Contract_type__c ='null';
            if(ac.Country_liquor_sold__c == NULL || ac.Country_liquor_sold__c == '') ac.Country_liquor_sold__c ='null';
            if(ac.District__c == NULL || ac.District__c == '') ac.District__c ='null';
            if(ac.Geo_Location__Latitude__s == NULL || ac.Geo_Location__Longitude__s == NULL ){
                ac.Geo_Location__Latitude__s = null;
                ac.Geo_Location__Longitude__s = null;
            }
            if(ac.Goegraphy_state__c == NULL || ac.Goegraphy_state__c == '') ac.Goegraphy_state__c ='null';
            if(ac.Group_Outlet__c == NULL || ac.Group_Outlet__c == '') ac.Group_Outlet__c ='null';
            if(ac.Group_Name__c == NULL || ac.Group_Name__c == '') ac.Group_Name__c ='null';
            //if(ac.Group_Lead_TL__c == NULL || ac.Group_Lead_TL__c == '') ac.Group_Lead_TL__c ='null';
            if(ac.Location_Type__c == NULL || ac.Location_Type__c == '') ac.Location_Type__c ='null';
            if(ac.Lower_Prestige__c == NULL || ac.Lower_Prestige__c == '') ac.Lower_Prestige__c ='null';
            if(ac.Luxury_Core__c == NULL || ac.Luxury_Core__c == '') ac.Luxury_Core__c ='null';
            if(ac.Market_Type__c == NULL || ac.Market_Type__c == '') ac.Market_Type__c ='null';
            if(ac.Micro_channel__c == NULL || ac.Micro_channel__c == '') ac.Micro_channel__c ='null';
            if(ac.Mid_Prestige__c == NULL || ac.Mid_Prestige__c == '') ac.Mid_Prestige__c ='null';
            if(ac.MSL_Town_Tier__c == NULL || ac.MSL_Town_Tier__c == '') ac.MSL_Town_Tier__c ='null';
            if(ac.O_L_Id__c == NULL || ac.O_L_Id__c == '') ac.O_L_Id__c ='null';
            if(ac.Outlet_Contact_Person__c == NULL || ac.Outlet_Contact_Person__c == '') ac.Outlet_Contact_Person__c ='null';
            if(ac.Outlet_License_Code__c == NULL || ac.Outlet_License_Code__c == '') ac.Outlet_License_Code__c ='null';
            if(ac.Outlet_License_Name__c == NULL || ac.Outlet_License_Name__c == '') ac.Outlet_License_Name__c ='null';
            if(ac.Outlet_Mobile__c == NULL || ac.Outlet_Mobile__c == '') ac.Outlet_Mobile__c ='null';
            if(ac.Overall_Segmentation__c == NULL || ac.Overall_Segmentation__c == '') ac.Overall_Segmentation__c ='null';
            if(ac.Perfect_Outlet__c == NULL || ac.Perfect_Outlet__c == '') ac.Perfect_Outlet__c ='null';
            if(ac.Pincode__c == NULL || ac.Pincode__c == '') ac.Pincode__c ='null';
            if(ac.Premium_Core__c == NULL || ac.Premium_Core__c == '') ac.Premium_Core__c ='null';
            if(ac.Primary_Occasion__c == NULL || ac.Primary_Occasion__c == '') ac.Primary_Occasion__c ='null';
            if(ac.Primary_Customer_Name__c == NULL || ac.Primary_Customer_Name__c == '') ac.Primary_Customer_Name__c =null;
            if(ac.Secondary_Occasion__c == NULL || ac.Secondary_Occasion__c == '') ac.Secondary_Occasion__c ='null';
            if(ac.TL_Code__r.Name == NULL || ac.TL_Code__r.Name == '') ac.TL_Code__r.Name ='null';  
            if(ac.Town__c == NULL || ac.Town__c == '') ac.Town__c ='null';  
            if(ac.Town_code__c == NULL || ac.Town_code__c == '') ac.Town_code__c ='null';  
            if(ac.TSE_Code__r.Name == NULL || ac.TSE_Code__r.Name == '') ac.TSE_Code__r.Name ='null';  
            if(ac.USL_Outlet_ID__c == NULL || ac.USL_Outlet_ID__c == '') ac.USL_Outlet_ID__c ='null';  
             if(ac.Upper_Prestige__c == NULL || ac.Upper_Prestige__c == '') {ac.Upper_Prestige__c ='null';}            
                   acc_tosend.add(ac);  
            }
        return acc_tosend;
        }       
    }
===============================================
i know this may happened becaused i used many if conditions in a for loop. please help me to reduce this.

Regards,
Ranga.V
Following is my Before trigger:

trigger GroupClusterMap on Account (before insert, before update) {
    set<string> groupId = new set<string>();
    list<Account> listAccs= new list<Account>();
    list<Outlets_Groups_Primary_Customer__c> groupOutlets = new list<Outlets_Groups_Primary_Customer__c>();
    for(Account acc:trigger.new) {
        if(acc.Group_Name1__c!=NULL)
            groupId.add(acc.Group_Name1__c);
        }
    listAccs = [Select Id, Cluster_Code__c,Group_Name1__c,TL_Code__c from Account where Group_Name1__c IN: groupId limit 1];
    groupOutlets = [Select Id, Lead_TL__c,Name from Outlets_Groups_Primary_Customer__c where Id IN: groupId limit 1];
    if(trigger.isinsert) {
        for(Account aa:trigger.new) {
            for(Account dup:listAccs) {
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.Cluster_Code__c!=dup.Cluster_Code__c)){
                    aa.adderror('Group is mapped to a Cluster');
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.TL_Code__c!=dup.TL_Code__c)){
                    for(Outlets_Groups_Primary_Customer__c outgrps: groupOutlets){
                        if(outgrps.Lead_TL__c == NULL || outgrps.Lead_TL__c == '')
                            aa.adderror('Please do a Lead TL mapping in the Group');
                    }
                }                    
                }
                }
            }
        }
    if(trigger.isupdate) {
        for(Account aa:trigger.new){
            for(Account dup:listAccs) {                             
               // if ((aa.Group_Name1__c==dup.Group_Name1__c && aa.Group_Name1__c !=trigger.oldmap.get(aa.id).Group_Name1__c) && (aa.Cluster_Code__c!=dup.Cluster_Code__c && aa.Cluster_Code__c !=trigger.oldmap.get(aa.id).Cluster_Code__c))
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.Cluster_Code__c!=dup.Cluster_Code__c)){
                    aa.adderror('Group is mapped to a Cluster');
                if (aa.Group_Name1__c!=NULL && (aa.Group_Name1__c==dup.Group_Name1__c && aa.TL_Code__c!=dup.TL_Code__c)){
                    for(Outlets_Groups_Primary_Customer__c outgrps: groupOutlets){
                        if(outgrps.Lead_TL__c == NULL || outgrps.Lead_TL__c == '')
                            aa.adderror('Please do a Lead TL mapping in the Group');
                    }
                  }                    
                }
            } 
        }
    }
}
=========================================================
Following is the test class i had written for it - it only covers 57% code.

@IsTest
public class GroupClusterMapTest {   
    
    static testMethod void GroupClusterMapTest(){
        Id RecordTypeId = Schema.SObjectType.Masters__c.getRecordTypeInfosByName().get('Cluster').getRecordTypeId();
        Masters__c master = New Masters__c();
        master.Cluster_Name__c='RPCSCL004';
        master.Geographic_State__c='ANDHRA PRADESH';
        master.RecordTypeid=RecordTypeId;
        insert master;        
        
        TL_Master__c tl1= new TL_Master__c();
        tl1.Name='APTL004';
        tl1.TL_Territory_Name__c='NORTH COASTAL';
        tl1.Cluster__c=master.id;
        insert tl1;
        
        TSE_Master__c oldTse2 = new TSE_Master__c();
        oldTse2.Name = 'APTS033';
        oldTse2.TSE_Territory_Name__c = 'VISAKHAPATNAM - II AREA-I';
        oldTse2.TL_Code__c=tl1.id;
        insert oldTse2;
        
        Beat_TSE_Mapping__c NewBte1 = new Beat_TSE_Mapping__c();
        NewBte1.Beat_Name__c = 'BEAT 03';
        NewBte1.Name = 'ABBT1130';
        NewBte1.TSE_Code__c = oldTse2.id;
        insert NewBte1;
        
        Outlets_Groups_Primary_Customer__c newGrp = new Outlets_Groups_Primary_Customer__c();
        newGrp.Name = 'mygroup';
        newGrp.Type__c = 'Groups';
        newGrp.State_Group_PC__c = 'ANDHRA PRADESH';
        newGrp.Lead_TL__c = tl1.Id;
        insert newGrp;
        
        Account OldAcc = new Account();        
        OldAcc.Beat_Code__c = NewBte1.Id;
        //OldAcc.Beat_Name__c = oldBte.Beat_Name__c ;
        OldAcc.TSE_Code__c = oldTse2.id;
        //OldAcc.TSE_ID__c = oldBte.TSE_ID__c;
        //OldAcc.TSE_Name__c = oldBte.TSE_Name__c;
        OldAcc.District__c = 'Test District';
        OldAcc.Goegraphy_state__c = 'ANDHRA PRADESH';
        OldAcc.Town__c = 'Test Town';
        OldAcc.Name = 'Test name';
        OldAcc.Market_Type__c = 'Corporation';
        OldAcc.MSL_Town_Tier__c= 'BTNTest';
        OldAcc.Cluster_Code__c=master.Id;
        OldAcc.TSE_Code__c=oldTse2.id;
        OldAcc.Outlet_Type__c='D';
        OldAcc.Beat_Code__c= NewBte1.Id;
        OldAcc.TL_Code__c = tl1.Id;
        OldAcc.Address__c = 'testadd';
        OldAcc.Stock_List__c = 'Tier 1';
        OldAcc.Channel_type__c = 'PrOP';
        OldAcc.Micro_channel__c = 'Prestige Bar';
        OldAcc.Perfect_Outlet__c = 'Yes';
        OldAcc.Group_Outlet__c='No';
        oldAcc.Group_Name1__c = newGrp.Id;
        OldAcc.Contract_type__c = 'Open';
        insert OldAcc;
        
         Account NewAcc = new Account();
        NewAcc.id = OldAcc.id;
        NewAcc.Beat_Code__c = NewBte1.ID;
        //  NewAcc.Beat_Name__c = NewBte.Beat_Name__c ; 
        //NewAcc.TSE_Code__c = oldTse3.id;
        // NewAcc.TSE_ID__c = NewBte.TSE_ID__c;
        // NewAcc.TSE_Name__c = NewBte.TSE_Name__c;
        NewAcc.District__c = 'Test District1';
        NewAcc.Town__c = 'Test Town1';
        NewAcc.Name = 'Test name1';
        oldAcc.Group_Name1__c = newGrp.Id;
        update NewAcc;
    }

}

Your help is greatly appreciated...Thank you !!!
 
This is my Schedule class:

global class OutletExporter implements System.Schedulable {
    global void execute(SchedulableContext sc) {
        String today = Datetime.now().AddDays(-1).format('dd-MM-yyyy');
        List<Account> accList = [Select RPC__c,Cluster__c,TL_Territory_Name__c,Team_Lead_Employee_ID__c,TSE_Name__c,TSE_ID__c,TSE_Code__r.Outlet_Count__c  from Account where CreatedDate =Yesterday LIMIT 50000];
        //List<Account> latestModiaccList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where LastModifiedDate=TODAY AND CreatedDate !=TODAY];
        
        String header = 'Accounts inserted Today \r\n\n'+ 'RPC, Cluster, TLTerritory Name, TL EMP ID,TSE Territory Name,TSE EMP ID,Outlet Count \r\n';
        //String header1 ='\r\n\bAccounts Modified Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
        String generatedCSVFile = header+'';
        List<String> queryFields = new List<String>{'RPC__c','Cluster__c','TL_Territory_Name__c','Team_Lead_Employee_ID__c','TSE_Name__c','TSE_ID__c','Outlet Count'};
        String fileRow = '';
        system.debug('My Account List:'+accList);
        for(Account a: accList){
        fileRow = '';
        fileRow = fileRow +','+ a.RPC__c;
        fileRow = fileRow +','+ a.Cluster__c;
        fileRow = fileRow +','+ a.TL_Territory_Name__c;
        fileRow = fileRow +','+ a.Team_Lead_Employee_ID__c;
        fileRow = fileRow +','+ a.TSE_Name__c;
        fileRow = fileRow +','+ a.TSE_ID__c;
           fileRow = fileRow +','+ a.TSE_Code__r.Outlet_Count__c;
        fileRow = fileRow.replaceFirst(',','');
        generatedCSVFile = generatedCSVFile + fileRow + '\n';
        }
        Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
        Blob csvBlob = blob.valueOf(generatedCSVFile);
        String csvName = 'Outlets inserted and modified on '+today+'.csv';
        csvAttachment.setFileName(csvName);
        csvAttachment.setBody(csvBlob);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'ranga.vangalapudi@diageo.com','jayalakshmi.t@ivymobility.com','jennifer.b@ivymobility.com','Pradeep.Shiggavi@diageo.com','Nithyananda.Alva@diageo.com','Rajat.Yadav@diageo.com'};
        String subject = 'Outlets inserted and modified on '+today+'';
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody('Outlets inserted and modified on '+today+'');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
       }
}

This is the my test class
@isTest
public class OutletExporterTest {
     
    static testmethod void testoutlets(){        
       Id RecordTypeId = Schema.SObjectType.Masters__c.getRecordTypeInfosByName().get('Cluster').getRecordTypeId();
        Masters__c master = New Masters__c();
        master.Cluster_Name__c='RPCSCL004';
        master.RecordTypeid=RecordTypeId;
        insert master;
        TL_Master__c tl= new TL_Master__c();
        tl.Name='APTL001';
        tl.TL_Territory_Name__c='CENTRAL COASTAL';
        tl.Cluster__c=master.id;
        insert tl;
        
        TSE_Master__c oldTse1 = new TSE_Master__c();
        oldTse1.Name = 'APTS001';
        oldTse1.TSE_Territory_Name__c = 'AMALAPURAM';
        oldTse1.TL_Code__c=tl.id;
        insert oldTse1;
        
        Beat_TSE_Mapping__c NewBte = new Beat_TSE_Mapping__c();
        NewBte.Beat_Name__c = 'Beat_1';
        NewBte.Name = 'KABT0564';
        NewBte.TSE_Code__c = oldTse1.id;
        insert NewBte;
        
        
        Account acc = new Account();
        acc.name = 'test name';
        //acc.RPC__c = 'RPC-N' ;
        acc.Active__c = 'Waiting Approval';
        acc.Pincode__c = '560068';
        // acc.Beat_Name__c = 'testBeat';
        acc.Town__c = 'testTown';
        acc.Outlet_License_Name__c = 'testOl';
        acc.Address__c = 'testadd';
        acc.Stock_List__c = 'Tier 1';
        acc.Channel_type__c = 'Off';
        acc.Micro_channel__c = 'Browsable PTO';
        acc.Perfect_Outlet__c = 'Yes';
        acc.Contract_type__c = 'Open';
        //acc.TL_Territory_Name__c = 'Gurgaon 3';
        //acc.RH_Territory_Name__c = 'Haryana 3';
        //acc.Cluster__c = 'Haryana 1' ;
        acc.District__c = 'Gurgaon 3';
        acc.Goegraphy_state__c = 'Haryana';
        acc.Market_Type__c='Bond Market';
        acc.MSL_Town_Tier__c='Uncovered';
        acc.Beat_Code__c= NewBte.Id;
        acc.Cluster_Code__c=master.Id;
        acc.TSE_Code__c=oldTse1.id;
        acc.TL_Code__c=tl.Id;
        acc.Outlet_Type__c='D';
        acc.Group_Outlet__c='No';
        insert acc ; 
        Account NewAcc = new Account();
        NewAcc.id = acc.id;
        NewAcc.Beat_Code__c = NewBte.ID;
        //  NewAcc.Beat_Name__c = NewBte.Beat_Name__c ; 
        //NewAcc.TSE_Code__c = oldTse3.id;
        // NewAcc.TSE_ID__c = NewBte.TSE_ID__c;
        // NewAcc.TSE_Name__c = NewBte.TSE_Name__c;
        NewAcc.District__c = 'Test District1';
        NewAcc.Town__c = 'Test Town1';
        NewAcc.Name = 'Test name1';
        update NewAcc;
            Test.startTest();
            OutletExporter  objTest = new OutletExporter();
            String sch = '0 0 7 ? * * *';
            system.schedule('Test Schdule', sch, objTest); 
            Test.stopTest();
    }
}

Please help me on this?
Hello Everyone,

I want to know the possible ways through which we can fetch more than 50k/1million records through apex class in salesforce.

Please respond.

Thanks in advance.

Rregards
Aakanksha Singh