• P Kumar
  • NEWBIE
  • 70 Points
  • Member since 2015
  • CRM Operations Specialist
  • Element14 India Pvt Ltd

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 13
    Replies
Hi,

I have created trigger with hardcoding.
i want that to work dynamically.
Because, Recordtype Ids are different in Production and sandbox.

Kindly help me where i have to make changes exactly.

Following is my trigger code.
=========================================================================

trigger APACLeadExactTargetEmails on xtma_Individual_Email_Result__c (after insert, after update)
{
    
     set<Id> LeadRts = new Set<Id>{'012200000005uXiAAI','0127E000000CgrLQAS','0127E000000CgqNQAS'};

//    Id rtID= [select Id,name from RecordType where name ='APAC - Open'OR name ='Global Abandoned Checkout' OR name = 'Global New Web Registrant' limit 1].Id;

    Set<String> setIDs = new Set<String>();

    for(xtma_Individual_Email_Result__c Emails : trigger.new){
        if(Emails.Lead__c!=null){
            setIDs.add(Emails.Lead__c);
        }
    }

    List<lead> listLead = [ Select Id FROM Lead where RecordTypeId in :LeadRts AND id in :setIDs ] ;
    Map<String,Lead> mapKeyWiseLead = new Map<String,Lead>();
        for(Lead obj :  listLead )
        {
            String key = obj.id;
            mapKeyWiseLead.put(key,obj);
        }
        
    List<Lead> listUpdatelead = new List<Lead>();
    Set<String> setLeadID = new Set<String>();
    
    String key;
    for(xtma_Individual_Email_Result__c Emails : trigger.new)
    {
        key='';
        if(Emails.Lead__c!=null){
            key=Emails.Lead__c;
            
            if( mapKeyWiseLead.containsKey(key) )
            {
                Lead checkLead = mapKeyWiseLead.get(Key) ;
                
               if(emails.name.contains('1st Newsletter - EDE')) 
                {
                    checkLead.X1st_Email_Date__c= Emails.Date_Time_Sent__c.Date();

                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==FALSE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X1st_Email_Outcome__c = 'Sent';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X1st_Email_Outcome__c = 'Opened';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c>0){
                        checkLead.X1st_Email_Outcome__c = 'Clicked';
                        }
                       if(emails.name=='1st Newsletter - EDE'){checkLead.X1st_Email_Name__c = '1st Newsletter - EDE';
                    }
                        listUpdatelead.add(checkLead);
                        setLeadID.add(checkLead.id);
                }
                if(emails.name.contains('2nd Newsletter - EDE'))
                {
                    checkLead.X2nd_Email_Date__c= Emails.Date_Time_Sent__c.Date();

                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==FALSE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X2nd_Email_Outcome__c = 'Sent';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X2nd_Email_Outcome__c = 'Opened';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c>0){
                        checkLead.X2nd_Email_Outcome__c = 'Clicked';
                        }
                       if(emails.name=='2nd Newsletter - EDE'){checkLead.X2nd_Email_Name__c = '2nd Newsletter - EDE';
                    }
                        listUpdatelead.add(checkLead);
                        setLeadID.add(checkLead.id);
                }
                if(emails.name.contains('3rd Newsletter - EDE')) 
                {
                    checkLead.X3rd_Email_Date__c= Emails.Date_Time_Sent__c.Date();

                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==FALSE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X3rd_Email_Outcome__c = 'Sent';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X3rd_Email_Outcome__c = 'Opened';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c>0){
                        checkLead.X3rd_Email_Outcome__c = 'Clicked';
                        }
                       if(emails.name=='3rd Newsletter - EDE'){checkLead.X3rd_Email_Name__c = '3rd Newsletter - EDE';
                    }
                        listUpdatelead.add(checkLead);
                        setLeadID.add(checkLead.id);
                }
                
            }
        }
    }
        if( listUpdatelead.size() > 0 )
        {
                try
                    {
                        update listUpdatelead;            
                    }
                catch(DMLException e)
                {  
                    System.debug('The following exception has occurred: ' + e.getMessage());
                }
        }
}

Regards,
Pranav
Hi,

I want to send email alert automatically for future date.
future date is set manually.

Can anyone help me how can i achieve this?

Preferable using Workflows and Email alert.


Regards,
Pranav

Hi,

My requirement is as follows

1) The Trigger should update the existing lead with updated Lead Creation Date, lead source and lead source detail if found with same details like first name, last name, email, country and leadsource and leadsource details are not same, Should not insert new record.
2) if lead source and lead source details are also same then through error (Stop inserting new record).
3) if no matching found then insert the record.

I have written the following trigger, which is not working.

am getting follwoing error : 
Apex trigger APACLeadDuplicateofExistingLead caused an unexpected exception, contact your administrator: APACLeadDuplicateofExistingLead: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.APACLeadDuplicateofExistingLead: line 9, column 1

please help as soon as possible.

//Trigger for APAC Region – Managing Duplicate Leads of Existing Lead

trigger APACLeadDuplicateofExistingLead on Lead (before insert)
{
        Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

         for(Lead l:Trigger.new)
         {
                Lead lid = [select ID from Lead where FirstName =: l.Name and LastName =: l.LastName and Email =: l.Email and Country_code__c =: l.Country_code__c and RecordTypeId =: rtID limit 1];

                if(l.LeadSource!= lid.LeadSource || l.Lead_Source_Detail_NEW__c != lid.Lead_Source_Detail_NEW__c )
                {
                    Lead updateLead =[select id from lead where id =: lid.id];
                    
                    updateLead.Lead_Creation_Date__c=System.Today();
                    updateLead.LeadSource=l.LeadSource;
                    updateLead.Lead_Source_Detail_NEW__c=l.Lead_Source_Detail_NEW__c;
                    
                    update updateLead;

                    l.addError('Lead already exist with same details, Lead Id : ' + lid.id);
                }
                if(l.LeadSource== lid.LeadSource && l.Lead_Source_Detail_NEW__c == lid.Lead_Source_Detail_NEW__c )
                {
                    l.addError('Lead already exist with same details, Lead Id : ' + lid.id);
                }
         }
}

