• Jason Adler 9
  • NEWBIE
  • 20 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 3
    Replies
It was previously working correctly at 80% coverage. I've since made changes to the trigger and now its at 66%. The changes are the addition of a US_zip_code__c checkbox. Previously the trigger could only assign to UserAssigned or User2 and now we can also assign to Mex CB RSM or Mex WH RSM. I commented out the continue line as marked in the code and added the two new user fields (Mex CB RSM and Mex WH RSM) to the query in order to grab this information to use.
Anybody good at writing test classes that can help?

Trigger:
trigger LeadAssignOwnerByPostalCode on Lead (before insert, before update) {

    List<Lead> lList = new List<Lead>();
   
    Map<String,Zip_Code__c> zipCodeMap = new Map<String,Zip_Code__c>();
    
    Map<id, User> userMap = new Map<id, User>();
    
    Set<String> userIds = new Set<String>();
    
    Set<String> zipCodeString = new Set<String>();
    
    List<Zip_Code__c> zipCodeList = new List<Zip_Code__c>();
    
    List<Messaging.SingleEmailMessage> listmail = new List<Messaging.SingleEmailMessage>(); 

   
    for(Lead l: Trigger.new)
    {       
         if (l.Do_Not_Apply_Zip_Assignment_Rules__c == false && (l.LeadSource == 'WPP-2020' || l.LeadSource == '346 Leasing - 2020' || l.LeadSource == '1219 Leasing - 2020' || l.LeadSource == 'Hydro Leasing - 2020' || l.LeadSource == 'Chatbot')){
    
        System.debug('LeadAssignmentByZipCode -- Do_Not_Use_ZipAssignment_del__c ' + l.Do_Not_Apply_Zip_Assignment_Rules__c);
        
      
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(l.id);
            //CHANGE****NOW COMMENTED OUT***:if(l.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(l.PostalCode <> null){
            zipCodeString.add(l.PostalCode);
            System.debug('LeadAssignmentByZipCode -- Lead -- ' + l.Name + ' Zip -- ' + l.PostalCode);
                
        }
    }
    }
    if(!zipCodeString.IsEmpty())
    {
        System.debug('LeadAssignmentByZipCode -- Leads To Process ' + zipCodeString.size());
        zipCodeList = [SELECT  id, Name, UserAssigned__c, User2__c, Mex_WH_RSM__c, Mex_CB_RSM__c,  Dealer_Lead_Email_Address__c  FROM Zip_Code__c WHERE Name IN: zipCodeString ];
        
    } else{
        System.debug('LeadAssignmentByZipCode -- No Leads To Process');
    }
    
    
    if(!zipCodeString.IsEmpty()){
        
        System.debug('LeadAssignByZip --- zipCodeString Count --> ' + zipCodeString.size());
        
        
        for(Zip_Code__c z: zipCodeList){
            
            if(!zipCodeMap.containsKey(z.Name)){
                zipCodeMap.put(z.name, z);
                userIds.add(z.UserAssigned__c);
            }
            
        }
    }else
        System.debug('LeadAssignByZip --- zipCodeString Count --> zero');
         
        
    if(!userIds.IsEmpty()){
        
        System.debug('LeadAssignByZip --- userIds Count --> ' + userIds.size());
        userMap = new Map<id,User>([SELECT id, email FROM User WHERE id IN: userIDs]);
        
    }else
        System.debug('LeadAssignByZip --- userIds Count --> zero');
            

    for(Lead lead: Trigger.New) {
        
     
        if (lead.Do_Not_Apply_Zip_Assignment_Rules__c == false && (lead.LeadSource == 'WPP-2020' || lead.LeadSource == '346 Leasing - 2020' || lead.LeadSource == '1219 Leasing - 2020' || lead.LeadSource == 'Hydro Leasing - 2020' || lead.LeadSource == 'Chatbot')){
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(lead.id);
            //if(lead.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        //CHANGES****Added logic to handle a US_Zip_Code__c field and two new users that can be assigned as owner***
        if(zipCodeMap.containsKey(lead.PostalCode)){
        if(lead.US_Zip_Code__c == true){
        
          //  Id owner = zipCodeMap.get(lead.PostalCode).UserAssigned__c;
          //  lead.OwnerId = owner;
            
           Id owner;
           Zip_Code__c zipCode = zipCodeMap.get(lead.PostalCode);

          if(lead.LeadSource == 'WPP-2020' || lead.LeadSource == '346 Leasing - 2020'){
              if(zipCode.user2__c != null) {
                owner = zipCode.User2__c;
                }
              else {
                owner = zipCode.UserAssigned__c;
                } 
          }
         
          else {
              if(zipCode.UserAssigned__c != null) {
                owner = zipCode.UserAssigned__c;
               }
        
              else {
               owner = zipCode.User2__c;
              }
              }
          lead.OwnerId = owner;
         
            
            lead.Dealer_Lead_Person__c = zipCodeMap.get(lead.PostalCode).Dealer_Lead_Email_Address__c;
            
            }
            
            else{
        
        
          //  Id owner = zipCodeMap.get(lead.PostalCode).UserAssigned__c;
          //  lead.OwnerId = owner;
            
           Id owner;
           Zip_Code__c zipCode = zipCodeMap.get(lead.PostalCode);

          if(lead.LeadSource == 'WPP-2020' || lead.LeadSource == '346 Leasing - 2020'){
              if(zipCode.Mex_WH_RSM__c != null) {
                owner = zipCode.Mex_WH_RSM__c;
                }
              else {
                owner = zipCode.Mex_CB_RSM__c;
                } 
          }
         
          else {
              if(zipCode.UserAssigned__c != null) {
                owner = zipCode.Mex_CB_RSM__c;
               }
        
              else {
               owner = zipCode.Mex_WH_RSM__c;
              }
              }
          lead.OwnerId = owner;
         
            
            lead.Dealer_Lead_Person__c = zipCodeMap.get(lead.PostalCode).Dealer_Lead_Email_Address__c;
            
            }
            }
            }
           }}

