• Ashley Cobb 25
  • NEWBIE
  • 25 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 5
    Replies
Hello,

The company that I work for has custom code to convert a lead to a contact/account.  For some reason it only fires about half the time.  This is extrememly important because our users do not have access to leads so when they are not converted they are not followed up with. I would really appreciate it if anyone can look and see if they find any errors. I have been looking through it for days and cannot seem to figure out why it only fires half the time and doesn't send me any error messages.  This is a little bit beyond my ability as I have never worked with @future methods or scheduling things via the UI.

Trigger:
trigger LeadTrigger on Lead( after update, after insert )
{
    // Assign values of trigger new list to helper class variable
    LeadTriggerHelper.newLeadList = trigger.new;
    // Assign values of trigger old list to helper class variable
    LeadTriggerHelper.oldLeadList = trigger.old;
    // Assign values of trigger new map to helper class variable
    LeadTriggerHelper.newLeadMap = trigger.newMap;
    // Assign values of trigger old map to helper class variable
    LeadTriggerHelper.oldLeadMap = trigger.oldMap;
    
    // Check if runTrigger
    if( LeadTriggerHelper.runTrigger )
    {
        // Check if after
        if( trigger.isAfter )
        {
            // Check if Update
            if( trigger.isUpdate )
            {
                // Call method to convert lead
                LeadTriggerHelper.leadConversionAfterInsert();
            }
            
            if( trigger.isInsert )
            {
                LeadTriggerHelper.scheduleLeadConversion();
            }
        }
    }
}
Classes:
public with sharing class LeadTriggerHelper
{
    // To check whether to call boolean or not
    public static Boolean runTrigger = true;
    // List to store Lead of trigger.new
    public static List<Lead> newLeadList = new List<Lead>();
    // List to store Lead of trigger.old
    public static List<Lead> oldLeadList = new List<Lead>();
    // Map to store Lead of trigger.newMap
    public static Map<Id, Lead> newLeadMap = new Map<Id, Lead>();
    // Map to store Lead of trigger.oldMap
    public static Map<Id, Lead> oldLeadMap = new Map<Id, Lead>();
    
    private static String convertStatus;
    private static Map<String, User> nameToUserMap = new Map<String, User>();
    
    /**
     * Name: leadConversionAfterInsert
     * @param:
     * @return:
     * Desc: Method to convert lead when created
    **/
    public static void leadConversionAfterInsert()
    {
        //try
        //{
            Set<String> uniqueEmails = new Set<String>();
            Set<String> uniqueWebsites = new Set<String>();
            List<Lead> uniqueLeads = new List<Lead>();
            List<Lead> existingLeads = new List<Lead>();
            List<Lead> newAccountExistingEmail = new List<Lead>();
            Set<String> userNames = new Set<String>();
            
            for( Lead lead : newLeadList )
            {
                if( lead.Convert__c && !oldLeadMap.get( lead.Id ).Convert__c && !lead.Isconverted )
                {
                    if( lead.Website != null && lead.Website != '' )
                    {
                        if( uniqueWebsites.contains( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
                        {
                            if( lead.Email != null && lead.Email != '' )
                            {
                                if( uniqueEmails.contains( lead.Email ))
                                {
                                    newAccountExistingEmail.add( lead );
                                }
                                else
                                {
                                    uniqueEmails.add( lead.Email );
                                    existingLeads.add( lead );
                                }
                            }
                            else
                            {
                                existingLeads.add( lead );
                            }
                        }
                        else
                        {
                            uniqueWebsites.add( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                            uniqueLeads.add( lead );
                            
                            if( lead.Email != null && lead.Email != '' )
                            {
                                uniqueEmails.add( lead.Email );
                            }
                        }
                    }
                    else if( lead.Email != null && lead.Email != '' )
                    {
                        if( uniqueEmails.contains( lead.Email ))
                        {
                            existingLeads.add( lead );
                        }
                        else
                        {
                            uniqueEmails.add( lead.Email );
                            uniqueLeads.add( lead );
                        }
                    }
                    else
                    {
                        uniqueLeads.add( lead );
                    }
                    
                    if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' )
                        userNames.add( lead.MASTER_SDR_Owner__c );
                }
            }
            
            LeadStatus convertStatuses = [ Select MasterLabel from LeadStatus where IsConverted = true limit 1 ];
            convertStatus = convertStatuses.MasterLabel;
            
            for( User u : [ Select Id, Name from User where Name IN :userNames ])
            {
                nameToUserMap.put( u.Name, u );
            }
            
            convertLeads( uniqueLeads );
            convertLeads( existingLeads );
            convertLeads( newAccountExistingEmail );
        /*}
        catch( Exception e )
        {
            system.debug( 'Error********************' + e.getMessage() + ':::::::::::::::' + e.getLineNumber() );
        }*/
    }
    
    public static void convertLeads( List<Lead> leadsToBeConverted )
    {
        Set<String> emailAddressSet = new Set<String>();
        Set<Id> accountIds = new Set<Id>();
        Set<String> webSiteSet = new Set<String>();
        
        for( Lead lead : leadsToBeConverted )
        {
            if( lead.bizible2__Account__c != null )
                accountIds.add( lead.bizible2__Account__c );
            else if( lead.Website != null && lead.Website != '' )
                webSiteSet.add( '%' + lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                
            if( lead.Email != null && lead.Email != '' )
                emailAddressSet.add( lead.Email );
        }
        
        Map<Id, Account> accountMap = new Map<Id, Account>([ Select Id, Website, Phone, Description, Intel_City__c,
                                                                Intel_Country__c, Intel_State__c, Territory_New__c,
                                                                ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                                                    Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                                                    Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                                                    LeadSource from Contacts where Email IN :emailAddressSet )
                                                                from Account where Id IN :accountIds ]);
        
        Map<String, List<Account>> websiteToAccountMap = new Map<String, List<Account>>();
        for( Account acc : [ Select Id, Website, Phone, Description, Intel_City__c, Intel_Country__c, Intel_State__c,
                                Territory_New__c, ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                LeadSource from Contacts where Email IN :emailAddressSet ) from Account where Website like :webSiteSet ])
        {
            List<Account> accs = new List<Account>();
            if( websiteToAccountMap.containsKey( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                accs = websiteToAccountMap.get( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
            }
            
            accs.add( acc );
            websiteToAccountMap.put( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ), accs );
        }
        
        /*Map<String, Contact> emailAddressToContactMap = new Map<String, Contact>();
        for( Contact con : [ Select Id, Email, Phone, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                            Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                            Survey_Using_an_Agency__c, MASTER_SDR_Contact_Attempts__c, MASTER_SDR_Follow_Up_Date__c, MASTER_SDR_Notes__c,
                            MASTER_SDR_Owner__c, MASTER_SDR_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                            LeadSource from Contact where Email IN :emailAddressSet ])
        {
            emailAddressToContactMap.put( con.Email, con );
        }*/
        
        List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
        Map<Id, Account> accountsToBeUpdated = new Map<Id, Account>();
        Map<Id, Contact> contactsToBeUpdated = new Map<Id, Contact>();
        
        for( Lead lead : leadsToBeConverted )
        {
            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setDoNotCreateOpportunity( true );
            lc.setLeadId( lead.Id );
            lc.setConvertedStatus( convertStatus );
            
            Account acc;
            Contact con;
            if( lead.bizible2__Account__c != null && accountMap.containsKey( lead.bizible2__Account__c ))
            {
                acc = accountMap.get( lead.bizible2__Account__c );
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Contact c : acc.Contacts )
                    {
                        if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                        {
                            con = c;
                            break;
                        }
                    }
                }
            }
            else if( lead.Website != null && lead.WebSite != ''
                        && websiteToAccountMap.containsKey( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                List<Account> accounts = websiteToAccountMap.get( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Account a : accounts )
                    {
                        for( Contact c : a.Contacts )
                        {
                            if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                            {
                                acc = a;
                                con = c;
                                break;
                            }
                        }
                        
                        if( acc != null )
                            break;
                    }
                    
                    if( acc == null )
                        acc = accounts[0];
                }
            }
            
            if( acc != null )
            {  
                lc.setAccountId( acc.Id );
                Boolean flag = false;
                
                if( acc.Phone == null || acc.Phone == '' )
                {
                    acc.Phone = lead.Phone;
                    flag = true;
                }
                
                if( acc.Description == null || acc.Description == '' )
                {
                    acc.Description = lead.Description;
                    flag = true;
                }
                
                if( acc.Intel_City__c == null || acc.Intel_City__c == '' )
                {
                    acc.Intel_City__c = lead.Intel_City__c;
                    flag = true;
                }
                
                if( acc.Intel_Country__c == null || acc.Intel_Country__c == '' )
                {
                    acc.Intel_Country__c = lead.Intel_Country__c;
                    flag = true;
                }
                
                if( acc.Territory_New__c == null || acc.Territory_New__c == '' )
                {
                    acc.Territory_New__c = lead.Territory_New__c;
                    flag = true;
                }
                
                if( acc.Intel_State__c == null || acc.Intel_State__c == '' )
                {
                    acc.Intel_State__c = lead.Intel_State__c;
                    flag = true;
                }
                
                if( flag )
                    accountsToBeUpdated.put( acc.Id, acc );
            }
            
            if( con != null )
            {
                lc.setContactId( con.Id );
                Boolean flag = false;
                //Contact con = emailAddressToContactMap.get( lead.Email );
                
                if( con.Phone == null || con.Phone == '' )
                {
                    con.Phone = lead.Phone;
                    flag = true;
                }
                
                if( con.Title == null || con.Title == '' )
                {
                    con.Title = lead.Title;
                    flag = true;
                }
                
                if( con.Description == null || con.Description == '' )
                {
                    con.Description = lead.Description;
                    flag = true;
                }
                
                if( con.LeadSource == null || con.LeadSource == '' )
                {
                    con.LeadSource = lead.LeadSource;
                    flag = true;
                }
                
                if( !con.Snapengage__c )
                {
                    con.Snapengage__c = lead.Snapengage__c;
                    flag = true;
                }
                
                if( con.Survey_Agency_Services__c == null || con.Survey_Agency_Services__c == '' )
                {
                    con.Survey_Agency_Services__c = lead.Survey_Agency_Services__c;
                    flag = true;
                }
                
                if( con.Survey_Current_Attribution_Model__c == null || con.Survey_Current_Attribution_Model__c == '' )
                {
                    con.Survey_Current_Attribution_Model__c = lead.Current_Attribution_Model_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Marketing_Channels_in_Use__c == null || con.Survey_Marketing_Channels_in_Use__c == '' )
                {
                    con.Survey_Marketing_Channels_in_Use__c = lead.Marketing_Channels_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Name_of_Agency__c == null || con.Survey_Name_of_Agency__c == '' )
                {
                    con.Survey_Name_of_Agency__c = lead.Survey_Name_of_Agency__c;
                    flag = true;
                }
                
                if( con.Survey_Reporting_Tools_and_Apps_in_Use__c == null || con.Survey_Reporting_Tools_and_Apps_in_Use__c == '' )
                {
                    con.Survey_Reporting_Tools_and_Apps_in_Use__c = lead.Reporting_Tools_and_Apps_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Using_an_Agency__c == null || con.Survey_Using_an_Agency__c == '' )
                {
                    con.Survey_Using_an_Agency__c = lead.Survey_Using_an_Agency__c;
                    flag = true;
                }
                
                if( con.Calls_Made__c == null || con.Calls_Made__c == '' )
                {
                    con.Calls_Made__c = lead.MASTER_SDR_Contact_Attempts_2__c;
                    flag = true;
                }
                
                if( con.Follow_up_Date__c == null )
                {
                    con.Follow_up_Date__c = lead.MASTER_SDR_Follow_Up_Date__c;
                    flag = true;
                }
                
                if( con.Relevant_ADR_Notes__c == null || con.Relevant_ADR_Notes__c == '' )
                {
                    con.Relevant_ADR_Notes__c = lead.MASTER_SDR_Notes__c;
                    flag = true;
                }
                
                if( con.ADR_Owner__c == null )
                {
                    if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' && nameToUserMap.containsKey( lead.MASTER_SDR_Owner__c ))
                    {
                        con.ADR_Owner__c = nameToUserMap.get( lead.MASTER_SDR_Owner__c ).Id;
                        flag = true;
                    }
                }
                
                if( con.Current_Stage__c == null || con.Current_Stage__c == '' )
                {
                    con.Current_Stage__c = lead.MASTER_SDR_Stage_2__c;
                    flag = true;
                }
                
                if( con.Demo_Result__c == null || con.Demo_Result__c == '' )
                {
                    con.Demo_Result__c = lead.Demo_Rejection_Reason__c;
                    flag = true;
                }
                
                if( con.Demo_Scheduled_Date__c == null )
                {
                    con.Demo_Scheduled_Date__c = lead.Demo_Scheduled_Date__c;
                    flag = true;
                }
                
                if( flag )
                    contactsToBeUpdated.put( con.Id, con );
            }
            
            leadConverts.add(lc);
        }
        
        if( leadConverts.size() > 0 )
            Database.convertLead( leadConverts );
        
        if( accountsToBeUpdated.size() > 0 )
            update accountsToBeUpdated.values();
            
        if( contactsToBeUpdated.size() > 0 )
            update contactsToBeUpdated.values();
    }
    
    public static void scheduleLeadConversion()
    {
        Set<Id> leadIdsToScheduleAterFiveMins = new Set<Id>();
        Set<Id> leadIdsToScheduleAterThirtyMins = new Set<Id>();
        Set<Id> leadIds = new Set<Id>();
        
        for( Lead lead : newLeadList )
        {
            if( !lead.IsConverted )
            {
                if( lead.bizible2__Account__c != null )
                    leadIds.add( lead.Id );
                else if( lead.Inbound__c )
                    leadIdsToScheduleAterFiveMins.add( lead.Id );
                else
                    leadIdsToScheduleAterThirtyMins.add( lead.Id );
            }
            system.debug(leadIds);
            system.debug(leadIdsToScheduleAterFiveMins);
            system.debug(leadIdsToScheduleAterThirtyMins);
        }
        
        if( leadIds.size() > 0 )
            LeadConnectorBatch.runBatchJob( 200, '', leadIds );
        
        if( leadIdsToScheduleAterFiveMins.size() > 0 )
            convertLeadsByBatch( leadIdsToScheduleAterFiveMins, 5 );
        
        if( leadIdsToScheduleAterThirtyMins.size() > 0 )
            convertLeadsByBatch( leadIdsToScheduleAterThirtyMins, 30 );
    }
    
    @future
    private static void convertLeadsByBatch( Set<Id> leadIds, Integer mins )
    {
        // Get the new Date time instance for schedular
        Datetime nextRunInstance = Datetime.now().addMinutes( mins );
        
        // Get seconds, minutes and hours
        String seconds = String.valueOf( nextRunInstance.second());
        String minutes = String.valueOf( nextRunInstance.minute());
        String hour = String.valueOf( nextRunInstance.hour());
        String day = String.valueOf( nextRunInstance.day());
        String month = String.valueOf( nextRunInstance.month());
        String year = String.valueOf( nextRunInstance.year());
        
        // Create Schedular string and return
        String nextFireTime = seconds + ' ' + minutes + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
        
        LeadConversionScheduler.runSchedular( nextFireTime, leadIds );
    }
}
global with sharing class LeadConversionScheduler implements Schedulable
{
    // To store lead Id
    private Set<Id> leadIds;
    
    /**
     * Name: runSchedular
     * @param: schedularString - Time string to schedule batch
     *         leadId - Lead id to be converted
     * @return: 
     * Desc: Method which initiates the schedular class to run the Batch Class
    **/
    global static void runSchedular( String schedularString, Set<Id> leadIds )
    {
        // Create the instance of schedular class
        LeadConversionScheduler schedularInstance = new LeadConversionScheduler();
        schedularInstance.leadIds = leadIds;
        
        // Schedule the class
        System.schedule( 'Lead Conversion starts at ' + Datetime.now() + ' ' + Math.random(), schedularString, schedularInstance );
    }
    
    /**
     * Name: execute
     * @param: SC - SchedulableContext
     * @return: 
     * Desc: Schedular execution method, to process results
    **/
    global void execute( SchedulableContext SC )
    {
        // Run the Queue
        LeadConnectorBatch.runBatchJob( 200, '', leadIds );
    }
}


Thanks!!
Hello Everyone!

I have created a trigger and class in my sandbox that fires after insert and after update.  I am now working on creating a test class for it, and I am achieving code coverage, but as soon as I add in System.assertEquals(1, [select count() from Commissions_Chart__c]); to verify that a record has been created, it fails.  Any help is appreciated!!  Trigger, class, and test class are below!

Trigger:
trigger CommissionsTrigger on Opportunity (after update, after insert) {
    
    List<Opportunity> comToUpdate = new List<Opportunity>();
    List<Opportunity> comToInsert = new List<Opportunity>();
    List<Opportunity> comToDelete = new List<Opportunity>();
    
    For(Opportunity opp:Trigger.new){
        If(Trigger.isupdate){
            Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
            If(oldOpp.OwnerId != opp.OwnerId){
                comToDelete.add(opp);
                comToInsert.add(opp);
            }
        }
        system.debug('Opps to Delete: ' + comToDelete);
        System.debug('Opps to Insert: ' + comToInsert);
    }
    
    For(Opportunity o: Trigger.new){
        If(Trigger.isinsert){
            comToInsert.add(o);
        }
        If(Trigger.isUpdate){
            comToUpdate.add(o);
        }
    }
    
   if(comToInsert.size()>0){
        CommissionsClass.CreateCommissionsObject(comToInsert);
       system.debug('comToInsert List is : ' + comToInsert);
    }
    If(comToDelete.size()>0){
        CommissionsClass.DeleteCommissionsObject(comToDelete);
        system.debug('comToDelete List is : ' + comToDelete);
    }
   if(comToUpdate.size()>0){
        CommissionsClass.UpdateCommissionsObject(comToUpdate);
       System.debug('comToUpdate List is : ' + comToUpdate);
    }
    

}



Class:
public class CommissionsClass {
    public static void CreateCommissionsObject(Opportunity[] comToInsert){
        List<Commissions_Chart__c> comInsert = new List<Commissions_Chart__c>();
        List<Commissions__c> comToAttach = [select Id, OwnerId, Commissions_Month__c FROM Commissions__c WHERE Commissions_Month__c = THIS_MONTH];
        
        For(Commissions__c cm : comToAttach){
            For(Opportunity o : comToInsert){
                If(cm.OwnerId == o.OwnerId){
                    Commissions_Chart__c c = new Commissions_Chart__c(Account_Name__c = o.AccountId, Close_Date__c = o.closeDate, 
                                                              Opportunity_MRR__c = o.Billing_Amount_Monthly_Calcualted__c,Opportunity_Name__c = o.Id,
                                                             Opportunity_Stage__c = o.StageName, User__c = o.OwnerId, Commissions__c = cm.Id, Payment_Term__c = o.Contract_Payment_Terms__c, 
                                                                      Services_Amount__c = o.Professional_Service_Amount__c);
                    If(o.Total_Renewal_Term__c != NULL){
                        c.Term__c = o.Contract_Initial_Term_Months__c + o.Total_Renewal_Term__c;
                    }else{
                        c.Term__c = o.Contract_Initial_Term_Months__c;
                    }
                    comInsert.add(c);
                }
        }
        }
        System.debug('ComInsert list: ' + comInsert);
        insert comInsert;
    }
    
    public static void DeleteCommissionsObject(Opportunity[] comToDelete){
        
       List<Commissions_Chart__c> ccToDelete = new List<Commissions_Chart__c>();
       List<Commissions_Chart__c> charts = [select Id, Opportunity_Name__c, User__c from Commissions_Chart__c where Opportunity_Name__c In : ComToDelete];
       List<Opportunity> opps = [select ID, OwnerId from Opportunity where ID in :comToDelete];
        
        For(Commissions_Chart__c ch : charts){
            for (opportunity ops : opps){
                If(ch.User__c != ops.OwnerId){
                    ccToDelete.add(ch);
                }
            }
        }
            Database.DeleteResult[] drList = Database.delete(ccToDelete, false);

        
        for(Database.DeleteResult dr : drList){
            if(dr.isSuccess()){
                System.debug('Successfully deleted Commissions Chart with ID: ' + dr.getID());
            }
            else {
                for (Database.Error err : dr.getErrors()){
                    system.debug('The following error has occurred.');
                    system.debug(err.getStatusCode() + ' : ' + err.getMessage());
                    System.debug('Commissions Chart fields that affected this error: ' + err.getFields());
                }
            }
        }


        
    }
    
        public static void UpdateCommissionsObject(Opportunity[] comToUpdate){
        List<Commissions_Chart__c> comUpdate = [SELECT Id, Account_Name__c, Close_Date__c, Opportunity_MRR__c, Opportunity_Name__c, Opportunity_Stage__c, User__c, Term__c 
                                                FROM Commissions_Chart__c WHERE Close_Date__c = THIS_YEAR];
        List<Commissions_Chart__c>updatecom = new List<Commissions_Chart__C>();
        
        for(Commissions_Chart__c cc:comUpdate){
            For(opportunity op : comToUpdate){
                If(cc.Opportunity_Name__c == op.Id){
                    cc.opportunity_stage__C = Op.StageName;
                    cc.Close_Date__c = op.CloseDate;
                    cc.Opportunity_MRR__C = op.Billing_Amount_Monthly_Calcualted__c;
                    cc.Payment_Term__c = op.Contract_Payment_Terms__c;
                    cc.Services_Amount__c = op.Professional_Service_Amount__c;
                    If(op.Total_Renewal_Term__c != NULL){
                        cc.Term__c = op.Contract_Initial_Term_Months__c + op.Total_Renewal_Term__c;
                    }else{
                        cc.Term__c = op.Contract_Initial_Term_Months__c;
                    }
                    
                    updatecom.add(cc);
                }
                system.debug(updatecom);
            }
        }
            update updatecom;

        
    }

}



Test Class:
@isTest
public class CommissionsCalculatorTest {
    static testMethod void CommissionsTriggerTest() {
    
        //fetch IDs for records
        Profile P = [select ID from Profile where Name = 'Standard User'];
        RecordType rt = [select ID from recordtype where name ='New Business'];
        
        
        //Create a user for testing
        User u = new User(FirstName = 'Testing', 
                          LastName = 'User', 
                          email = 'testing@bizible.com', 
                          monthly_quota__c = 5000,
                         username = 'testing@bizible.com',
                         Alias = 'tuser',
                         profileId = p.Id,
                         TimeZoneSidKey = 'America/Los_Angeles',
                         LocaleSidKey = 'en_US',
                         EmailEncodingKey = 'UTF-8',
                         LanguageLocaleKey = 'en_US');
        Insert u;
    
        //Create account for Opportunities
        Account a = new Account(Name = 'TestingCommissions',
                               OwnerId = u.Id,
                               ADR_Owner__C = u.Id);
        Insert a;
        
        //Create Commissions__C record for commissions Chart
        Commissions__c c = new Commissions__c(Name = u.FirstName,
                                          OwnerId = u.Id,
                                          Commissions_month__c = System.today());
        
        
        //Create Opportuntitiy for Trigger
        List<Opportunity> Opps = new List<Opportunity>();

        Opportunity o1 = new Opportunity(Name = 'TestCommissions1',
                                   stageName = 'Qualified Discovery',
                                   CloseDate = system.date.today(),
                                   Amount = 12000,
                                   AccountID = a.ID,
                                   Contract_Payment_Terms__c = 'Monthly',
                                   Contract_Initial_Term_Months__c = 12,
                                   OwnerId = u.Id,
                                   recordtypeID = rt.Id);

       

        Test.startTest();
        
        insert o1;

        Test.stopTest();
        
        System.assertEquals(1, [select count() from Opportunity]);
        System.assertEquals(1, [select count() from Commissions_Chart__c]);
    }
}
 
Hello!

I have been given the task of creating cases whenever a task with a specific subject is attached to a contact.  It works just fine for new contacts in the system, but every time marketing inserts new campaigns, a case is created for every past task with the subject as well.  So at times we can get 100+ cases created on old tasks.  The code that I am using is below:

Trigger:

trigger taskToCaseCreate on Task (after insert, after update) {
        if(checkRecursive.runOnce())
    {

    
    List<Task> newTaskList = new List<Task>();
    
    If (Trigger.isInsert){
        For(Task T: Trigger.new){
            If (T.WhoId != NULL){
                newTaskList.add(T);
            }
        }
    }
    
    If (Trigger.isUpdate){
        For(Task T : Trigger.new){
            String o = trigger.oldMap.get(T.ID).WhoID;
            If (T.WhoId != NULL && T.Subject.contains('Submitted Form')){
            If(Trigger.oldMap.get(T.Id).WhoId != Trigger.newMap.get(T.Id).WhoId && !o.startswith('003')){
                newTaskList.add(T);
            }
            }
        }
    }
    
       If(newTaskList.size() > 0){
    createCaseFromTask.createCaseFromTask(newTaskList);
    }
    }
}

Class:

public class createCaseFromTask {
    Public Static void createCaseFromTask(Task[] newTask){
        
        List<Case> newCase = new List<Case>();
        
         for (Task n:newTask){
             String s = n.WhoId;
             
                If(s.startswith('003') && n.subject.contains('Submitted Form') && (n.subject.contains('Demo') || n.Subject.contains('Contact'))){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Demo Request');
                   // newCase.add(c);
                     Insert c;
                }     
                If(s.startswith('003') && n.subject.contains('Submitted Form') && n.subject.contains('Content Download')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Content Download');
                  //  newCase.add(c);
                     Insert c;
                  
                }
                If(s.startswith('003') && n.subject.contains('Submitted Form') && n.subject.contains('Webinar')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Webinar');
                  //  newCase.add(c);
                     Insert c;
                  
                }
                If(s.startswith('003') && n.subject.contains('Submitted Form') && n.subject.contains('Blog')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Subscribed to Blog Notifications');
                 //   newCase.add(c);
                     Insert c;
                   
                }  
                If(s.startswith('003') && n.subject.contains('Submitted Form') && !n.subject.contains('Blog') && !n.subject.contains('Webinar') && !n.subject.contains('Content Download') && !n.subject.contains('Demo') && !n.Subject.contains('Contact')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Submitted Form');
                  //  newCase.add(c);
                     Insert c;
                  
                } 
              //  Insert newCase;
                }
    }

}



To add to this, we insert everything into the system as a lead.  Then we have a piece of code that autoconverts the lead to a contact and deduplicates it in the process.  So marketing inserts their lists as leads, and then the leads run through the code, get converted to contacts, then merged.  It seems that when they merged, all the tasks are retriggered.  I tried turning the oldmap ID into a string and skipping it when the old ID is a contact as well but it is still creating the cases.  Any help would be much appreciated.

Thanks!
Hello,

The company that I work for has custom code to convert a lead to a contact/account.  For some reason it only fires about half the time.  This is extrememly important because our users do not have access to leads so when they are not converted they are not followed up with. I would really appreciate it if anyone can look and see if they find any errors. I have been looking through it for days and cannot seem to figure out why it only fires half the time and doesn't send me any error messages.  This is a little bit beyond my ability as I have never worked with @future methods or scheduling things via the UI.

Trigger:
trigger LeadTrigger on Lead( after update, after insert )
{
    // Assign values of trigger new list to helper class variable
    LeadTriggerHelper.newLeadList = trigger.new;
    // Assign values of trigger old list to helper class variable
    LeadTriggerHelper.oldLeadList = trigger.old;
    // Assign values of trigger new map to helper class variable
    LeadTriggerHelper.newLeadMap = trigger.newMap;
    // Assign values of trigger old map to helper class variable
    LeadTriggerHelper.oldLeadMap = trigger.oldMap;
    
    // Check if runTrigger
    if( LeadTriggerHelper.runTrigger )
    {
        // Check if after
        if( trigger.isAfter )
        {
            // Check if Update
            if( trigger.isUpdate )
            {
                // Call method to convert lead
                LeadTriggerHelper.leadConversionAfterInsert();
            }
            
            if( trigger.isInsert )
            {
                LeadTriggerHelper.scheduleLeadConversion();
            }
        }
    }
}
Classes:
public with sharing class LeadTriggerHelper
{
    // To check whether to call boolean or not
    public static Boolean runTrigger = true;
    // List to store Lead of trigger.new
    public static List<Lead> newLeadList = new List<Lead>();
    // List to store Lead of trigger.old
    public static List<Lead> oldLeadList = new List<Lead>();
    // Map to store Lead of trigger.newMap
    public static Map<Id, Lead> newLeadMap = new Map<Id, Lead>();
    // Map to store Lead of trigger.oldMap
    public static Map<Id, Lead> oldLeadMap = new Map<Id, Lead>();
    
    private static String convertStatus;
    private static Map<String, User> nameToUserMap = new Map<String, User>();
    
    /**
     * Name: leadConversionAfterInsert
     * @param:
     * @return:
     * Desc: Method to convert lead when created
    **/
    public static void leadConversionAfterInsert()
    {
        //try
        //{
            Set<String> uniqueEmails = new Set<String>();
            Set<String> uniqueWebsites = new Set<String>();
            List<Lead> uniqueLeads = new List<Lead>();
            List<Lead> existingLeads = new List<Lead>();
            List<Lead> newAccountExistingEmail = new List<Lead>();
            Set<String> userNames = new Set<String>();
            
            for( Lead lead : newLeadList )
            {
                if( lead.Convert__c && !oldLeadMap.get( lead.Id ).Convert__c && !lead.Isconverted )
                {
                    if( lead.Website != null && lead.Website != '' )
                    {
                        if( uniqueWebsites.contains( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
                        {
                            if( lead.Email != null && lead.Email != '' )
                            {
                                if( uniqueEmails.contains( lead.Email ))
                                {
                                    newAccountExistingEmail.add( lead );
                                }
                                else
                                {
                                    uniqueEmails.add( lead.Email );
                                    existingLeads.add( lead );
                                }
                            }
                            else
                            {
                                existingLeads.add( lead );
                            }
                        }
                        else
                        {
                            uniqueWebsites.add( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                            uniqueLeads.add( lead );
                            
                            if( lead.Email != null && lead.Email != '' )
                            {
                                uniqueEmails.add( lead.Email );
                            }
                        }
                    }
                    else if( lead.Email != null && lead.Email != '' )
                    {
                        if( uniqueEmails.contains( lead.Email ))
                        {
                            existingLeads.add( lead );
                        }
                        else
                        {
                            uniqueEmails.add( lead.Email );
                            uniqueLeads.add( lead );
                        }
                    }
                    else
                    {
                        uniqueLeads.add( lead );
                    }
                    
                    if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' )
                        userNames.add( lead.MASTER_SDR_Owner__c );
                }
            }
            
            LeadStatus convertStatuses = [ Select MasterLabel from LeadStatus where IsConverted = true limit 1 ];
            convertStatus = convertStatuses.MasterLabel;
            
            for( User u : [ Select Id, Name from User where Name IN :userNames ])
            {
                nameToUserMap.put( u.Name, u );
            }
            
            convertLeads( uniqueLeads );
            convertLeads( existingLeads );
            convertLeads( newAccountExistingEmail );
        /*}
        catch( Exception e )
        {
            system.debug( 'Error********************' + e.getMessage() + ':::::::::::::::' + e.getLineNumber() );
        }*/
    }
    
    public static void convertLeads( List<Lead> leadsToBeConverted )
    {
        Set<String> emailAddressSet = new Set<String>();
        Set<Id> accountIds = new Set<Id>();
        Set<String> webSiteSet = new Set<String>();
        
        for( Lead lead : leadsToBeConverted )
        {
            if( lead.bizible2__Account__c != null )
                accountIds.add( lead.bizible2__Account__c );
            else if( lead.Website != null && lead.Website != '' )
                webSiteSet.add( '%' + lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                
            if( lead.Email != null && lead.Email != '' )
                emailAddressSet.add( lead.Email );
        }
        
        Map<Id, Account> accountMap = new Map<Id, Account>([ Select Id, Website, Phone, Description, Intel_City__c,
                                                                Intel_Country__c, Intel_State__c, Territory_New__c,
                                                                ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                                                    Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                                                    Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                                                    LeadSource from Contacts where Email IN :emailAddressSet )
                                                                from Account where Id IN :accountIds ]);
        
        Map<String, List<Account>> websiteToAccountMap = new Map<String, List<Account>>();
        for( Account acc : [ Select Id, Website, Phone, Description, Intel_City__c, Intel_Country__c, Intel_State__c,
                                Territory_New__c, ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                LeadSource from Contacts where Email IN :emailAddressSet ) from Account where Website like :webSiteSet ])
        {
            List<Account> accs = new List<Account>();
            if( websiteToAccountMap.containsKey( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                accs = websiteToAccountMap.get( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
            }
            
            accs.add( acc );
            websiteToAccountMap.put( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ), accs );
        }
        
        /*Map<String, Contact> emailAddressToContactMap = new Map<String, Contact>();
        for( Contact con : [ Select Id, Email, Phone, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                            Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                            Survey_Using_an_Agency__c, MASTER_SDR_Contact_Attempts__c, MASTER_SDR_Follow_Up_Date__c, MASTER_SDR_Notes__c,
                            MASTER_SDR_Owner__c, MASTER_SDR_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                            LeadSource from Contact where Email IN :emailAddressSet ])
        {
            emailAddressToContactMap.put( con.Email, con );
        }*/
        
        List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
        Map<Id, Account> accountsToBeUpdated = new Map<Id, Account>();
        Map<Id, Contact> contactsToBeUpdated = new Map<Id, Contact>();
        
        for( Lead lead : leadsToBeConverted )
        {
            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setDoNotCreateOpportunity( true );
            lc.setLeadId( lead.Id );
            lc.setConvertedStatus( convertStatus );
            
            Account acc;
            Contact con;
            if( lead.bizible2__Account__c != null && accountMap.containsKey( lead.bizible2__Account__c ))
            {
                acc = accountMap.get( lead.bizible2__Account__c );
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Contact c : acc.Contacts )
                    {
                        if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                        {
                            con = c;
                            break;
                        }
                    }
                }
            }
            else if( lead.Website != null && lead.WebSite != ''
                        && websiteToAccountMap.containsKey( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                List<Account> accounts = websiteToAccountMap.get( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Account a : accounts )
                    {
                        for( Contact c : a.Contacts )
                        {
                            if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                            {
                                acc = a;
                                con = c;
                                break;
                            }
                        }
                        
                        if( acc != null )
                            break;
                    }
                    
                    if( acc == null )
                        acc = accounts[0];
                }
            }
            
            if( acc != null )
            {  
                lc.setAccountId( acc.Id );
                Boolean flag = false;
                
                if( acc.Phone == null || acc.Phone == '' )
                {
                    acc.Phone = lead.Phone;
                    flag = true;
                }
                
                if( acc.Description == null || acc.Description == '' )
                {
                    acc.Description = lead.Description;
                    flag = true;
                }
                
                if( acc.Intel_City__c == null || acc.Intel_City__c == '' )
                {
                    acc.Intel_City__c = lead.Intel_City__c;
                    flag = true;
                }
                
                if( acc.Intel_Country__c == null || acc.Intel_Country__c == '' )
                {
                    acc.Intel_Country__c = lead.Intel_Country__c;
                    flag = true;
                }
                
                if( acc.Territory_New__c == null || acc.Territory_New__c == '' )
                {
                    acc.Territory_New__c = lead.Territory_New__c;
                    flag = true;
                }
                
                if( acc.Intel_State__c == null || acc.Intel_State__c == '' )
                {
                    acc.Intel_State__c = lead.Intel_State__c;
                    flag = true;
                }
                
                if( flag )
                    accountsToBeUpdated.put( acc.Id, acc );
            }
            
            if( con != null )
            {
                lc.setContactId( con.Id );
                Boolean flag = false;
                //Contact con = emailAddressToContactMap.get( lead.Email );
                
                if( con.Phone == null || con.Phone == '' )
                {
                    con.Phone = lead.Phone;
                    flag = true;
                }
                
                if( con.Title == null || con.Title == '' )
                {
                    con.Title = lead.Title;
                    flag = true;
                }
                
                if( con.Description == null || con.Description == '' )
                {
                    con.Description = lead.Description;
                    flag = true;
                }
                
                if( con.LeadSource == null || con.LeadSource == '' )
                {
                    con.LeadSource = lead.LeadSource;
                    flag = true;
                }
                
                if( !con.Snapengage__c )
                {
                    con.Snapengage__c = lead.Snapengage__c;
                    flag = true;
                }
                
                if( con.Survey_Agency_Services__c == null || con.Survey_Agency_Services__c == '' )
                {
                    con.Survey_Agency_Services__c = lead.Survey_Agency_Services__c;
                    flag = true;
                }
                
                if( con.Survey_Current_Attribution_Model__c == null || con.Survey_Current_Attribution_Model__c == '' )
                {
                    con.Survey_Current_Attribution_Model__c = lead.Current_Attribution_Model_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Marketing_Channels_in_Use__c == null || con.Survey_Marketing_Channels_in_Use__c == '' )
                {
                    con.Survey_Marketing_Channels_in_Use__c = lead.Marketing_Channels_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Name_of_Agency__c == null || con.Survey_Name_of_Agency__c == '' )
                {
                    con.Survey_Name_of_Agency__c = lead.Survey_Name_of_Agency__c;
                    flag = true;
                }
                
                if( con.Survey_Reporting_Tools_and_Apps_in_Use__c == null || con.Survey_Reporting_Tools_and_Apps_in_Use__c == '' )
                {
                    con.Survey_Reporting_Tools_and_Apps_in_Use__c = lead.Reporting_Tools_and_Apps_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Using_an_Agency__c == null || con.Survey_Using_an_Agency__c == '' )
                {
                    con.Survey_Using_an_Agency__c = lead.Survey_Using_an_Agency__c;
                    flag = true;
                }
                
                if( con.Calls_Made__c == null || con.Calls_Made__c == '' )
                {
                    con.Calls_Made__c = lead.MASTER_SDR_Contact_Attempts_2__c;
                    flag = true;
                }
                
                if( con.Follow_up_Date__c == null )
                {
                    con.Follow_up_Date__c = lead.MASTER_SDR_Follow_Up_Date__c;
                    flag = true;
                }
                
                if( con.Relevant_ADR_Notes__c == null || con.Relevant_ADR_Notes__c == '' )
                {
                    con.Relevant_ADR_Notes__c = lead.MASTER_SDR_Notes__c;
                    flag = true;
                }
                
                if( con.ADR_Owner__c == null )
                {
                    if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' && nameToUserMap.containsKey( lead.MASTER_SDR_Owner__c ))
                    {
                        con.ADR_Owner__c = nameToUserMap.get( lead.MASTER_SDR_Owner__c ).Id;
                        flag = true;
                    }
                }
                
                if( con.Current_Stage__c == null || con.Current_Stage__c == '' )
                {
                    con.Current_Stage__c = lead.MASTER_SDR_Stage_2__c;
                    flag = true;
                }
                
                if( con.Demo_Result__c == null || con.Demo_Result__c == '' )
                {
                    con.Demo_Result__c = lead.Demo_Rejection_Reason__c;
                    flag = true;
                }
                
                if( con.Demo_Scheduled_Date__c == null )
                {
                    con.Demo_Scheduled_Date__c = lead.Demo_Scheduled_Date__c;
                    flag = true;
                }
                
                if( flag )
                    contactsToBeUpdated.put( con.Id, con );
            }
            
            leadConverts.add(lc);
        }
        
        if( leadConverts.size() > 0 )
            Database.convertLead( leadConverts );
        
        if( accountsToBeUpdated.size() > 0 )
            update accountsToBeUpdated.values();
            
        if( contactsToBeUpdated.size() > 0 )
            update contactsToBeUpdated.values();
    }
    
    public static void scheduleLeadConversion()
    {
        Set<Id> leadIdsToScheduleAterFiveMins = new Set<Id>();
        Set<Id> leadIdsToScheduleAterThirtyMins = new Set<Id>();
        Set<Id> leadIds = new Set<Id>();
        
        for( Lead lead : newLeadList )
        {
            if( !lead.IsConverted )
            {
                if( lead.bizible2__Account__c != null )
                    leadIds.add( lead.Id );
                else if( lead.Inbound__c )
                    leadIdsToScheduleAterFiveMins.add( lead.Id );
                else
                    leadIdsToScheduleAterThirtyMins.add( lead.Id );
            }
            system.debug(leadIds);
            system.debug(leadIdsToScheduleAterFiveMins);
            system.debug(leadIdsToScheduleAterThirtyMins);
        }
        
        if( leadIds.size() > 0 )
            LeadConnectorBatch.runBatchJob( 200, '', leadIds );
        
        if( leadIdsToScheduleAterFiveMins.size() > 0 )
            convertLeadsByBatch( leadIdsToScheduleAterFiveMins, 5 );
        
        if( leadIdsToScheduleAterThirtyMins.size() > 0 )
            convertLeadsByBatch( leadIdsToScheduleAterThirtyMins, 30 );
    }
    
    @future
    private static void convertLeadsByBatch( Set<Id> leadIds, Integer mins )
    {
        // Get the new Date time instance for schedular
        Datetime nextRunInstance = Datetime.now().addMinutes( mins );
        
        // Get seconds, minutes and hours
        String seconds = String.valueOf( nextRunInstance.second());
        String minutes = String.valueOf( nextRunInstance.minute());
        String hour = String.valueOf( nextRunInstance.hour());
        String day = String.valueOf( nextRunInstance.day());
        String month = String.valueOf( nextRunInstance.month());
        String year = String.valueOf( nextRunInstance.year());
        
        // Create Schedular string and return
        String nextFireTime = seconds + ' ' + minutes + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
        
        LeadConversionScheduler.runSchedular( nextFireTime, leadIds );
    }
}
global with sharing class LeadConversionScheduler implements Schedulable
{
    // To store lead Id
    private Set<Id> leadIds;
    
    /**
     * Name: runSchedular
     * @param: schedularString - Time string to schedule batch
     *         leadId - Lead id to be converted
     * @return: 
     * Desc: Method which initiates the schedular class to run the Batch Class
    **/
    global static void runSchedular( String schedularString, Set<Id> leadIds )
    {
        // Create the instance of schedular class
        LeadConversionScheduler schedularInstance = new LeadConversionScheduler();
        schedularInstance.leadIds = leadIds;
        
        // Schedule the class
        System.schedule( 'Lead Conversion starts at ' + Datetime.now() + ' ' + Math.random(), schedularString, schedularInstance );
    }
    
    /**
     * Name: execute
     * @param: SC - SchedulableContext
     * @return: 
     * Desc: Schedular execution method, to process results
    **/
    global void execute( SchedulableContext SC )
    {
        // Run the Queue
        LeadConnectorBatch.runBatchJob( 200, '', leadIds );
    }
}


Thanks!!
Hello Everyone!

I have created a trigger and class in my sandbox that fires after insert and after update.  I am now working on creating a test class for it, and I am achieving code coverage, but as soon as I add in System.assertEquals(1, [select count() from Commissions_Chart__c]); to verify that a record has been created, it fails.  Any help is appreciated!!  Trigger, class, and test class are below!

Trigger:
trigger CommissionsTrigger on Opportunity (after update, after insert) {
    
    List<Opportunity> comToUpdate = new List<Opportunity>();
    List<Opportunity> comToInsert = new List<Opportunity>();
    List<Opportunity> comToDelete = new List<Opportunity>();
    
    For(Opportunity opp:Trigger.new){
        If(Trigger.isupdate){
            Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
            If(oldOpp.OwnerId != opp.OwnerId){
                comToDelete.add(opp);
                comToInsert.add(opp);
            }
        }
        system.debug('Opps to Delete: ' + comToDelete);
        System.debug('Opps to Insert: ' + comToInsert);
    }
    
    For(Opportunity o: Trigger.new){
        If(Trigger.isinsert){
            comToInsert.add(o);
        }
        If(Trigger.isUpdate){
            comToUpdate.add(o);
        }
    }
    
   if(comToInsert.size()>0){
        CommissionsClass.CreateCommissionsObject(comToInsert);
       system.debug('comToInsert List is : ' + comToInsert);
    }
    If(comToDelete.size()>0){
        CommissionsClass.DeleteCommissionsObject(comToDelete);
        system.debug('comToDelete List is : ' + comToDelete);
    }
   if(comToUpdate.size()>0){
        CommissionsClass.UpdateCommissionsObject(comToUpdate);
       System.debug('comToUpdate List is : ' + comToUpdate);
    }
    

}



Class:
public class CommissionsClass {
    public static void CreateCommissionsObject(Opportunity[] comToInsert){
        List<Commissions_Chart__c> comInsert = new List<Commissions_Chart__c>();
        List<Commissions__c> comToAttach = [select Id, OwnerId, Commissions_Month__c FROM Commissions__c WHERE Commissions_Month__c = THIS_MONTH];
        
        For(Commissions__c cm : comToAttach){
            For(Opportunity o : comToInsert){
                If(cm.OwnerId == o.OwnerId){
                    Commissions_Chart__c c = new Commissions_Chart__c(Account_Name__c = o.AccountId, Close_Date__c = o.closeDate, 
                                                              Opportunity_MRR__c = o.Billing_Amount_Monthly_Calcualted__c,Opportunity_Name__c = o.Id,
                                                             Opportunity_Stage__c = o.StageName, User__c = o.OwnerId, Commissions__c = cm.Id, Payment_Term__c = o.Contract_Payment_Terms__c, 
                                                                      Services_Amount__c = o.Professional_Service_Amount__c);
                    If(o.Total_Renewal_Term__c != NULL){
                        c.Term__c = o.Contract_Initial_Term_Months__c + o.Total_Renewal_Term__c;
                    }else{
                        c.Term__c = o.Contract_Initial_Term_Months__c;
                    }
                    comInsert.add(c);
                }
        }
        }
        System.debug('ComInsert list: ' + comInsert);
        insert comInsert;
    }
    
    public static void DeleteCommissionsObject(Opportunity[] comToDelete){
        
       List<Commissions_Chart__c> ccToDelete = new List<Commissions_Chart__c>();
       List<Commissions_Chart__c> charts = [select Id, Opportunity_Name__c, User__c from Commissions_Chart__c where Opportunity_Name__c In : ComToDelete];
       List<Opportunity> opps = [select ID, OwnerId from Opportunity where ID in :comToDelete];
        
        For(Commissions_Chart__c ch : charts){
            for (opportunity ops : opps){
                If(ch.User__c != ops.OwnerId){
                    ccToDelete.add(ch);
                }
            }
        }
            Database.DeleteResult[] drList = Database.delete(ccToDelete, false);

        
        for(Database.DeleteResult dr : drList){
            if(dr.isSuccess()){
                System.debug('Successfully deleted Commissions Chart with ID: ' + dr.getID());
            }
            else {
                for (Database.Error err : dr.getErrors()){
                    system.debug('The following error has occurred.');
                    system.debug(err.getStatusCode() + ' : ' + err.getMessage());
                    System.debug('Commissions Chart fields that affected this error: ' + err.getFields());
                }
            }
        }


        
    }
    
        public static void UpdateCommissionsObject(Opportunity[] comToUpdate){
        List<Commissions_Chart__c> comUpdate = [SELECT Id, Account_Name__c, Close_Date__c, Opportunity_MRR__c, Opportunity_Name__c, Opportunity_Stage__c, User__c, Term__c 
                                                FROM Commissions_Chart__c WHERE Close_Date__c = THIS_YEAR];
        List<Commissions_Chart__c>updatecom = new List<Commissions_Chart__C>();
        
        for(Commissions_Chart__c cc:comUpdate){
            For(opportunity op : comToUpdate){
                If(cc.Opportunity_Name__c == op.Id){
                    cc.opportunity_stage__C = Op.StageName;
                    cc.Close_Date__c = op.CloseDate;
                    cc.Opportunity_MRR__C = op.Billing_Amount_Monthly_Calcualted__c;
                    cc.Payment_Term__c = op.Contract_Payment_Terms__c;
                    cc.Services_Amount__c = op.Professional_Service_Amount__c;
                    If(op.Total_Renewal_Term__c != NULL){
                        cc.Term__c = op.Contract_Initial_Term_Months__c + op.Total_Renewal_Term__c;
                    }else{
                        cc.Term__c = op.Contract_Initial_Term_Months__c;
                    }
                    
                    updatecom.add(cc);
                }
                system.debug(updatecom);
            }
        }
            update updatecom;

        
    }

}



Test Class:
@isTest
public class CommissionsCalculatorTest {
    static testMethod void CommissionsTriggerTest() {
    
        //fetch IDs for records
        Profile P = [select ID from Profile where Name = 'Standard User'];
        RecordType rt = [select ID from recordtype where name ='New Business'];
        
        
        //Create a user for testing
        User u = new User(FirstName = 'Testing', 
                          LastName = 'User', 
                          email = 'testing@bizible.com', 
                          monthly_quota__c = 5000,
                         username = 'testing@bizible.com',
                         Alias = 'tuser',
                         profileId = p.Id,
                         TimeZoneSidKey = 'America/Los_Angeles',
                         LocaleSidKey = 'en_US',
                         EmailEncodingKey = 'UTF-8',
                         LanguageLocaleKey = 'en_US');
        Insert u;
    
        //Create account for Opportunities
        Account a = new Account(Name = 'TestingCommissions',
                               OwnerId = u.Id,
                               ADR_Owner__C = u.Id);
        Insert a;
        
        //Create Commissions__C record for commissions Chart
        Commissions__c c = new Commissions__c(Name = u.FirstName,
                                          OwnerId = u.Id,
                                          Commissions_month__c = System.today());
        
        
        //Create Opportuntitiy for Trigger
        List<Opportunity> Opps = new List<Opportunity>();

        Opportunity o1 = new Opportunity(Name = 'TestCommissions1',
                                   stageName = 'Qualified Discovery',
                                   CloseDate = system.date.today(),
                                   Amount = 12000,
                                   AccountID = a.ID,
                                   Contract_Payment_Terms__c = 'Monthly',
                                   Contract_Initial_Term_Months__c = 12,
                                   OwnerId = u.Id,
                                   recordtypeID = rt.Id);

       

        Test.startTest();
        
        insert o1;

        Test.stopTest();
        
        System.assertEquals(1, [select count() from Opportunity]);
        System.assertEquals(1, [select count() from Commissions_Chart__c]);
    }
}
 
Hello!

I have been given the task of creating cases whenever a task with a specific subject is attached to a contact.  It works just fine for new contacts in the system, but every time marketing inserts new campaigns, a case is created for every past task with the subject as well.  So at times we can get 100+ cases created on old tasks.  The code that I am using is below:

Trigger:

trigger taskToCaseCreate on Task (after insert, after update) {
        if(checkRecursive.runOnce())
    {

    
    List<Task> newTaskList = new List<Task>();
    
    If (Trigger.isInsert){
        For(Task T: Trigger.new){
            If (T.WhoId != NULL){
                newTaskList.add(T);
            }
        }
    }
    
    If (Trigger.isUpdate){
        For(Task T : Trigger.new){
            String o = trigger.oldMap.get(T.ID).WhoID;
            If (T.WhoId != NULL && T.Subject.contains('Submitted Form')){
            If(Trigger.oldMap.get(T.Id).WhoId != Trigger.newMap.get(T.Id).WhoId && !o.startswith('003')){
                newTaskList.add(T);
            }
            }
        }
    }
    
       If(newTaskList.size() > 0){
    createCaseFromTask.createCaseFromTask(newTaskList);
    }
    }
}

Class:

public class createCaseFromTask {
    Public Static void createCaseFromTask(Task[] newTask){
        
        List<Case> newCase = new List<Case>();
        
         for (Task n:newTask){
             String s = n.WhoId;
             
                If(s.startswith('003') && n.subject.contains('Submitted Form') && (n.subject.contains('Demo') || n.Subject.contains('Contact'))){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Demo Request');
                   // newCase.add(c);
                     Insert c;
                }     
                If(s.startswith('003') && n.subject.contains('Submitted Form') && n.subject.contains('Content Download')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Content Download');
                  //  newCase.add(c);
                     Insert c;
                  
                }
                If(s.startswith('003') && n.subject.contains('Submitted Form') && n.subject.contains('Webinar')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Webinar');
                  //  newCase.add(c);
                     Insert c;
                  
                }
                If(s.startswith('003') && n.subject.contains('Submitted Form') && n.subject.contains('Blog')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Subscribed to Blog Notifications');
                 //   newCase.add(c);
                     Insert c;
                   
                }  
                If(s.startswith('003') && n.subject.contains('Submitted Form') && !n.subject.contains('Blog') && !n.subject.contains('Webinar') && !n.subject.contains('Content Download') && !n.subject.contains('Demo') && !n.Subject.contains('Contact')){
                    Case c = new Case(ContactId = n.WhoId, Status = 'New', Subject = 'Submitted Form');
                  //  newCase.add(c);
                     Insert c;
                  
                } 
              //  Insert newCase;
                }
    }

}



To add to this, we insert everything into the system as a lead.  Then we have a piece of code that autoconverts the lead to a contact and deduplicates it in the process.  So marketing inserts their lists as leads, and then the leads run through the code, get converted to contacts, then merged.  It seems that when they merged, all the tasks are retriggered.  I tried turning the oldmap ID into a string and skipping it when the old ID is a contact as well but it is still creating the cases.  Any help would be much appreciated.

Thanks!