Hi,
Following is my trigger and test Class, Please help in acheiveing min 75% of Code Coverage.
Now my trigger has only 49% of code coverage.
I have checked under developer console, Bolded text in trigger are not covered by test class.
Need Help ASAP.
========================================================================
@isTest(SeeAllData=true)
public class LeadTaggingTest{
public static testMethod void LeadTaggingStaticTestMethod(){

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;
Id SiteID= [select Id,name from RecordType where name ='Site' limit 1].Id;
Id BillRtId = [Select Id, name from RecordType where name = 'Billing Account' limit 1].Id;
User O = [select id from user where id='00520000001Omvk' LIMIT 1];
Set<String> allLeadEmails = new Set <String> ();
Set<String> allFirstNames = new Set <String> ();
Set<String> allLastNames = new Set <String> ();
Set<String> allCompanyCodes = new Set <String> ();
Set<String> APACCompanyCodes = new Set<String>{'AU1', 'SG1', 'IN1', 'NZ1', 'CN1'};

try{
    Test.startTest();
  {
      Account Billing = 
      new Account (
          Name='TestBillingAcc', 
          RecordTypeId=BillRtId, 
          Company__c='SG1',
          Primary_Account_Owner__c='Katherine Schuil',
          Primary_Account_Owner_ID__c='TOFFKA',
          Primary_Sales_Function__c='TeleMarketing',
          Owner = O);
      insert Billing;
    
      Account Site = 
      new Account (
          Name='TestSiteAcc', 
          RecordTypeId=SiteId, 
          Company__c='SG1', 
          Ship_To__c = '001',
          Primary_Account_Owner__c='Katherine Schuil',
          Primary_Account_Owner_ID__c='TOFFKA',
          Primary_Sales_Function__c='TeleMarketing',
          Owner = O,
          Parent = Billing,
          Specific_Customer_Type__c='Other',
          CEM_OEM_Tier__c=1,
          Fixed_Quote_Comments__c='Testing Fixed Quote Comments');
      insert Site;

      Contact c = 
      new Contact (
          FirstName = 'Test',
          LastName = 'Lead',
          Email = 'testinglead@element14.com',
          Account_Number__c = '12345',
          PIN__c = '064582',
          First_Order_Date__c = Date.newInstance( 2015, 2, 2 ),
          Turnover__c = 10000.00,
          Account = Site
          );
      insert c;
  
      Lead l = 
      new Lead (
          FirstName ='Test', 
          LastName ='Lead', 
          Country_code__c ='Singapore',
          Company = 'SG1',
          email = 'testinglead@element14.com',
          Lead_Type__c = 'New Company',
          LeadSource = 'Supplier Lead Referral',
      RecordTypeId=rtID,
          Lead_Source_Detail_NEW__c = '3M');
          insert l;

Contact c1 = 
      new Contact (
          FirstName = 'TestP',
          LastName = 'Lead',
          Email = 'testinglead@element14.com',
          Account_Number__c = '12345',
          PIN__c = '064582',
          First_Order_Date__c = Date.newInstance( 2015, 2, 2 ),
          Turnover__c = 0.00,
          Account = Site
          );
insert c1;          

Lead l1 = 
      new Lead (
          FirstName ='Test', 
          LastName ='Lead', 
          Country_code__c ='Singapore',
          Company = 'SG1',
          email = 'testinglead@element14.com',
          Lead_Type__c = 'New Company',
          LeadSource = 'Supplier Lead Referral',
          RecordTypeId=rtID,
          Lead_Source_Detail_NEW__c = '3M');
insert l1;         
 }
 Test.stopTest();
} catch (Exception e) {
    system.assertEquals('********* Error Found ********', e.getMessage());
    System.debug('******@ Exception*****');
}
System.debug('******End of Test*****');
}
}
========================================================================
Trigger LeadTagging on Contact (after insert, after update)
{
  if( ContactLeadTriggerHandler.isLeadTrigger == false )
    {
        ContactLeadTriggerHandler.isContactTrigger = true;
        
              Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;
               Set<String> setEmailId = new Set<String>();
               Set<String> setFirstName = new Set<String>();
               Set<String> setLastName = new Set<String>();

                for(Contact myContact : Trigger.new)
               {
                       if(myContact.Email != null && myContact.FirstName != null && myContact.LastName != null)
                       {
                               setEmailId.add(myContact.Email);
                               setFirstName.add(myContact.FirstName);
                               setLastName.add(myContact.LastName);
                       }
               }
              List<lead> listLead = [ Select Id, FirstName, LastName, Email, Status, Ready_to_Convert__c, Country_code__c FROM Lead where RecordTypeId = :rtId AND ( Email in :setEmailId or FirstName in :setFirstName or LastName in :setLastName ) ] ;
               
               Map<String,Lead> mapKeyWiseLead = new Map<String,Lead>();
               for(Lead obj :  listLead )
               {
                    String key = obj.Email +'-'+obj.FirstName+'-'+obj.LastName;
                    mapKeyWiseLead.put(key,obj);
               }
               
               List<Lead> listUpdatelead = new List<Lead>();
               Set<String> setLeadID = new Set<String>(); // Added to check duplicate Lead
                
                String key;
                for(Contact myContact : Trigger.new)
                {
                    key='';
                    if(myContact.email != null && myContact.FirstName != null && myContact.LastName != null)
                    {
                        key = myContact.Email +'-'+myContact.FirstName+'-'+myContact.LastName;
                        if( mapKeyWiseLead.containsKey(key) )
                        {
                            Lead checkLead = mapKeyWiseLead.get(Key) ;
                            
                               if( checkLead.Email == myContact.email &&  checkLead.FirstName == myContact.FirstName && checkLead.LastName == myContact.LastName )
                                {
                                    System.debug('Lead to Update :'+checkLead.id);
                                      if(myContact.Turnover__c > 0.00)
                                      {
                                              if(setLeadID.contains(checkLead.id) == false)
                                              {
                                                     checkLead.Status = 'Order Placed';
                                                     checkLead.Ready_to_Convert__c = TRUE;
                                                     listUpdatelead.add(checkLead);
                                                     setLeadID.add(checkLead.id);
                                              }
                                      }
                                      if((myContact.Turnover__c <= 0.00 || myContact.Turnover__c== null) && (checkLead.Country_code__c != 'India' || checkLead.Country_code__c != 'China' || checkLead.Country_code__c != 'Taiwan' || checkLead.Country_code__c != 'Hong Kong'))
                                      {
                                              if(setLeadID.contains(checkLead.id) == false)
                                              {
                                                     checkLead.Status = 'Account created';
                                                     listUpdatelead.add(checkLead);
                                                     setLeadID.add(checkLead.id);
                                              }      
                                      }
                                                     checkLead.Existing_Contact__c = TRUE;
                                                     checkLead.Contact_Created_Date__c = myContact.Created_Date__c;
                                                     checkLead.Contact_ID__c = myContact.Id;
                                                     checkLead.Account_Number__c = myContact.Account_number__c;
                                                     checkLead.Ship_To__c = myContact.Ship_To__c;
                                                     checkLead.Contact_Company__c = myContact.Company__c;
                                                     checkLead.Primary_Account_Owner__c = myContact.Primary_Account_Owner__c;
                                                     checkLead.Primary_Account_Owner_ID__c = myContact.Primary_Account_Owner_ID__c;
                                                     checkLead.Contact_Primary_Sales_Function__c = myContact.Primary_Sales_Function__c;
                                                     checkLead.First_Order_Date__c = myContact.First_Order_Date__c;
                                                     checkLead.Contact_Owner__c = myContact.ownerID;
                                                     checkLead.Turnover__c = myContact.Turnover__c;
                                                     checkLead.PIN__c = myContact.PIN__c;
                                }      
                        }
                    }
                }


               if( listUpdatelead.size() > 0 )
               {
                       try
                       {
                               update listUpdatelead;            
                       }
                       catch(DMLException e)
                       {  
                               System.debug('The following exception has occurred: ' + e.getMessage());
                       }
                 }
        }
}

========================================================================

Hi,

When i upload data into salesforce through data loader, am getting 'System.LimitException: Apex CPU time limit exceeded' Error.

Can any one suggest me why this error happens?

Regards,
Pranav

Hi I have tried to create a trigger to Lead Dedupe Management.
It worked perfectly when i inserted single record.
but when i upload through data loader am getting this error.

following is my code. Can any one help in createing the same for bulk inserts of lead through data loader.

==================================================================================
trigger LeadEventDedupeTestTrigger on Lead (before insert, before update)  {

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

    for(Integer i=0;i<Trigger.new.size();i++){
            if(Trigger.new[i].Email !=null && Trigger.new[i].FirstName !=null && Trigger.new[i].LastName !=null){
                Contact ContactList = [Select Id ,Email,FirstName,LastName,Company__c,Account_Number__c,PIN__c,Ship_To__c,
                                            Created_Date__c,Primary_Account_Owner__c,Primary_Account_Owner_ID__c,Primary_Sales_Function__c,
                                            First_Order_Date__c,OwnerId,Owner.Name,Turnover__c
                                            FROM Contact WHERE Email =: Trigger.new[i].Email AND FirstName =: Trigger.new[i].FirstName AND LastName =: Trigger.new[i].LastName]; 
                {
                    Trigger.new[i].Existing_Contact__c = TRUE;
                    Trigger.new[i].Contact_Created_Date__c = ContactList.Created_Date__c;
                    Trigger.new[i].Contact_ID__c = ContactList.Id;
                    Trigger.new[i].Account_Number__c = ContactList.Account_number__c;
                    Trigger.new[i].Ship_To__c = ContactList.Ship_To__c;
                    Trigger.new[i].Contact_Company__c = ContactList.Company__c;
                    Trigger.new[i].Primary_Account_Owner__c = ContactList.Primary_Account_Owner__c;
                    Trigger.new[i].Primary_Account_Owner_ID__c = ContactList.Primary_Account_Owner_ID__c;
                    Trigger.new[i].Contact_Primary_Sales_Function__c = ContactList.Primary_Sales_Function__c;
                    Trigger.new[i].First_Order_Date__c = ContactList.First_Order_Date__c;
                    Trigger.new[i].Contact_Owner_ID__c = ContactList.Owner.Name;
                    Trigger.new[i].Turnover__c = ContactList.Turnover__c;
                    Trigger.new[i].PIN__c = ContactList.PIN__c;
                    
                    if(Trigger.new[i].Lead_Created_Date__c > ContactList.Created_Date__c){
                  if(Trigger.new[i].LeadSource == 'Supplier Lead Referral' || Trigger.new[i].LeadSource == 'Supplier Live Inquiry'){
                      Trigger.new[i].OwnerId = ContactList.OwnerId;
                  }
              else{
                Trigger.new[i].addError('Lead already exist as a Contact, Account Number : ' + ContactList.Account_number__c + ' / PIN : ' + ContactList.PIN__c + '/ Contact ID : ' + ContactList.Id);
              }
                }
            }
        }
    }
}

Hi,

I want to update leads based on criteria once after the contact is insereted. This trigger is not working for my bulk inserts or updates. Am getting error 'System.LimitException: Too many SOQL queries: 101'. Can anyone help me out ?
There is other trigger on leads which will tag the contact details on lead object fields when lead is inserted or updated.
I suppose to deliver this by this friday, Very Urgent.


Trigger updateLeads1 on Contact (after insert, after update) {

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

        for(Contact myContact : Trigger.new){
            if(myContact.email != null && myContact.FirstName != null && myContact.LastName != null) {
              for(Lead checkLead : [Select Id, FirstName, LastName, Email, Status, Ready_to_Convert__c, Country_code__c FROM Lead where RecordTypeId = :rtId AND Email = :myContact.Email AND FirstName = :myContact.FirstName AND LastName = :myContact.LastName limit 1]){
                    if(myContact.Turnover__c > 0.00){
                    updatelead(checkLead.id);
                }
             if((myContact.Turnover__c <= 0.00 || myContact.Turnover__c== null) && (checkLead.Country_code__c != 'India' || checkLead.Country_code__c != 'China' || checkLead.Country_code__c != 'Taiwan' || checkLead.Country_code__c != 'Hong Kong')){
                    updatelead1(checkLead.id);
                    }
                }
          }
    }
    
    public static void updatelead(Id leadId) {
    System.debug('Lead ID : '+ leadId);
    lead ld = [SELECT id FROM lead WHERE ID = :leadId];
    system.debug('Lead ID in Query :'+ld);
    ld.Status = 'Order Placed';
    ld.Ready_to_Convert__c = TRUE;
    try {
        update ld;             
        } catch(DMLException e) {   
        System.debug('The following exception has occurred: ' + e.getMessage()); 
        }
}

    public static void updatelead1(Id leadId) {
    System.debug('Lead ID : '+ leadId);
    lead ld = [SELECT id FROM lead WHERE ID = :leadId];
    system.debug('Lead ID in Query :'+ld);
    ld.Status = 'Account created';
    try {
        update ld;             
        } catch(DMLException e) {   
        System.debug('The following exception has occurred: ' + e.getMessage()); 
        }
    }
}

Regards,
Pranav

Can anyone please let me know, why am not able to get 100% code coverage.

Trigger
======

// Trigger for APAC Region - to find Lead & Contact Duplicate

trigger APACLeadEventDedupe on Lead (before insert, before update) {

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

Set<String> allLeadEmails = new Set <String> ();
Set<String> allFirstNames = new Set <String> ();
Set<String> allLastNames = new Set <String> ();
Set<String> allCompanyCodes = new Set <String> ();
Set<String> APACCompanyCodes = new Set<String>{'AU1', 'SG1', 'IN1', 'NZ1', 'CN1'};

       
            if(newlead.email != null && newlead.FirstName != null && newlead.LastName != null && newlead.Company_Code__c != null && newlead.RecordTypeId == rtId ) {
                allLeadEmails.add(newlead.email);
                allFirstNames.add(newlead.FirstName);
                allLastNames.add(newlead.LastName);
                allCompanyCodes.add(newlead.Company_Code__c);
                }
    }

