0

I need some help. I'm getting this error and can't figure out the code the developer created that would cause this now. I'm not a developer so a lot of this doesn't make sense to me.

CaseToLeadTrigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Class.CaseToLeadHandler.getCasetoLead: line 61, column 1 Class.CaseToLeadHandler.isAfterInsert: line 3, column 1 Trigger.CaseToLeadTrigger: line 6, column 1

CaseToLeadHander code:

public class CaseToLeadHandler {
    public static void isAfterInsert(List<Case> inputList) {
        getCasetoLead(inputList);
    }
    
    
    private static void getCasetoLead (List<Case> inputList) {
        Id RTIdContactUs = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Contact Form').getRecordTypeId();
        Id RTIdDoIQualify = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Get Pre-Qualified').getRecordTypeId();
        Id RTIdUnpaidAppointment = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Unpaid Appointment').getRecordTypeId();
        Id RTIdPrepaidAppointment = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Prepaid Appointment').getRecordTypeId();
        Id RTIdPaymentReceived = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Payment received').getRecordTypeId();
        set<id> caseId = new set<id>();
        
        String lastNameCase;
        String caseMail;
        
        List<String> lstSTR = new List<String>();
        List<Lead> lstLeadForCreate = new List<Lead>();
        List<Case> caseWithNewAccountList = new List<Case>();
        List<Case> paymentPrePayCase = new List<Case>();
        List<Payment_History__c> createListPaymentHistory = new List<Payment_History__c>();
        
        Map<String, Case> mapStrToCase = new Map<String, Case>();
        Map<String, Case> mapStrToCaseUpdate = new Map<String, Case>();
        Map<String, Case> updateCaseForPrePay = new Map<String, Case>();
        
        for (Case itemCase : inputList) {
            caseId.add(itemCase.Id);
        }
        
        List<Case> lstCase = [SELECT Id, Description, Lead__c, What__c, When__c, Availability_of_the_health_conditions__c,
                                   Message__c, Subject, Where__c, Staff__c, Copy_of_diagnosis_letter_from_doctor__c, 
                                   What_is_your_date_of_birth__c, How_did_you_hear_about_us__c, Suffering_from_any_condition_on_website__c 
                              FROM Case 
                              WHERE Id IN:caseId];
        
        for (Case itemCase : lstCase) {
            if (itemCase.Subject != null && itemCase.Description != null) {
                if (itemCase.Description.contains('Name:') != FALSE) {
                    mapStrToCase.put(updateTrim(itemCase, 'Email:', '<mailto').toUpperCase(), itemCase);
                    mapStrToCaseUpdate.put(updateTrim(itemCase, 'Email:', '<mailto').toUpperCase(), itemCase);
                }
                
                if (itemCase.Description.contains('Customer:') != FALSE) {
                    mapStrToCase.put(updateTrim(itemCase, 'Email:', 'What').toUpperCase(),itemCase);
                    mapStrToCaseUpdate.put(updateTrim(itemCase, 'Email:', 'What').toUpperCase(),itemCase);
                }
                if(itemCase.Subject.contains('Payment received from')){
                    updateCaseForPrePay.put(itemCase.Subject.substring(itemCase.Subject.indexOf('Payment received from ')+22, itemCase.Subject.length()).toUpperCase(), itemCase);
                    itemcase.Price__c = itemCase.Description.substringBetween('Total: $', ' ');
                }
            }
        }
        
        List<Lead> lstLeadForUpdate = [SELECT Id, FirstName, LastName, Email, Status FROM Lead WHERE Email IN:mapStrToCase.keySet()];
        List<Lead> lstLeadForPrePay = [SELECT Id, FirstName, LastName, Email, Status FROM Lead WHERE Email IN:updateCaseForPrePay.keySet()];
        
        if (!lstLeadForUpdate.isEmpty()) {
            for (Lead itemLead : lstLeadForUpdate) {
                **if (mapStrToCase.get(itemLead.Email.toUpperCase()).Subject != null && mapStrToCase.get(itemLead.Email.toUpperCase()).Subject.contains('PREPAID') != FALSE) {
                  itemLead.Status = 'Booked - Need Diagnosis';**
                     if (itemLead.FirstName == null) {
               itemLead.FirstName = (updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' '), 'Phone') == '')?'':updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' ');
                    itemLead.LastName = (updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' '), 'Phone') == '')?updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', 'Phone'):updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' '), 'Phone');
                  }
                }
                if (mapStrToCase.get(itemLead.Email.toUpperCase()).Subject != null && mapStrToCase.get(itemLead.Email.toUpperCase()).Subject.contains('PREPAID') == FALSE) {
                     itemLead.Status = 'Booked - Need Diagnosis';
                     if (mapStrToCase.get(itemLead.Email.toUpperCase()).Description.contains('Customer') == TRUE) {
                       if (itemLead.FirstName == null) {
                 itemLead.FirstName = (updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' '), 'Phone') == '')?'':updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' ');
                      itemLead.LastName = (updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' '), 'Phone') == '')?updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', 'Phone'):updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Customer:       ', ' '), 'Phone');
                        }
                     }
                     If (mapStrToCase.get(itemLead.Email.toUpperCase()).Description.contains('Name:') != FALSE) {
                       if (itemLead.FirstName == null) {
                          itemLead.FirstName = (updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Name:', ' '), '<mailto') == '')?'':updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Name:', ' ');
                    itemLead.LastName = (updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Name:', ' '), '<mailto') == '')?updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Name:', 'Email:'):updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), updateTrim(mapStrToCase.get(itemLead.Email.toUpperCase()), 'Name:', ' '), 'Email:');
                        }
                     }
                }                                                            
                mapStrToCase.get(itemLead.Email.toUpperCase()).Lead__c = itemLead.Id;
                subStrMethod(mapStrToCase.get(itemLead.Email.toUpperCase()), RTIdContactUs, RTIdDoIQualify, RTIdUnpaidAppointment, RTIdPrepaidAppointment, RTIdPaymentReceived);
              mapStrToCaseUpdate.remove(itemLead.Email.toUpperCase());
            }
            try{
              update mapStrToCase.values();
            }
            catch(DmlException e) {
                System.debug('The following exception has occurred: ' + e.getMessage());
            }
            try{
              update lstLeadForUpdate;
            }
            catch(DmlException e) {
                System.debug('The following exception has occurred: ' + e.getMessage());
            }
        }
        
        if (!lstLeadForPrePay.isEmpty()) {
            
            for (Lead itemLead : lstLeadForPrePay) {
                updateCaseForPrePay.get(itemLead.Email.toUpperCase()).Lead__c = itemLead.Id;
                updateCaseForPrePay.get(itemLead.Email.toUpperCase()).RecordTypeId = RTIdPaymentReceived;
                
                Payment_History__c paymentHistory = new Payment_History__c();
                paymentHistory.Lead__c = itemLead.Id;
                paymentHistory.Description__c = updateCaseForPrePay.get(itemLead.Email.toUpperCase()).Description.substringBetween('Description: ', 'Unit');
        paymentHistory.Amount__c = decimal.valueOf(updateCaseForPrePay.get(itemLead.Email.toUpperCase()).Description.substringBetween('Total: $', ' '));
                paymentHistory.Receipt_No__c = updateCaseForPrePay.get(itemLead.Email.toUpperCase()).Description.substringBetween('Receipt No: ', '"');
                paymentHistory.Payment_type__c = 'PayPal';
                
                createListPaymentHistory.add(paymentHistory);
            }
            try{
                update updateCaseForPrePay.values();
            } 
            catch(DmlException e) {
                System.debug('The following exception has occurred: ' + e.getMessage());
            }
            try{
              insert createListPaymentHistory;
            }
            catch(DmlException e) {
                System.debug('The following exception has occurred: ' + e.getMessage());
            }
        }
        
        for (Case itemCase : mapStrToCaseUpdate.values()) {
                            
            Lead itemLead = new Lead();
            
            
            if (itemCase.Description.contains('Name:') != FALSE) {  
                itemLead.Status = 'New Lead';
                itemLead.LeadSource = 'Email';
              itemLead.FirstName = (updateTrim(itemCase, updateTrim(itemCase, 'Name:', ' '), '<mailto') == '')?'':updateTrim(itemCase, 'Name:', ' ');
              itemLead.LastName = (updateTrim(itemCase, updateTrim(itemCase, 'Name:', ' '), '<mailto') == '')?updateTrim(itemCase, 'Name:', 'Email:'):updateTrim(itemCase, updateTrim(itemCase, 'Name:', ' '), 'Email:');
              itemLead.Email = updateTrim(itemCase, 'Email:', '<mailto');
                
                if (itemCase.Description.contains('Are you a Permanent or Temporary resident?')) {
                    itemLead.Phone = updateTrim(itemCase, 'Phone Number:', 'Are');
                    itemLead.Permanent_or_Temporary_resident__c = updateTrim(itemCase, 'Are you a Permanent or Temporary resident?:', 'Zip');
                }
                
                if (!itemCase.Description.contains('Are you a Permanent or Temporary resident?')) {
                    itemLead.Phone = updateTrim(itemCase, 'Phone Number :', 'Zip');
                }
                
              itemLead.Company = 'Unknown';
            }
            
            if (itemCase.Description.contains('Customer:       ') != FALSE) {              
                if (itemCase.Subject != null && itemCase.Subject.contains('PREPAID') != FALSE) {
                  itemLead.Status = 'Booked - Need Diagnosis';
                }
                if (itemCase.Subject != null && itemCase.Subject.contains('PREPAID') == FALSE) {
                    itemLead.Status = 'Booked - Need Diagnosis';
                }
                itemLead.FirstName = (updateTrim(itemCase, updateTrim(itemCase, 'Customer:       ', ' '), 'Phone') == '')?'':updateTrim(itemCase, 'Customer:       ', ' ');
                itemLead.LastName = (updateTrim(itemCase, updateTrim(itemCase, 'Customer:       ', ' '), 'Phone') == '')?updateTrim(itemCase, 'Customer:       ', 'Phone'):updateTrim(itemCase, updateTrim(itemCase, 'Customer:       ', ' '), 'Phone');
                itemLead.Phone = updateTrim(itemCase, 'Phone:', 'Email');
                itemLead.Email = updateTrim(itemCase, 'Email:', 'What');
              itemLead.Company = 'Unknown';
                itemLead.LeadSource = 'Email';
                
            }
            
            lstLeadForCreate.add(itemLead);
            caseWithNewAccountList.add(itemCase);
        } 
       
        if (!lstLeadForCreate.isEmpty()) {
            try{
              insert lstLeadForCreate;
            } 
            catch(DmlException e) {
                System.debug('The following exception has occurred: ' + e.getMessage());
            }
        }
        
        for (integer i = 0; i < lstLeadForCreate.size(); i++ ) {
          caseWithNewAccountList.get(i).Lead__c = lstLeadForCreate.get(i).Id;
            subStrMethod(caseWithNewAccountList.get(i), RTIdContactUs, RTIdDoIQualify, RTIdUnpaidAppointment, RTIdPrepaidAppointment, RTIdPaymentReceived);
        }
        
        try{
          update caseWithNewAccountList;
        } 
        catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
        
    }
    
    
    private static void subStrMethod (Case itemCase, Id contactUs, Id DoIQualify, Id UnAppointment, Id RTIdPrepaidAppointment, Id RTIdPaymentReceived) {
        if (itemCase.Description.contains('Customer:') != FALSE) {
            if(itemCase.Subject != null && itemCase.Subject.contains('PREPAID') != FALSE){
                itemCase.RecordTypeId = RTIdPrepaidAppointment;
                itemCase.Duration__c = itemCase.Description.substringBetween('When:', 'Where').substringBetween('(', ')');
                itemCase.Staff__c = itemCase.Description.substringBetween('Staff:', 'Payment');
            }
            if(itemCase.Subject != null && itemCase.Subject.contains('PREPAID') == FALSE){
                itemCase.RecordTypeId = UnAppointment;
                itemCase.Staff__c = itemCase.Description.substringBetween('Staff:', 'Questions');
            }
            
            itemCase.What__c = itemCase.Description.substringBetween('What:', 'When');
            itemCase.When__c = itemCase.Description.substringBetween('When:',  'Where');
            itemCase.Where__c = itemCase.Description.substringBetween('Where:', 'Staff');
            itemCase.Copy_of_diagnosis_letter_from_doctor__c = itemCase.Description.substringBetween('appointment?', 'What');
            itemCase.What_is_your_date_of_birth__c = itemCase.Description.substringBetween('YYYY', 'How');
            itemCase.How_did_you_hear_about_us__c = itemCase.Description.substring(itemCase.Description.IndexOf('us?')+3, itemCase.Description.IndexOf('Manage appointment'));
        }
        
        if (itemCase.Description.contains('Name:') != FALSE) {
            
            if (itemCase.Description.contains('Are you a Permanent or Temporary resident?')) {
                itemCase.RecordTypeId = DoIQualify;
              itemCase.Suffering_from_any_condition_on_website__c = itemCase.Description.substringBetween('website? :', 'How');
              itemCase.How_did_you_hear_about_us__c = itemCase.Description.substring(itemCase.Description.IndexOf('us?')+5, itemCase.Description.IndexOf('This message')-33);
            }
            
            if (!itemCase.Description.contains('Are you a Permanent or Temporary resident?')) {
                itemCase.RecordTypeId = contactUs;
                itemCase.Availability_of_the_health_conditions__c = itemCase.Description.substringBetween('Do you have one of the health conditions approved by the state for cannabis?:', 'How did you hear about us?');
                itemCase.How_did_you_hear_about_us__c = itemCase.Description.substringBetween('How did you hear about us?:', 'Message:');
                itemCase.Message__c = itemCase.Description.substring(itemCase.Description.IndexOf('Message:')+8, itemCase.Description.IndexOf('This message')-34);
            }
        }
    }
    
    
    private static String updateTrim (Case objCase, String startStr, String endStr) {
        
        String strStrin = objCase.Description.substringBetween(startStr, endStr);
        
    if (strStrin != null) {
          return strStrin.trim().replaceAll('\\s+','');    
        }
        else {
            return '';
        }
        
    }
}