Test Class:
 
@isTest(SeeAllData=true)
private class TestLeadAssignmentByZipCode {

    static testMethod void testLeadAssignedByZipCode() {

        try{
            
            test.startTest();
            
            Zip_Code__c  zip = new ZIP_Code__c();
            zip.Name = '20716';
            zip.UserAssigned__c = UserInfo.getUserId();
            
            insert zip;
            
            Lead lead = new Lead();
            
            lead.FirstName = 'James';
            lead.Company = 'Acme';
            lead.Street = '100 West Street';
            lead.City = 'Marlboro';
            lead.State = 'MD';
            lead.PostalCode = '20716';
            lead.LeadSource = 'WPP-2020';
            insert lead;
            
            lead.PostalCode = '20710';
            
            
            update lead;
            
            String s2 = CheckOrganizationID.getServer();
                        
           
            
            test.stopTest();
            
            
            
            
        }catch (Exception e){
        
            System.Debug('Error While Testing testLeadAssignedByZipCode');
            
        }           

    }
}

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

    List<Lead> lList = new List<Lead>();
    
   
    Map<String,Zip_Code__c> zipCodeMap = new Map<String,Zip_Code__c>();
    
    Map<id, User> userMap = new Map<id, User>();
    
    Set<String> userIds = new Set<String>();
    
    Set<String> zipCodeString = new Set<String>();
    
    List<Zip_Code__c> zipCodeList = new List<Zip_Code__c>();
    
    List<Messaging.SingleEmailMessage> listmail = new List<Messaging.SingleEmailMessage>(); 

    for(Lead l: Trigger.new)
    {       
        
        System.debug('LeadAssignmentByZipCode -- Do_Not_Use_ZipAssignment_del__c ' + l.Do_Not_Apply_Zip_Assignment_Rules__c);
        
        //Do_Not_Use_ZipAssignment_del__c
        if(l.Do_Not_Apply_Zip_Assignment_Rules__c == true || l.LeadSource != 'Lead from Hubspot') continue;
        
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(l.id);
            if(l.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(l.PostalCode <> null){
            zipCodeString.add(l.PostalCode);
            System.debug('LeadAssignmentByZipCode -- Lead -- ' + l.Name + ' Zip -- ' + l.PostalCode);
                
        }
    }
    
    if(!zipCodeString.IsEmpty())
    {
        System.debug('LeadAssignmentByZipCode -- Leads To Process ' + zipCodeString.size());
      
        zipCodeList = [SELECT  id, Name, UserAssigned__c, Dealer_Lead_Email_Address__c  FROM Zip_Code__c WHERE Name IN: zipCodeString ];
        
    } else{
        System.debug('LeadAssignmentByZipCode -- No Leads To Process');
    }
    
    
    if(!zipCodeString.IsEmpty()){
        
        System.debug('LeadAssignByZip --- zipCodeString Count --> ' + zipCodeString.size());
        
        
        for(Zip_Code__c z: zipCodeList){
            
            if(!zipCodeMap.containsKey(z.Name)){
                zipCodeMap.put(z.name, z);
                userIds.add(z.UserAssigned__c);
            }
            
        }
    }else
        System.debug('LeadAssignByZip --- zipCodeString Count --> zero');
         
        
    if(!userIds.IsEmpty()){
        
        System.debug('LeadAssignByZip --- userIds Count --> ' + userIds.size());
        userMap = new Map<id,User>([SELECT id, email FROM User WHERE id IN: userIDs]);
        
    }else
        System.debug('LeadAssignByZip --- userIds Count --> zero');
            

    for(Lead lead: Trigger.New) {
        
        if(lead.Do_Not_Apply_Zip_Assignment_Rules__c == true) continue;
        
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(lead.id);
            if(lead.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(zipCodeMap.containsKey(lead.PostalCode)){
            
            Id owner = zipCodeMap.get(lead.PostalCode).UserAssigned__c;
            lead.OwnerId = owner;
            
        
            lead.Dealer_Lead_Person__c = zipCodeMap.get(lead.PostalCode).Dealer_Lead_Email_Address__c;
            //Added by Abhishek : End
            }
            }

}

And here is the current test class:
 
@isTest(SeeAllData=true)
private class TestLeadAssignmentByZipCode {

    static testMethod void testLeadAssignedByZipCode() {

        try{
            
            test.startTest();
            
            Zip_Code__c  zip = new ZIP_Code__c();
            zip.Name = '20716';
            zip.UserAssigned__c = UserInfo.getUserId();
            
            insert zip;
            
            Lead lead = new Lead();
            
            lead.FirstName = 'James';
            lead.Company = 'Acme';
            lead.Street = '100 West Street';
            lead.City = 'Marlboro';
            lead.State = 'MD';
            lead.PostalCode = '20716';
            
            insert lead;
            
            lead.PostalCode = '20710';
            
            
            update lead;
            
            String s2 = CheckOrganizationID.getServer();
            
            test.stopTest();
            
            
            
            
        }catch (Exception e){
        
            System.Debug('Error While Testing testLeadAssignedByZipCode');
            
        }           

    }
}

I'm stuck at 51%, can anyone help?
Can anyone help to write a test class for the SaveAsPdfExtension seen here (https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_print_as_pdf_button.htm):

public class SaveAsPdfExtension {

    // Required extension constructor (empty, no-op)
    public SaveAsPDFExtension(ApexPages.StandardController controller) {}
    
    // Determines what kind of rendering to use for the page request
    public String renderingService { get; private set; }
    
    // Allow the page to set the PDF file name
    public String renderedFileName {
        get;
        set { renderedFileName = this.sanitizeFileName(value); }
    }

    // Rendered content MIME type, used to affect HTTP response
    public String renderedContentType {
        get {
            String renderedContentType = 'text/html'; // the default
            
            if( ! this.renderingAsHtml() ) {
                // Provides a MIME type for a PDF document
                renderedContentType = 'application/pdf';
                
                // Add a file name for the PDF file
                if( this.renderedFileName != null) {
                    // This is supposed to set the file name, but it doesn't work
                    renderedContentType += '#' + this.renderedFileName;
                    
                    // This is a work-around to set the file name
                    ApexPages.currentPage().getHeaders().put(
                        'content-disposition', 'attachment; filename=' +
                         this.renderedFileName);
                }
            }
            
            return renderedContentType;
        }
    }
    
    // Are we rendering to HTML or PDF?
    public Boolean renderingAsHtml() {
        return ( (renderingService == null) ||
                 ( ! renderingService.startsWith('PDF')) );
    }

    // Action method to save (or "print") to PDF
    public PageReference saveToPdf() {
        renderingService = 'PDF';
        return null;
    }
    
    // Private helper -- basic, conservative santization
    private String sanitizeFileName(String unsafeName) {
        String allowedCharacters = '0-9a-zA-Z-_.';
        String sanitizedName =
            unsafeName.replaceAll('[^' + allowedCharacters + ']', '');
        // You might also want to check filename length,
        // that the filename ends in '.pdf', etc.
        return(sanitizedName);
    }
}
 
The visualforce code is copied below...I was under impression that the renderAs="pdf" should have default save ability. On my community page, I am using a feed publisher attached to action that calls visualforce page which renders pdf. The save button is greyed out. How do I add functionality to this save button, or use a workaround? I need to offer my community user ability to save their pdf to their local machine.

save button greyed out


<apex:page standardController="Case" renderAs="pdf" applyBodyTag="false"> <head> <style> body { font-family: 'Arial Unicode MS'; } .companyName { font: bold 10px; color: black; text-overflow:hidden; overflow:hidden} .finePrint {font: 8px; color: black;} .redPrint { font: bold 14px; color: red; text-overflow:hidden; overflow:hidden} <apex:outputPanel layout="none" rendered="{!IF(Case.Existing_Residual_Cap_Calculation_N__r.Status__c == 'Estimated', true, false)}"> .watermark { background-repeat: repeat; background-image: url("{!URLFOR($Resource.watermark_estimated)}"); } </apex:outputPanel> <apex:outputPanel layout="none" rendered="{!IF(Case.Existing_Residual_Cap_Calculation_N__r.Status__c == 'Canceled / Rejected', true, false)}"> .watermark { background-repeat: repeat; background-image: url("{!URLFOR($Resource.rejected_watermark)}"); } </apex:outputPanel> table {border-collapse:collapse; table-layout:fixed; } table td {border:solid 1px ; border-color: white; font: bold 13px; color: black; word-wrap:break-word;} </style> </head> <body class="watermark"> <!-- set length of text output <apex:variable var="c" value="{!23}" /> <apex:variable var="c2" value="{!26}" />--> <apex:variable var="c" value="{!23}" /> <apex:variable var="c2" value="{!34}" /> <div align="right"> <apex:image url="{!$Resource.KNA_Logo}" style="float:right;width:25%; height:60px; margin:10px" /></div> <h2 align="right">Reduced Capacity Request Report (RCR)</h2> <!-- <br /> --> <h3>Basic Information Section</h3> <table> <tr > <td width="110px"><apex:outputText value="{!LEFT("Case No.",c)}"/></td> <td width="230px"><apex:outputText value="{!LEFT(Case.CaseNumber,c2)}"/></td> <td width="110px"><apex:outputText value="{!LEFT("Calculation No.",c)}" styleclass="redPrint"/></td> <td width="230px"><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Calculation_No__c,c2)}" styleclass="redPrint"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("Dealership",c)}"/> </td> <td><apex:outputText value="{!LEFT(Case.Account.Name,c2)}"/> </td> <td><apex:outputText value="{!LEFT("Status",c)}"/> </td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Status__c,c2)}"/> </td> </tr> <tr> <td><apex:outputText value="{!LEFT("Requester Name",c)}"/> </td> <td><apex:outputText value="{!LEFT(Case.Contact.Name,c2)}"/> </td> <td><apex:outputText value="{!LEFT("Date Closed",c)}"/> </td> <td><apex:outputText value="{0, date, MMMM d',' yyyy}"><apex:param value="{!Case.ClosedDate}" /></apex:outputText></td> </tr> </table> <br /> <apex:outputText value="______________!!! USE CALCULATION NO. AS REFERENCE ON THE ORDER FORM !!!________________" styleclass="redPrint"></apex:outputText> <br /> <h3>Equipment Section</h3> <table> <tr > <td width="130px"><apex:outputText value="{!LEFT("Truck Series",c)}"/></td> <td width="220px"><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Truck_Series__c,c2)}"/> </td> <td width="130px"><apex:outputText value="{!LEFT("Attachment #1",c)}"/></td> <td width="220px"><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Attachment_01__r.Name,c2)}"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("Truck Model",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Truck_Model__c,c2)}"/></td> <td><apex:outputText value="{!LEFT("Attachment #2",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Attachment_2__r.Name,c2)}"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("Mast Type",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Mast_Salescode__r.Name,c2)}"/> </td> <td><apex:outputText value="{!LEFT("Attachment #3",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Attachment_3__r.Name,c2)}"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("Tires Type",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Tires__r.Description,c2)}"/> </td> <td><apex:outputText value="{!LEFT("Forks",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Attachment_4__r.Name,c2)}"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("Carriage Type",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Carriage__r.Name,c2)}"/> </td> <td><apex:outputText value="{!LEFT("Carriage Info",c)}"/></td> <td><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Carriage__r.Description,c2)}"/></td> </tr> </table> <br /> <h3>Application Section</h3> <table> <tr > <td width="150px"><apex:outputText value="{!LEFT("Payload Length [in.]",c)}"/></td> <td width="190x"><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.Payload_Length_in__c}"/> </td> <td width="150px"><apex:outputText value="{!LEFT("Payload Width [in.]",c)}"/></td> <td width="190px"><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.Payload_Width_in__c}"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("Payload Height [in.]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.Payload_Height_in__c}"/></td> <td><apex:outputText value="{!LEFT("Payload Weight [lb]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.Payload_Weight_lb__c}"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("1st Load Center [in.]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.X1st_Load_Center_in__c}"/> </td> <td><apex:outputText value="{!LEFT("2nd Load Center [in.]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.X2nd_Load_Center_in__c}"/> </td> </tr> <tr valign="top" > <td height="50px" ><apex:outputText value="{!LEFT("Application Description",c)}"/></td> <td colspan="3"><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Application_Description__c,255)}"/></td> </tr> </table> <br /> <h3>Result Section</h3> <table> <tr > <td width="130px"><apex:outputText value="{!LEFT("Capacity 1st LC [lb]",c)}"/></td> <td width="210px"><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.Capacity_lbs_result_1__c}"/> </td> <td width="130px"><apex:outputText value="{!LEFT("Capacity 2nd LC [lb]",c)}"/></td> <td width="210px"><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.Capacity_lbs_result_2__c}"/> </td> </tr> <tr> <td><apex:outputText value="{!LEFT("up to max Hgt. [in.]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.up_to_max_Hgt_in_1__c}"/></td> <td><apex:outputText value="{!LEFT("up to max Hgt. [in.]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.up_to_max_Hgt_in_2__c}"/></td> </tr> <tr> <td><apex:outputText value="{!LEFT("out to max. off. [in]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.out_to_max_off_in_1__c}"/></td> <td><apex:outputText value="{!LEFT("out to max. off. [in]",c)}"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.out_to_max_off_in_2__c}"/></td> </tr> <tr> <td><apex:outputText value="@LC [in]"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.X1st_Load_Center_in__c}"/> </td> <td><apex:outputText value="@LC [in]"/></td> <td><apex:outputText value="{!Case.Existing_Residual_Cap_Calculation_N__r.X2nd_Load_Center_in__c}"/> </td> </tr> <tr valign="top" > <td height="50px" ><apex:outputText value="{!LEFT("Notes from KION Engineer",30)}"/></td> <td colspan="3"><apex:outputText value="{!LEFT(Case.Existing_Residual_Cap_Calculation_N__r.Notes_from_KION_Engineer__c,255)}"/></td> </tr> </table> <br /> <br /> <apex:outputText value="{!NOW()}" styleclass="companyName"></apex:outputText> <br /> <apex:outputText value="The requestor assumes the responsibility of informing the lift equipment owner about forklift capacity ratings. Lift Height, load Center and lateral offset limitations must not be exceeded. Ratings are calculated estimates and actual rating plate values may vary in some cases. The information on this form in no way constitutes a guarantee that KION can or will provide the equipment specified. Certification of availability is obtained only through the KION sales department." styleClass="finePrint"/> </body> </apex:page>
Attached below is the trigger...its an old trigger that I am digging up now. The goal of the project is to assign an owner to a lead based on postal code. So there are two objects in play: Lead and a custom object called ZIP_Code__c. We have manually assigned a field called Dealer_Lead_Contact__c with an email address to every record in the Zip Code object.

Every time this trigger is ran, on new or updated lead, I want to send an email to the Dealer_Lead_Contact__c. I plan to do this with the process builder but need to first populate an equivalent field in the Lead object.

So, in the trigger, I want to add a functionality that will use the zip code field in the lead object (Zip_Code__c) and search the zip code object (ZIP_Code__c) for a match. If it finds a match, assign the dealer lead contact field in the lead object (Dealer_Lead_Contact__c) with the dealer lead contact in the zip code object (Dealer_Lead_Contact__c)?

Currently the Dealer_Lead_Contact__c is a text field, the email address will be coming in the form of ***@***.com as a column in an excel sheet and uploaded to the Zip code object with the data loader. Not sure if there is a better way to fire an automatic email than using the text as text.  Any help is appreciated!



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

    List<Lead> lList = new List<Lead>();
    
    Map<String,ID> zipCodeMap = new Map<String,ID>();
    
    Map<id, User> userMap = new Map<id, User>();
    
    Set<String> userIds = new Set<String>();
    
    Set<String> zipCodeString = new Set<String>();
    
    List<Zip_Code__c> zipCodeList = new List<Zip_Code__c>();
    
    List<Messaging.SingleEmailMessage> listmail = new List<Messaging.SingleEmailMessage>(); 

    for(Lead l: Trigger.new)
    {       
        
        System.debug('LeadAssignmentByZipCode -- Do_Not_Use_ZipAssignment_del__c ' + l.Do_Not_Apply_Zip_Assignment_Rules__c);
        
        //Do_Not_Use_ZipAssignment_del__c
        if(l.Do_Not_Apply_Zip_Assignment_Rules__c == true) continue;
        
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(l.id);
            if(l.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(l.PostalCode <> null){
            zipCodeString.add(l.PostalCode);
            System.debug('LeadAssignmentByZipCode -- Lead -- ' + l.Name + ' Zip -- ' + l.PostalCode);
                
        }
    }
    
    if(!zipCodeString.IsEmpty())
    {
        System.debug('LeadAssignmentByZipCode -- Leads To Process ' + zipCodeString.size());
        
        zipCodeList = [SELECT  id, Name, UserAssigned__c  FROM Zip_Code__c WHERE Name IN: zipCodeString ];
        
    } else{
        System.debug('LeadAssignmentByZipCode -- No Leads To Process');
    }
    
    
    if(!zipCodeString.IsEmpty()){
        
        System.debug('LeadAssignByZip --- zipCodeString Count --> ' + zipCodeString.size());
        
        
        for(Zip_Code__c z: zipCodeList){
            
            if(!zipCodeMap.containsKey(z.Name)){
                zipCodeMap.put(z.name, z.UserAssigned__c);
                userIds.add(z.UserAssigned__c);
            }
            
        }
    }else
        System.debug('LeadAssignByZip --- zipCodeString Count --> zero');
         
        
    if(!userIds.IsEmpty()){
        
        System.debug('LeadAssignByZip --- userIds Count --> ' + userIds.size());
        userMap = new Map<id,User>([SELECT id, email FROM User WHERE id IN: userIDs]);
        
    }else
        System.debug('LeadAssignByZip --- userIds Count --> zero');
            

    for(Lead lead: Trigger.New) {
        
        if(lead.Do_Not_Apply_Zip_Assignment_Rules__c == true) continue;
        
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(lead.id);
            if(lead.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(zipCodeMap.containsKey(lead.PostalCode)){
            
            Id owner = zipCodeMap.get(lead.PostalCode);
            lead.OwnerId = owner;
            
            String inSubject = 'Lead Assignment Change' ;
            String inPlainTextBody = '';
            
            //if(CheckOrganizationID.IsProduction())
            //  inPlainTextBody = 'A lead has been assigned to you:  https://na.salesforce.com/' + lead.id + '  Please click for details.\n\n';
            //else
            //inPlainTextBody = 'A lead has been assigned to you: ' +  CheckOrganizationID.getServer() + '.salesforce.com/' + lead.id + '\n\nPlease click for details.\n\n';
            inPlainTextBody = 'A lead has been assigned to you: \n\n' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + lead.Id + '\n\nPlease click for details.\n\n';
            
            inPlainTextBody += 'Name: ' + lead.FirstName + ' '  + lead.LastName + '\n';
            inPlainTextBody += 'Company: ' + lead.Company + '\n';
            inPlainTextBody += 'Street: ' + lead.Street + '\n';          
                
            inPlainTextBody += 'City, State, Zip Code: ' + lead.City + ', ' + lead.State + ' ' + lead.PostalCode + '\n';
            

            if(lead.Email <> null)
                inPlainTextBody += lead.Email + '\n';   
            if(lead.Phone <> null)
                inPlainTextBody += lead.Phone + '\n';                       
            
            String toAddress = '';           
            
            Messaging.Singleemailmessage mail = new Messaging.Singleemailmessage();
            
            mail.setSubject(inSubject);
            list<String> ToAddr = ToAddress.split(',');
            
            if(userMap.containsKey(owner)){
                User u = userMap.get(owner);
                //toAddress = u.Email;
            }
            
            //mail.setToAddresses(toAddr);
            mail.setPlainTextBody(inPlainTextBody);
            mail.setSenderDisplayName('Salesforce Administrator');
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId(owner);
            
            listMail.add(mail);

        }   
        
    }   
        
    if(!listMail.IsEmpty()){
        
        try{            
            System.debug('LeadAssignByZip Sending Mail listMail Size ---> ' + listMail.size());
            Messaging.SendEmailResult [] results = Messaging.sendEmail(listmail);  
        
        }catch (Exception Ex)
        {
            system.debug('ERROR occured while sending email==>'+ String.ValueOf(Ex));
        }        
            
    } else{
            
        System.debug('LeadAssignByZip listMail Empty No Mail to send..... ');
    }               
    
}
It was previously working correctly at 80% coverage. I've since made changes to the trigger and now its at 66%. The changes are the addition of a US_zip_code__c checkbox. Previously the trigger could only assign to UserAssigned or User2 and now we can also assign to Mex CB RSM or Mex WH RSM. I commented out the continue line as marked in the code and added the two new user fields (Mex CB RSM and Mex WH RSM) to the query in order to grab this information to use.
Anybody good at writing test classes that can help?

Trigger:
trigger LeadAssignOwnerByPostalCode on Lead (before insert, before update) {

    List<Lead> lList = new List<Lead>();
   
    Map<String,Zip_Code__c> zipCodeMap = new Map<String,Zip_Code__c>();
    
    Map<id, User> userMap = new Map<id, User>();
    
    Set<String> userIds = new Set<String>();
    
    Set<String> zipCodeString = new Set<String>();
    
    List<Zip_Code__c> zipCodeList = new List<Zip_Code__c>();
    
    List<Messaging.SingleEmailMessage> listmail = new List<Messaging.SingleEmailMessage>(); 

   
    for(Lead l: Trigger.new)
    {       
         if (l.Do_Not_Apply_Zip_Assignment_Rules__c == false && (l.LeadSource == 'WPP-2020' || l.LeadSource == '346 Leasing - 2020' || l.LeadSource == '1219 Leasing - 2020' || l.LeadSource == 'Hydro Leasing - 2020' || l.LeadSource == 'Chatbot')){
    
        System.debug('LeadAssignmentByZipCode -- Do_Not_Use_ZipAssignment_del__c ' + l.Do_Not_Apply_Zip_Assignment_Rules__c);
        
      
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(l.id);
            //CHANGE****NOW COMMENTED OUT***:if(l.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(l.PostalCode <> null){
            zipCodeString.add(l.PostalCode);
            System.debug('LeadAssignmentByZipCode -- Lead -- ' + l.Name + ' Zip -- ' + l.PostalCode);
                
        }
    }
    }
    if(!zipCodeString.IsEmpty())
    {
        System.debug('LeadAssignmentByZipCode -- Leads To Process ' + zipCodeString.size());
        zipCodeList = [SELECT  id, Name, UserAssigned__c, User2__c, Mex_WH_RSM__c, Mex_CB_RSM__c,  Dealer_Lead_Email_Address__c  FROM Zip_Code__c WHERE Name IN: zipCodeString ];
        
    } else{
        System.debug('LeadAssignmentByZipCode -- No Leads To Process');
    }
    
    
    if(!zipCodeString.IsEmpty()){
        
        System.debug('LeadAssignByZip --- zipCodeString Count --> ' + zipCodeString.size());
        
        
        for(Zip_Code__c z: zipCodeList){
            
            if(!zipCodeMap.containsKey(z.Name)){
                zipCodeMap.put(z.name, z);
                userIds.add(z.UserAssigned__c);
            }
            
        }
    }else
        System.debug('LeadAssignByZip --- zipCodeString Count --> zero');
         
        
    if(!userIds.IsEmpty()){
        
        System.debug('LeadAssignByZip --- userIds Count --> ' + userIds.size());
        userMap = new Map<id,User>([SELECT id, email FROM User WHERE id IN: userIDs]);
        
    }else
        System.debug('LeadAssignByZip --- userIds Count --> zero');
            

    for(Lead lead: Trigger.New) {
        
     
        if (lead.Do_Not_Apply_Zip_Assignment_Rules__c == false && (lead.LeadSource == 'WPP-2020' || lead.LeadSource == '346 Leasing - 2020' || lead.LeadSource == '1219 Leasing - 2020' || lead.LeadSource == 'Hydro Leasing - 2020' || lead.LeadSource == 'Chatbot')){
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(lead.id);
            //if(lead.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        //CHANGES****Added logic to handle a US_Zip_Code__c field and two new users that can be assigned as owner***
        if(zipCodeMap.containsKey(lead.PostalCode)){
        if(lead.US_Zip_Code__c == true){
        
          //  Id owner = zipCodeMap.get(lead.PostalCode).UserAssigned__c;
          //  lead.OwnerId = owner;
            
           Id owner;
           Zip_Code__c zipCode = zipCodeMap.get(lead.PostalCode);

          if(lead.LeadSource == 'WPP-2020' || lead.LeadSource == '346 Leasing - 2020'){
              if(zipCode.user2__c != null) {
                owner = zipCode.User2__c;
                }
              else {
                owner = zipCode.UserAssigned__c;
                } 
          }
         
          else {
              if(zipCode.UserAssigned__c != null) {
                owner = zipCode.UserAssigned__c;
               }
        
              else {
               owner = zipCode.User2__c;
              }
              }
          lead.OwnerId = owner;
         
            
            lead.Dealer_Lead_Person__c = zipCodeMap.get(lead.PostalCode).Dealer_Lead_Email_Address__c;
            
            }
            
            else{
        
        
          //  Id owner = zipCodeMap.get(lead.PostalCode).UserAssigned__c;
          //  lead.OwnerId = owner;
            
           Id owner;
           Zip_Code__c zipCode = zipCodeMap.get(lead.PostalCode);

          if(lead.LeadSource == 'WPP-2020' || lead.LeadSource == '346 Leasing - 2020'){
              if(zipCode.Mex_WH_RSM__c != null) {
                owner = zipCode.Mex_WH_RSM__c;
                }
              else {
                owner = zipCode.Mex_CB_RSM__c;
                } 
          }
         
          else {
              if(zipCode.UserAssigned__c != null) {
                owner = zipCode.Mex_CB_RSM__c;
               }
        
              else {
               owner = zipCode.Mex_WH_RSM__c;
              }
              }
          lead.OwnerId = owner;
         
            
            lead.Dealer_Lead_Person__c = zipCodeMap.get(lead.PostalCode).Dealer_Lead_Email_Address__c;
            
            }
            }
            }
           }}

Test Class:
 
@isTest(SeeAllData=true)
private class TestLeadAssignmentByZipCode {

    static testMethod void testLeadAssignedByZipCode() {

        try{
            
            test.startTest();
            
            Zip_Code__c  zip = new ZIP_Code__c();
            zip.Name = '20716';
            zip.UserAssigned__c = UserInfo.getUserId();
            
            insert zip;
            
            Lead lead = new Lead();
            
            lead.FirstName = 'James';
            lead.Company = 'Acme';
            lead.Street = '100 West Street';
            lead.City = 'Marlboro';
            lead.State = 'MD';
            lead.PostalCode = '20716';
            lead.LeadSource = 'WPP-2020';
            insert lead;
            
            lead.PostalCode = '20710';
            
            
            update lead;
            
            String s2 = CheckOrganizationID.getServer();
                        
           
            
            test.stopTest();
            
            
            
            
        }catch (Exception e){
        
            System.Debug('Error While Testing testLeadAssignedByZipCode');
            
        }           

    }
}

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

    List<Lead> lList = new List<Lead>();
    
   
    Map<String,Zip_Code__c> zipCodeMap = new Map<String,Zip_Code__c>();
    
    Map<id, User> userMap = new Map<id, User>();
    
    Set<String> userIds = new Set<String>();
    
    Set<String> zipCodeString = new Set<String>();
    
    List<Zip_Code__c> zipCodeList = new List<Zip_Code__c>();
    
    List<Messaging.SingleEmailMessage> listmail = new List<Messaging.SingleEmailMessage>(); 

    for(Lead l: Trigger.new)
    {       
        
        System.debug('LeadAssignmentByZipCode -- Do_Not_Use_ZipAssignment_del__c ' + l.Do_Not_Apply_Zip_Assignment_Rules__c);
        
        //Do_Not_Use_ZipAssignment_del__c
        if(l.Do_Not_Apply_Zip_Assignment_Rules__c == true || l.LeadSource != 'Lead from Hubspot') continue;
        
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(l.id);
            if(l.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(l.PostalCode <> null){
            zipCodeString.add(l.PostalCode);
            System.debug('LeadAssignmentByZipCode -- Lead -- ' + l.Name + ' Zip -- ' + l.PostalCode);
                
        }
    }
    
    if(!zipCodeString.IsEmpty())
    {
        System.debug('LeadAssignmentByZipCode -- Leads To Process ' + zipCodeString.size());
      
        zipCodeList = [SELECT  id, Name, UserAssigned__c, Dealer_Lead_Email_Address__c  FROM Zip_Code__c WHERE Name IN: zipCodeString ];
        
    } else{
        System.debug('LeadAssignmentByZipCode -- No Leads To Process');
    }
    
    
    if(!zipCodeString.IsEmpty()){
        
        System.debug('LeadAssignByZip --- zipCodeString Count --> ' + zipCodeString.size());
        
        
        for(Zip_Code__c z: zipCodeList){
            
            if(!zipCodeMap.containsKey(z.Name)){
                zipCodeMap.put(z.name, z);
                userIds.add(z.UserAssigned__c);
            }
            
        }
    }else
        System.debug('LeadAssignByZip --- zipCodeString Count --> zero');
         
        
    if(!userIds.IsEmpty()){
        
        System.debug('LeadAssignByZip --- userIds Count --> ' + userIds.size());
        userMap = new Map<id,User>([SELECT id, email FROM User WHERE id IN: userIDs]);
        
    }else
        System.debug('LeadAssignByZip --- userIds Count --> zero');
            

    for(Lead lead: Trigger.New) {
        
        if(lead.Do_Not_Apply_Zip_Assignment_Rules__c == true) continue;
        
        if(Trigger.isUpdate){
            System.debug('LeadAssignmentByZipCode -- Update Trigger -- ');
            Lead oldLead = Trigger.oldMap.get(lead.id);
            if(lead.PostalCode.equals(oldLead.PostalCode)) continue;
        } else
            System.debug('LeadAssignmentByZipCode -- Insert Trigger -- ');
        
        
        if(zipCodeMap.containsKey(lead.PostalCode)){
            
            Id owner = zipCodeMap.get(lead.PostalCode).UserAssigned__c;
            lead.OwnerId = owner;
            
        
            lead.Dealer_Lead_Person__c = zipCodeMap.get(lead.PostalCode).Dealer_Lead_Email_Address__c;
            //Added by Abhishek : End
            }
            }

}

And here is the current test class:
 
@isTest(SeeAllData=true)
private class TestLeadAssignmentByZipCode {

    static testMethod void testLeadAssignedByZipCode() {

        try{
            
            test.startTest();
            
            Zip_Code__c  zip = new ZIP_Code__c();
            zip.Name = '20716';
            zip.UserAssigned__c = UserInfo.getUserId();
            
            insert zip;
            
            Lead lead = new Lead();
            
            lead.FirstName = 'James';
            lead.Company = 'Acme';
            lead.Street = '100 West Street';
            lead.City = 'Marlboro';
            lead.State = 'MD';
            lead.PostalCode = '20716';
            
            insert lead;
            
            lead.PostalCode = '20710';
            
            
            update lead;
            
            String s2 = CheckOrganizationID.getServer();
            
            test.stopTest();
            
            
            
            
        }catch (Exception e){
        
            System.Debug('Error While Testing testLeadAssignedByZipCode');
            
        }           

    }
}

I'm stuck at 51%, can anyone help?