//Step 2: Query for All Contact Records in Step 1


    List<Contact> ContactList = [Select Id ,Email,FirstName,LastName,Company__c,Account_Number__c,PIN__c,Ship_To__c,
                                            Created_Date__c,Primary_Account_Owner__c,Primary_Account_Owner_ID__c,Primary_Sales_Function__c,
                                            First_Order_Date__c,OwnerId,Owner.Name,Turnover__c
                                            FROM Contact WHERE Email IN: allLeadEmails AND FirstName IN: allFirstNames AND LastName IN: allLastNames AND Company__c IN: allCompanyCodes]; // AND RecordTypeId=:ContactRtId];
                                            
    System.debug('After query  -values in Where Clause   allLeadEmails '+allLeadEmails );  
          System.debug('After query  -values in Where Clause   allFirstNames '+allFirstNames );  
                System.debug('After query  -values in Where Clause   allLastNames '+allLastNames );
                           System.debug('After query  -values in Where Clause   allCompanyCodes '+allCompanyCodes );  
  
      System.debug('After query  - ContactList '+ContactList );                                      

//For the triggers in the loop, add the relevant contact information.

        
  for (Lead LeadInLoop : Trigger.new) {
      System.debug('---> Line No : 53 <---');
      System.debug('---> Line No : 54 <---'+ContactList);
     for (Contact c: ContactList){
          String companyCode = LeadInLoop.Company_Code__c;
          System.debug('******Company Code is : '+ LeadInLoop.Company_Code__c );
          if(APACCompanyCodes.contains(LeadInLoop.Company_Code__c)){
          System.debug('******Company Code Inserted as : '+ LeadInLoop.Company_Code__c );
          if((LeadInLoop.email == c.email) && (LeadInLoop.FirstName == c.FirstName) && (LeadInLoop.LastName == c.LastName) ){

                 LeadInLoop.Existing_Contact__c = TRUE;
                 LeadInLoop.Contact_Created_Date__c = c.Created_Date__c;
                 LeadInLoop.Contact_ID__c = c.Id;
                 LeadInLoop.Account_Number__c = c.Account_number__c;
                 LeadInLoop.Ship_To__c = c.Ship_To__c;
                 LeadInLoop.Contact_Company__c = c.Company__c;
                 LeadInLoop.Primary_Account_Owner__c = c.Primary_Account_Owner__c;
                 LeadInLoop.Primary_Account_Owner_ID__c = c.Primary_Account_Owner_ID__c;
                 LeadInLoop.Contact_Primary_Sales_Function__c = c.Primary_Sales_Function__c;
                 LeadInLoop.First_Order_Date__c = c.First_Order_Date__c;
                 LeadInLoop.Contact_Owner_ID__c = c.Owner.Name;
                 LeadInLoop.Turnover__c = c.Turnover__c;
                 LeadInLoop.PIN__c = c.PIN__c;
                 
              if(LeadInLoop.Lead_Created_Date__c > c.Created_Date__c){
                  if(LeadInLoop.LeadSource == 'Supplier Lead Referral'){
                      LeadInLoop.OwnerId = c.OwnerId;
                  }
              else{
                LeadInLoop.addError('Lead already exist in Contact, Ref ID : ' + c.Id);
              }
            }
            if(LeadInLoop.Lead_Created_Date__c <= c.Created_Date__c){
                if(c.Turnover__c>0.00){
                    LeadInLoop.Status = 'Order Placed';
                    LeadInLoop.Ready_to_Convert__c = TRUE;
                }
                if((c.Turnover__c <= 0.00 || c.Turnover__c== null) && (LeadInLoop.Country_code__c != 'India' || LeadInLoop.Country_code__c != 'China' || LeadInLoop.Country_code__c != 'Taiwan' || LeadInLoop.Country_code__c != 'Hong Kong'))
                       LeadInLoop.Status = 'Account created';
                }
          }
      }
    }
  }
}


Test Class
========

@isTest(SeeAllData=true)