Line 61:
if (mapStrToCase.get(itemLead.Email.toUpperCase()).Subject != null && mapStrToCase.get(itemLead.Email.toUpperCase()).Subject.contains('PREPAID') != FALSE)

1
  • Line 61 is called out in the provided code, but it's long enough that I feel like calling it out specifically will help people.
    – Derek F
    Feb 4, 2021 at 16:58

1 Answer 1

1

A Null Pointer Exception (NPE for short) happens when you to try to perform an action on something that is null. Something like null.toString(), null.Status, null.get(0), etc...

null is a special thing in many programming languages (Apex included). In Apex, null has no properties, no instance variables, and no methods. Generally speaking, everything is null until someone or something gives it another value.

Working out the cause of an NPE is usually an exercise in working backwards. You know where the NPE happened, you're working backwards to figure out what can't possibly be null to narrow down what is null, and then you can work out why the thing that is null is infact null.

Let's break down the individual parts on that particular line that could evaluate to null (and then make an attempt to do something with that null value):

  • itemLead.Email.toUpperCase()
    • the lead's email could be null
  • mapStrToCase.get(<email>).Subject
    • mapStrToCase may not have the specified email (which is case-sensitive because of how the keys of a Map work)

We know that itemLead is not null because the list feeding that loop, lstLeadForUpdate, is populated by a query. We would have run into a different error earlier in the code if the query failed, and queries never return null (they can return empty lists).

Similarly, we know that the issue cannot possibly be in the second condition of the if statement because, if we get past the first condition, mapStrToCase.get(itemLead.Email.toUpperCase()).Subject is guaranteed to not be null

So, either your lead's email is null, or mapStrToCase does not contain the email for a given lead.

Looking at the code some, I don't think it's possible that mapStrToCase does not contain the email (those emails are the only thing used to retrieve the leads).

Email is not a required field on Lead (not by default, at least), so this one is plausible.

My Conclusion

I think the most likely scenario is as follows:

  • Someone is trying to insert a Case that doesn't have an email in the case description (or it's not in-between "Email:" and either "<mailto" or "What").
  • That causes you to query for Leads with an Email of '' (an empty string). Since Salesforce doesn't store empty strings in SObjects, that's equivalent to null, so Salesforce is giving you a Lead (or Leads) with null email.
  • Attempting to work on a Lead with a null email gets you into trouble.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .