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
Savi3Savi3 

Batch Apex

Hi ,

 

   The campaign object has  two custom fields Lifetime_Value__c(Annual value) and Direct_Campaign_Sales__c.The issue facing is that there are a few campaigns that the Direct and Annual Value is not adding up and a few others that it looks incorrect.

And getting error like this:- "First error:Update failed first exception on row 200 with id 70180000000QFuAAo;first error: UNABLE_TO_LOCK_ROW,unable to obtain exclusive access to this record:[] " for campaignstaticsupdater() batch class and getting same error  for another row in campaignConvertedAnd Prospectsupdater() batch class (row0 with id 70180000000PYVGAA4 )

___________________________________________________________________________________________________

 

global class CampaignStatisticsUpdater implements Database.Batchable<sObject> {
  private List<Campaign> campaigns;
  public boolean testrun=false;
  public Id testcampaignid;
  
  private List<Campaign> loadCampaigns() {
    return [SELECT Id, StartDate, EndDate, Direct_Campaign_Sales__c, Lifetime_Value__c FROM Campaign order  by CreatedDate DESC];
  }
  
  global Database.QueryLocator start(Database.BatchableContext bc) {
    List<Campaign> campaigns = loadCampaigns();
    for(Campaign camp : campaigns) {
      camp.Direct_Campaign_Sales__c = 0;
      camp.Lifetime_Value__c = 0;
    }
    update campaigns;
    
    String query = 'SELECT Id, CampaignId, ContactId, Contact.AccountId, Account_Type_Stamp_Hidden__c FROM CampaignMember WHERE ContactId != null AND Contact.AccountId != null';
    if(testrun)
      return Database.getQueryLocator([SELECT Id, CampaignId, ContactId, Contact.AccountId, Account_Type_Stamp_Hidden__c FROM CampaignMember WHERE ContactId != null AND Contact.AccountId != null and CampaignId=:testcampaignid order by LastModifiedDate  ASC limit 100]);
    System.debug(System.LoggingLevel.INFO, query);
    Database.QueryLocator ql = Database.getQueryLocator(query);
    return ql;
  }
  
  global void execute(Database.BatchableContext bc, List<sObject> objs) {    
    Map<Id, Campaign> campMap = new Map<Id, Campaign>(loadCampaigns());
    List<CampaignMember> cms = (List<CampaignMember>) objs;
    
    // build the list of account ids
    Set<Id> acctIds = new Set<Id>();  
    for(CampaignMember cm : cms) {
      acctIds.add(cm.Contact.AccountId);
    }
    
    // load the campaign opportunities and map them by account
    Map<Id, List<Opportunity>> acctOppMap = new Map<Id, List<Opportunity>>();
    for(Opportunity o : [SELECT Id, Amount, CloseDate, StageName, AccountId, IsClosed, IsWon FROM Opportunity WHERE AccountId IN :acctIds AND Amount != null AND IsClosed = true AND IsWon = true]) {
      List<Opportunity> opps = acctOppMap.containsKey(o.AccountId) ? acctOppMap.get(o.AccountId) : new List<Opportunity>();
      opps.add(o);
      acctOppMap.put(o.AccountId, opps);
    }
    
    // update the statistics
    for(CampaignMember cm : cms) {
      Campaign camp = campMap.get(cm.CampaignId);
      if(acctOppMap.containsKey(cm.Contact.AccountId)) {
        for(Opportunity opp : acctOppMap.get(cm.Contact.AccountId)) {
          // update the statistics dealing with opportunities closed after the start of the campaign
          if(camp.StartDate != null &&camp.EndDate != null && opp.CloseDate != null && camp.StartDate <= opp.CloseDate) {
            if(opp.CloseDate <= camp.EndDate) {
              camp.Direct_Campaign_Sales__c += opp.Amount;
            }
            
            if(opp.CloseDate <= camp.EndDate.addYears(1)) {
              camp.Lifetime_Value__c += opp.Amount;
            }
          }
        }
      }
    }
    
    update campMap.values();
  }
  
  global void finish(Database.BatchableContext bc) {}
}_______________________________________________________________________________________________

global class CampaignConvertedAndProspectsUpdater implements Database.Batchable<sObject> {
  private List<Campaign> campaigns;
  
  private List<Campaign> loadCampaigns() {
    return [SELECT Id, StartDate, EndDate, Converted_Leads_and_Prospects__c FROM Campaign];
  }
  
  private List<Campaign> loadCampaigns(Set<Id> campIds) {
    return [SELECT Id, StartDate, EndDate, Converted_Leads_and_Prospects__c FROM Campaign WHERE Id IN :campIds];
  }
  
  global Database.QueryLocator start(Database.BatchableContext bc) {
    List<Campaign> campaigns = loadCampaigns();
    for(Campaign camp : campaigns) {
      camp.Converted_Leads_and_Prospects__c = 0;
    }
    update campaigns;
    
    String query = 'SELECT Id, Amount, Account_Created_Same_Day__c, AccountId, Account.IsPersonAccount, Account.PersonContactId, Conversion_Day_Campaign__c FROM Opportunity WHERE Account.IsPersonAccount = true AND Account_Created_Same_Day__c = 1 AND Conversion_Day_Campaign__c != NULL';
    System.debug(System.LoggingLevel.INFO, query);
    Database.QueryLocator ql = Database.getQueryLocator(query);
    return ql;
  }
  
  global void execute(Database.BatchableContext bc, List<sObject> objs) {
    List<Opportunity> opps = (List<Opportunity>) objs;
    Set<Id> campIds = new Set<Id>();
    for(Opportunity opp : opps) {
      if(opp.AccountId != null && opp.Account.IsPersonAccount && opp.Account_Created_Same_Day__c == 1 && opp.Conversion_Day_Campaign__c != null) {
        campIds.add(opp.Conversion_Day_Campaign__c);
      }
    }
    
    Map<Id, Campaign> campMap = new Map<Id, Campaign>(loadCampaigns(campIds));
    
    // iterate over all opps and update the conversion day campaing stat value
    for(Opportunity opp : opps) {
      if(opp.AccountId != null && opp.Account.IsPersonAccount && opp.Account_Created_Same_Day__c == 1 && opp.Conversion_Day_Campaign__c != null && campMap.containsKey(opp.Conversion_Day_Campaign__c)) {
        Campaign camp = campMap.get(opp.Conversion_Day_Campaign__c);
        Double curAmt = camp.Converted_Leads_and_Prospects__c == null ? 0 : camp.Converted_Leads_and_Prospects__c;
        camp.Converted_Leads_and_Prospects__c = curAmt + (opp.Amount == null ? 0 : opp.Amount);
      }
    }
    update campMap.values();
  }
  
  global void finish(Database.BatchableContext bc) {}
}

}________________________________________________________________________________________________

 

 

Any ideas would be of great help.....

 

Thank you.

sav3.