public class APACLeadEventDedupeTest{

public static testMethod void APACLeadEventDedupeStaticTestMethod(){

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;
Id SiteID= [select Id,name from RecordType where name ='Site' limit 1].Id;
Id BillRtId = [Select Id, name from RecordType where name = 'Billing Account' limit 1].Id;
User O = [select id from user where id='00520000001Omvk' LIMIT 1];
Set<String> allLeadEmails = new Set <String> ();
Set<String> allFirstNames = new Set <String> ();
Set<String> allLastNames = new Set <String> ();
Set<String> allCompanyCodes = new Set <String> ();
Set<String> APACCompanyCodes = new Set<String>{'AU1', 'SG1', 'IN1', 'NZ1', 'CN1'};

try{
//    Test.startTest();
  {
      Account Billing = 
      new Account (
          Name='TestBillingAcc', 
          RecordTypeId=BillRtId, 
          Company__c='SG1',
          Primary_Account_Owner__c='Katherine Schuil',
          Primary_Account_Owner_ID__c='TOFFKA',
          Primary_Sales_Function__c='TeleMarketing',
          Owner = O);
      
//      insert Billing;
    
    System.debug('**Billing Account Created' + Billing.Name);
    
      Account Site = 
      new Account (
          Name='TestSiteAcc', 
          RecordTypeId=SiteId, 
          Company__c='SG1', 
          Ship_To__c = '001',
          Primary_Account_Owner__c='Katherine Schuil',
          Primary_Account_Owner_ID__c='TOFFKA',
          Primary_Sales_Function__c='TeleMarketing',
          Owner = O,
          Parent = Billing,
          Specific_Customer_Type__c='Other',
          CEM_OEM_Tier__c=1,
          Fixed_Quote_Comments__c='Testing Fixed Quote Comments');
      
//      insert Site;

    System.debug('**Site Account Created' + Site.Name);

      Contact c = 
      new Contact (
          FirstName = 'Test',
          LastName = 'Lead',
          Email = 'testinglead@element14.com',
          Account_Number__c = '12345',
          PIN__c = '064582',
          First_Order_Date__c = Date.newInstance( 2015, 2, 2 ),
          Turnover__c = 10000.00,
          Account = Site
          );
      
//      insert c;
  
      System.debug('**Contact Created' + c.FirstName );
  
      Lead l = 
      new Lead (
          FirstName ='Test', 
          LastName ='Lead', 
          Country_code__c ='Singapore',
          Company = 'SG1',
          email = 'testinglead@element14.com',
          Lead_Type__c = 'New Company',
          LeadSource = 'Supplier Lead Referral',
      RecordTypeId=rtID,
          Lead_Source_Detail_NEW__c = '3M');
          
//          insert l;
          
          Test.startTest();{insert Billing;insert Site;insert c;insert l;}
          
          
          System.debug('**Lead Created : ' + l.FirstName + ' ' + l.LastName);
          System.debug('**Lead Created : ' + l.Company_Code__c);
          
          List<Contact> ContactList = [Select Id ,Email,FirstName,LastName,Company__c,Account_Number__c,PIN__c,Ship_To__c,
                                            Created_Date__c,Primary_Account_Owner__c,Primary_Account_Owner_ID__c,Primary_Sales_Function__c,
                                            First_Order_Date__c,OwnerId,Owner.Name,Turnover__c
                                            FROM Contact WHERE Email IN: allLeadEmails AND FirstName IN: allFirstNames AND LastName IN: allLastNames AND Company__c IN: allCompanyCodes AND Id =: c.Id];
                                            
          List<Lead> NewLead = [Select Id, FirstName,  LastName, Company_Code__c, email, Existing_Contact__c,Contact_Created_Date__c,
                                          Contact_ID__c, Account_Number__c, Ship_To__c, Contact_Company__c, Primary_Account_Owner__c,
                                          Primary_Account_Owner_ID__c, Contact_Primary_Sales_Function__c, First_Order_Date__c, Contact_Owner_ID__c,
                                          Turnover__c, PIN__c FROM Lead where Id =: l.Id];
//For the triggers in the loop, add the relevant contact information.

  for (Lead LeadInLoop : NewLead) {
      for (Contact c1: ContactList){
      System.debug('Company Code in Lead Loop'+LeadInLoop.Company_Code__c);
      if(APACCompanyCodes.contains(LeadInLoop.Company_Code__c)){
      
          if((LeadInLoop.email == c1.email) && (LeadInLoop.FirstName == c1.FirstName) && (LeadInLoop.LastName == c1.LastName) ){

                 LeadInLoop.Existing_Contact__c = TRUE;
                 LeadInLoop.Contact_Created_Date__c = c1.Created_Date__c;
                 LeadInLoop.Contact_ID__c = c1.Id;
                 LeadInLoop.Account_Number__c = c1.Account_number__c;
                 LeadInLoop.Ship_To__c = c1.Ship_To__c;
                 LeadInLoop.Contact_Company__c = c1.Company__c;
                 LeadInLoop.Primary_Account_Owner__c = c1.Primary_Account_Owner__c;
                 LeadInLoop.Primary_Account_Owner_ID__c = c1.Primary_Account_Owner_ID__c;
                 LeadInLoop.Contact_Primary_Sales_Function__c = c1.Primary_Sales_Function__c;
                 LeadInLoop.First_Order_Date__c = c1.First_Order_Date__c;
                 LeadInLoop.Contact_Owner_ID__c = c1.Owner.Name;
                 LeadInLoop.Turnover__c = c1.Turnover__c;
                 LeadInLoop.PIN__c = c1.PIN__c;
                 
              if(LeadInLoop.Lead_Created_Date__c > c1.Created_Date__c){
                  if(LeadInLoop.LeadSource == 'Supplier Lead Referral'){
                      LeadInLoop.OwnerId = c1.OwnerId;
                  }
              else{
                LeadInLoop.addError('Lead already exist in Contact, Ref ID : ' + c1.Id);
              }
            }
            
            System.debug('******@ After Lead Check *****');
            
            if(LeadInLoop.Lead_Created_Date__c <= c1.Created_Date__c){
                if(c1.Turnover__c>0.00){
                    LeadInLoop.Status = 'Order Placed';
                    LeadInLoop.Ready_to_Convert__c = TRUE;
                }
                
                System.debug('******@ Lead Status Update - Order Placed*****');
                
                if((c1.Turnover__c <= 0.00 || c1.Turnover__c== null) && (LeadInLoop.Country_code__c != 'India' || LeadInLoop.Country_code__c != 'China' || LeadInLoop.Country_code__c != 'Taiwan' || LeadInLoop.Country_code__c != 'Hong Kong'))
                       LeadInLoop.Status = 'Account created';
                }
                
                System.debug('******@ Lead Status Update - Account Created*****');
          }
      }
      }
  }
 }

} catch (Exception e) {
    system.assertEquals('********* Error Found ********', e.getMessage());
    System.debug('******@ Exception*****');

 Test.stopTest();
 System.debug('******End of Test*****');
}

}
Hi,

I have created trigger with hardcoding.
i want that to work dynamically.
Because, Recordtype Ids are different in Production and sandbox.

Kindly help me where i have to make changes exactly.

Following is my trigger code.
=========================================================================

trigger APACLeadExactTargetEmails on xtma_Individual_Email_Result__c (after insert, after update)
{
    
     set<Id> LeadRts = new Set<Id>{'012200000005uXiAAI','0127E000000CgrLQAS','0127E000000CgqNQAS'};

//    Id rtID= [select Id,name from RecordType where name ='APAC - Open'OR name ='Global Abandoned Checkout' OR name = 'Global New Web Registrant' limit 1].Id;

    Set<String> setIDs = new Set<String>();

    for(xtma_Individual_Email_Result__c Emails : trigger.new){
        if(Emails.Lead__c!=null){
            setIDs.add(Emails.Lead__c);
        }
    }

    List<lead> listLead = [ Select Id FROM Lead where RecordTypeId in :LeadRts AND id in :setIDs ] ;
    Map<String,Lead> mapKeyWiseLead = new Map<String,Lead>();
        for(Lead obj :  listLead )
        {
            String key = obj.id;
            mapKeyWiseLead.put(key,obj);
        }
        
    List<Lead> listUpdatelead = new List<Lead>();
    Set<String> setLeadID = new Set<String>();
    
    String key;
    for(xtma_Individual_Email_Result__c Emails : trigger.new)
    {
        key='';
        if(Emails.Lead__c!=null){
            key=Emails.Lead__c;
            
            if( mapKeyWiseLead.containsKey(key) )
            {
                Lead checkLead = mapKeyWiseLead.get(Key) ;
                
               if(emails.name.contains('1st Newsletter - EDE')) 
                {
                    checkLead.X1st_Email_Date__c= Emails.Date_Time_Sent__c.Date();

                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==FALSE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X1st_Email_Outcome__c = 'Sent';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X1st_Email_Outcome__c = 'Opened';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c>0){
                        checkLead.X1st_Email_Outcome__c = 'Clicked';
                        }
                       if(emails.name=='1st Newsletter - EDE'){checkLead.X1st_Email_Name__c = '1st Newsletter - EDE';
                    }
                        listUpdatelead.add(checkLead);
                        setLeadID.add(checkLead.id);
                }
                if(emails.name.contains('2nd Newsletter - EDE'))
                {
                    checkLead.X2nd_Email_Date__c= Emails.Date_Time_Sent__c.Date();

                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==FALSE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X2nd_Email_Outcome__c = 'Sent';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X2nd_Email_Outcome__c = 'Opened';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c>0){
                        checkLead.X2nd_Email_Outcome__c = 'Clicked';
                        }
                       if(emails.name=='2nd Newsletter - EDE'){checkLead.X2nd_Email_Name__c = '2nd Newsletter - EDE';
                    }
                        listUpdatelead.add(checkLead);
                        setLeadID.add(checkLead.id);
                }
                if(emails.name.contains('3rd Newsletter - EDE')) 
                {
                    checkLead.X3rd_Email_Date__c= Emails.Date_Time_Sent__c.Date();

                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==FALSE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X3rd_Email_Outcome__c = 'Sent';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c==null){
                        checkLead.X3rd_Email_Outcome__c = 'Opened';
                    }
                    if(Emails.Date_Time_Sent__c!=null && Emails.Opened__c==TRUE && Emails.Number_of_Total_Clicks__c>0){
                        checkLead.X3rd_Email_Outcome__c = 'Clicked';
                        }
                       if(emails.name=='3rd Newsletter - EDE'){checkLead.X3rd_Email_Name__c = '3rd Newsletter - EDE';
                    }
                        listUpdatelead.add(checkLead);
                        setLeadID.add(checkLead.id);
                }
                
            }
        }
    }
        if( listUpdatelead.size() > 0 )
        {
                try
                    {
                        update listUpdatelead;            
                    }
                catch(DMLException e)
                {  
                    System.debug('The following exception has occurred: ' + e.getMessage());
                }
        }
}

Regards,
Pranav

Hi,

My requirement is as follows

1) The Trigger should update the existing lead with updated Lead Creation Date, lead source and lead source detail if found with same details like first name, last name, email, country and leadsource and leadsource details are not same, Should not insert new record.
2) if lead source and lead source details are also same then through error (Stop inserting new record).
3) if no matching found then insert the record.

I have written the following trigger, which is not working.

am getting follwoing error : 
Apex trigger APACLeadDuplicateofExistingLead caused an unexpected exception, contact your administrator: APACLeadDuplicateofExistingLead: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.APACLeadDuplicateofExistingLead: line 9, column 1

please help as soon as possible.

//Trigger for APAC Region – Managing Duplicate Leads of Existing Lead

trigger APACLeadDuplicateofExistingLead on Lead (before insert)
{
        Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

         for(Lead l:Trigger.new)
         {
                Lead lid = [select ID from Lead where FirstName =: l.Name and LastName =: l.LastName and Email =: l.Email and Country_code__c =: l.Country_code__c and RecordTypeId =: rtID limit 1];

                if(l.LeadSource!= lid.LeadSource || l.Lead_Source_Detail_NEW__c != lid.Lead_Source_Detail_NEW__c )
                {
                    Lead updateLead =[select id from lead where id =: lid.id];
                    
                    updateLead.Lead_Creation_Date__c=System.Today();
                    updateLead.LeadSource=l.LeadSource;
                    updateLead.Lead_Source_Detail_NEW__c=l.Lead_Source_Detail_NEW__c;
                    
                    update updateLead;

                    l.addError('Lead already exist with same details, Lead Id : ' + lid.id);
                }
                if(l.LeadSource== lid.LeadSource && l.Lead_Source_Detail_NEW__c == lid.Lead_Source_Detail_NEW__c )
                {
                    l.addError('Lead already exist with same details, Lead Id : ' + lid.id);
                }
         }
}

Hi I have tried to create a trigger to Lead Dedupe Management.
It worked perfectly when i inserted single record.
but when i upload through data loader am getting this error.

following is my code. Can any one help in createing the same for bulk inserts of lead through data loader.

==================================================================================
trigger LeadEventDedupeTestTrigger on Lead (before insert, before update)  {

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

    for(Integer i=0;i<Trigger.new.size();i++){
            if(Trigger.new[i].Email !=null && Trigger.new[i].FirstName !=null && Trigger.new[i].LastName !=null){
                Contact ContactList = [Select Id ,Email,FirstName,LastName,Company__c,Account_Number__c,PIN__c,Ship_To__c,
                                            Created_Date__c,Primary_Account_Owner__c,Primary_Account_Owner_ID__c,Primary_Sales_Function__c,
                                            First_Order_Date__c,OwnerId,Owner.Name,Turnover__c
                                            FROM Contact WHERE Email =: Trigger.new[i].Email AND FirstName =: Trigger.new[i].FirstName AND LastName =: Trigger.new[i].LastName]; 
                {
                    Trigger.new[i].Existing_Contact__c = TRUE;
                    Trigger.new[i].Contact_Created_Date__c = ContactList.Created_Date__c;
                    Trigger.new[i].Contact_ID__c = ContactList.Id;
                    Trigger.new[i].Account_Number__c = ContactList.Account_number__c;
                    Trigger.new[i].Ship_To__c = ContactList.Ship_To__c;
                    Trigger.new[i].Contact_Company__c = ContactList.Company__c;
                    Trigger.new[i].Primary_Account_Owner__c = ContactList.Primary_Account_Owner__c;
                    Trigger.new[i].Primary_Account_Owner_ID__c = ContactList.Primary_Account_Owner_ID__c;
                    Trigger.new[i].Contact_Primary_Sales_Function__c = ContactList.Primary_Sales_Function__c;
                    Trigger.new[i].First_Order_Date__c = ContactList.First_Order_Date__c;
                    Trigger.new[i].Contact_Owner_ID__c = ContactList.Owner.Name;
                    Trigger.new[i].Turnover__c = ContactList.Turnover__c;
                    Trigger.new[i].PIN__c = ContactList.PIN__c;
                    
                    if(Trigger.new[i].Lead_Created_Date__c > ContactList.Created_Date__c){
                  if(Trigger.new[i].LeadSource == 'Supplier Lead Referral' || Trigger.new[i].LeadSource == 'Supplier Live Inquiry'){
                      Trigger.new[i].OwnerId = ContactList.OwnerId;
                  }
              else{
                Trigger.new[i].addError('Lead already exist as a Contact, Account Number : ' + ContactList.Account_number__c + ' / PIN : ' + ContactList.PIN__c + '/ Contact ID : ' + ContactList.Id);
              }
                }
            }
        }
    }
}

Hi,

I want to update leads based on criteria once after the contact is insereted. This trigger is not working for my bulk inserts or updates. Am getting error 'System.LimitException: Too many SOQL queries: 101'. Can anyone help me out ?
There is other trigger on leads which will tag the contact details on lead object fields when lead is inserted or updated.
I suppose to deliver this by this friday, Very Urgent.


Trigger updateLeads1 on Contact (after insert, after update) {

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

        for(Contact myContact : Trigger.new){
            if(myContact.email != null && myContact.FirstName != null && myContact.LastName != null) {
              for(Lead checkLead : [Select Id, FirstName, LastName, Email, Status, Ready_to_Convert__c, Country_code__c FROM Lead where RecordTypeId = :rtId AND Email = :myContact.Email AND FirstName = :myContact.FirstName AND LastName = :myContact.LastName limit 1]){
                    if(myContact.Turnover__c > 0.00){
                    updatelead(checkLead.id);
                }
             if((myContact.Turnover__c <= 0.00 || myContact.Turnover__c== null) && (checkLead.Country_code__c != 'India' || checkLead.Country_code__c != 'China' || checkLead.Country_code__c != 'Taiwan' || checkLead.Country_code__c != 'Hong Kong')){
                    updatelead1(checkLead.id);
                    }
                }
          }
    }
    
    public static void updatelead(Id leadId) {
    System.debug('Lead ID : '+ leadId);
    lead ld = [SELECT id FROM lead WHERE ID = :leadId];
    system.debug('Lead ID in Query :'+ld);
    ld.Status = 'Order Placed';
    ld.Ready_to_Convert__c = TRUE;
    try {
        update ld;             
        } catch(DMLException e) {   
        System.debug('The following exception has occurred: ' + e.getMessage()); 
        }
}

    public static void updatelead1(Id leadId) {
    System.debug('Lead ID : '+ leadId);
    lead ld = [SELECT id FROM lead WHERE ID = :leadId];
    system.debug('Lead ID in Query :'+ld);
    ld.Status = 'Account created';
    try {
        update ld;             
        } catch(DMLException e) {   
        System.debug('The following exception has occurred: ' + e.getMessage()); 
        }
    }
}

Regards,
Pranav

Can anyone please let me know, why am not able to get 100% code coverage.

Trigger
======

// Trigger for APAC Region - to find Lead & Contact Duplicate

trigger APACLeadEventDedupe on Lead (before insert, before update) {

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;

Set<String> allLeadEmails = new Set <String> ();
Set<String> allFirstNames = new Set <String> ();
Set<String> allLastNames = new Set <String> ();
Set<String> allCompanyCodes = new Set <String> ();
Set<String> APACCompanyCodes = new Set<String>{'AU1', 'SG1', 'IN1', 'NZ1', 'CN1'};

       
            if(newlead.email != null && newlead.FirstName != null && newlead.LastName != null && newlead.Company_Code__c != null && newlead.RecordTypeId == rtId ) {
                allLeadEmails.add(newlead.email);
                allFirstNames.add(newlead.FirstName);
                allLastNames.add(newlead.LastName);
                allCompanyCodes.add(newlead.Company_Code__c);
                }
    }

//Step 2: Query for All Contact Records in Step 1


    List<Contact> ContactList = [Select Id ,Email,FirstName,LastName,Company__c,Account_Number__c,PIN__c,Ship_To__c,
                                            Created_Date__c,Primary_Account_Owner__c,Primary_Account_Owner_ID__c,Primary_Sales_Function__c,
                                            First_Order_Date__c,OwnerId,Owner.Name,Turnover__c
                                            FROM Contact WHERE Email IN: allLeadEmails AND FirstName IN: allFirstNames AND LastName IN: allLastNames AND Company__c IN: allCompanyCodes]; // AND RecordTypeId=:ContactRtId];
                                            
    System.debug('After query  -values in Where Clause   allLeadEmails '+allLeadEmails );  
          System.debug('After query  -values in Where Clause   allFirstNames '+allFirstNames );  
                System.debug('After query  -values in Where Clause   allLastNames '+allLastNames );
                           System.debug('After query  -values in Where Clause   allCompanyCodes '+allCompanyCodes );  
  
      System.debug('After query  - ContactList '+ContactList );                                      

//For the triggers in the loop, add the relevant contact information.

        
  for (Lead LeadInLoop : Trigger.new) {
      System.debug('---> Line No : 53 <---');
      System.debug('---> Line No : 54 <---'+ContactList);
     for (Contact c: ContactList){
          String companyCode = LeadInLoop.Company_Code__c;
          System.debug('******Company Code is : '+ LeadInLoop.Company_Code__c );
          if(APACCompanyCodes.contains(LeadInLoop.Company_Code__c)){
          System.debug('******Company Code Inserted as : '+ LeadInLoop.Company_Code__c );
          if((LeadInLoop.email == c.email) && (LeadInLoop.FirstName == c.FirstName) && (LeadInLoop.LastName == c.LastName) ){

                 LeadInLoop.Existing_Contact__c = TRUE;
                 LeadInLoop.Contact_Created_Date__c = c.Created_Date__c;
                 LeadInLoop.Contact_ID__c = c.Id;
                 LeadInLoop.Account_Number__c = c.Account_number__c;
                 LeadInLoop.Ship_To__c = c.Ship_To__c;
                 LeadInLoop.Contact_Company__c = c.Company__c;
                 LeadInLoop.Primary_Account_Owner__c = c.Primary_Account_Owner__c;
                 LeadInLoop.Primary_Account_Owner_ID__c = c.Primary_Account_Owner_ID__c;
                 LeadInLoop.Contact_Primary_Sales_Function__c = c.Primary_Sales_Function__c;
                 LeadInLoop.First_Order_Date__c = c.First_Order_Date__c;
                 LeadInLoop.Contact_Owner_ID__c = c.Owner.Name;
                 LeadInLoop.Turnover__c = c.Turnover__c;
                 LeadInLoop.PIN__c = c.PIN__c;
                 
              if(LeadInLoop.Lead_Created_Date__c > c.Created_Date__c){
                  if(LeadInLoop.LeadSource == 'Supplier Lead Referral'){
                      LeadInLoop.OwnerId = c.OwnerId;
                  }
              else{
                LeadInLoop.addError('Lead already exist in Contact, Ref ID : ' + c.Id);
              }
            }
            if(LeadInLoop.Lead_Created_Date__c <= c.Created_Date__c){
                if(c.Turnover__c>0.00){
                    LeadInLoop.Status = 'Order Placed';
                    LeadInLoop.Ready_to_Convert__c = TRUE;
                }
                if((c.Turnover__c <= 0.00 || c.Turnover__c== null) && (LeadInLoop.Country_code__c != 'India' || LeadInLoop.Country_code__c != 'China' || LeadInLoop.Country_code__c != 'Taiwan' || LeadInLoop.Country_code__c != 'Hong Kong'))
                       LeadInLoop.Status = 'Account created';
                }
          }
      }
    }
  }
}


Test Class
========

@isTest(SeeAllData=true)

public class APACLeadEventDedupeTest{

public static testMethod void APACLeadEventDedupeStaticTestMethod(){

Id rtID= [select Id,name from RecordType where name ='APAC - Open' limit 1].Id;
Id SiteID= [select Id,name from RecordType where name ='Site' limit 1].Id;
Id BillRtId = [Select Id, name from RecordType where name = 'Billing Account' limit 1].Id;
User O = [select id from user where id='00520000001Omvk' LIMIT 1];
Set<String> allLeadEmails = new Set <String> ();
Set<String> allFirstNames = new Set <String> ();
Set<String> allLastNames = new Set <String> ();
Set<String> allCompanyCodes = new Set <String> ();
Set<String> APACCompanyCodes = new Set<String>{'AU1', 'SG1', 'IN1', 'NZ1', 'CN1'};

try{
//    Test.startTest();
  {
      Account Billing = 
      new Account (
          Name='TestBillingAcc', 
          RecordTypeId=BillRtId, 
          Company__c='SG1',
          Primary_Account_Owner__c='Katherine Schuil',
          Primary_Account_Owner_ID__c='TOFFKA',
          Primary_Sales_Function__c='TeleMarketing',
          Owner = O);
      
//      insert Billing;
    
    System.debug('**Billing Account Created' + Billing.Name);
    
      Account Site = 
      new Account (
          Name='TestSiteAcc', 
          RecordTypeId=SiteId, 
          Company__c='SG1', 
          Ship_To__c = '001',
          Primary_Account_Owner__c='Katherine Schuil',
          Primary_Account_Owner_ID__c='TOFFKA',
          Primary_Sales_Function__c='TeleMarketing',
          Owner = O,
          Parent = Billing,
          Specific_Customer_Type__c='Other',
          CEM_OEM_Tier__c=1,
          Fixed_Quote_Comments__c='Testing Fixed Quote Comments');
      
//      insert Site;

    System.debug('**Site Account Created' + Site.Name);

      Contact c = 
      new Contact (
          FirstName = 'Test',
          LastName = 'Lead',
          Email = 'testinglead@element14.com',
          Account_Number__c = '12345',
          PIN__c = '064582',
          First_Order_Date__c = Date.newInstance( 2015, 2, 2 ),
          Turnover__c = 10000.00,
          Account = Site
          );
      
//      insert c;
  
      System.debug('**Contact Created' + c.FirstName );
  
      Lead l = 
      new Lead (
          FirstName ='Test', 
          LastName ='Lead', 
          Country_code__c ='Singapore',
          Company = 'SG1',
          email = 'testinglead@element14.com',
          Lead_Type__c = 'New Company',
          LeadSource = 'Supplier Lead Referral',
      RecordTypeId=rtID,
          Lead_Source_Detail_NEW__c = '3M');
          
//          insert l;
          
          Test.startTest();{insert Billing;insert Site;insert c;insert l;}
          
          
          System.debug('**Lead Created : ' + l.FirstName + ' ' + l.LastName);
          System.debug('**Lead Created : ' + l.Company_Code__c);
          
          List<Contact> ContactList = [Select Id ,Email,FirstName,LastName,Company__c,Account_Number__c,PIN__c,Ship_To__c,
                                            Created_Date__c,Primary_Account_Owner__c,Primary_Account_Owner_ID__c,Primary_Sales_Function__c,
                                            First_Order_Date__c,OwnerId,Owner.Name,Turnover__c
                                            FROM Contact WHERE Email IN: allLeadEmails AND FirstName IN: allFirstNames AND LastName IN: allLastNames AND Company__c IN: allCompanyCodes AND Id =: c.Id];
                                            
          List<Lead> NewLead = [Select Id, FirstName,  LastName, Company_Code__c, email, Existing_Contact__c,Contact_Created_Date__c,
                                          Contact_ID__c, Account_Number__c, Ship_To__c, Contact_Company__c, Primary_Account_Owner__c,
                                          Primary_Account_Owner_ID__c, Contact_Primary_Sales_Function__c, First_Order_Date__c, Contact_Owner_ID__c,
                                          Turnover__c, PIN__c FROM Lead where Id =: l.Id];
//For the triggers in the loop, add the relevant contact information.

  for (Lead LeadInLoop : NewLead) {
      for (Contact c1: ContactList){
      System.debug('Company Code in Lead Loop'+LeadInLoop.Company_Code__c);
      if(APACCompanyCodes.contains(LeadInLoop.Company_Code__c)){
      
          if((LeadInLoop.email == c1.email) && (LeadInLoop.FirstName == c1.FirstName) && (LeadInLoop.LastName == c1.LastName) ){

                 LeadInLoop.Existing_Contact__c = TRUE;
                 LeadInLoop.Contact_Created_Date__c = c1.Created_Date__c;
                 LeadInLoop.Contact_ID__c = c1.Id;
                 LeadInLoop.Account_Number__c = c1.Account_number__c;
                 LeadInLoop.Ship_To__c = c1.Ship_To__c;
                 LeadInLoop.Contact_Company__c = c1.Company__c;
                 LeadInLoop.Primary_Account_Owner__c = c1.Primary_Account_Owner__c;
                 LeadInLoop.Primary_Account_Owner_ID__c = c1.Primary_Account_Owner_ID__c;
                 LeadInLoop.Contact_Primary_Sales_Function__c = c1.Primary_Sales_Function__c;
                 LeadInLoop.First_Order_Date__c = c1.First_Order_Date__c;
                 LeadInLoop.Contact_Owner_ID__c = c1.Owner.Name;
                 LeadInLoop.Turnover__c = c1.Turnover__c;
                 LeadInLoop.PIN__c = c1.PIN__c;
                 
              if(LeadInLoop.Lead_Created_Date__c > c1.Created_Date__c){
                  if(LeadInLoop.LeadSource == 'Supplier Lead Referral'){
                      LeadInLoop.OwnerId = c1.OwnerId;
                  }
              else{
                LeadInLoop.addError('Lead already exist in Contact, Ref ID : ' + c1.Id);
              }
            }
            
            System.debug('******@ After Lead Check *****');
            
            if(LeadInLoop.Lead_Created_Date__c <= c1.Created_Date__c){
                if(c1.Turnover__c>0.00){
                    LeadInLoop.Status = 'Order Placed';
                    LeadInLoop.Ready_to_Convert__c = TRUE;
                }
                
                System.debug('******@ Lead Status Update - Order Placed*****');
                
                if((c1.Turnover__c <= 0.00 || c1.Turnover__c== null) && (LeadInLoop.Country_code__c != 'India' || LeadInLoop.Country_code__c != 'China' || LeadInLoop.Country_code__c != 'Taiwan' || LeadInLoop.Country_code__c != 'Hong Kong'))
                       LeadInLoop.Status = 'Account created';
                }
                
                System.debug('******@ Lead Status Update - Account Created*****');
          }
      }
      }
  }
 }

} catch (Exception e) {
    system.assertEquals('********* Error Found ********', e.getMessage());
    System.debug('******@ Exception*****');

 Test.stopTest();
 System.debug('******End of Test*****');
}

}