function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AMR27AMR27 

Help with Empty List & Map

Hey All,

 

I am having an issue with a class that is supposed to handle incoming email-to-cases and associate the email address to a group of existing contacts.

 

I have seem to hit an impasse at lines 123 and 124, in that the debug log states that both CasestoUpdate and emailToContactMap are empty, but I cannot figure out why.

 

This has been in production running without part of this newly updated code, so the bulk of the code should work.  I do not know where I am going wrong, but as of now NO case is being created and NO contact is being associated as such.

 

Below is the code, please get back to me with any ideas.  I believe it has to do with the map, but since the list is also empty, I really don't know where to start.

 

Thanks in advance!!

 

trigger CSR_CreateContact on Case (before insert) {
    /*
     * Get CSR Case record type id
     */ 
    Id csrRTID = [select Id from recordtype where developername = 'CSRCase'].Id;
    
    /*
     * Email Loop Killer
     * Will not process new email if there are atleast 4 emails from 
     * the same email with the same subject and the previous email was less than 5 minutes ago
     */
    case[] c = trigger.new;
    if(c[0].RecordTypeId == csrRTID && c[0].Origin != 'Phone' && c[0].Origin != 'Other'){
        Integer caseCreateLimit = 10;
        case[] check = [select ID, CreatedDate, subject from Case where RecordTypeId =: csrRTID and SuppliedEmail = :c[0].SuppliedEmail and isclosed = false and createdDate >: DateTime.Now().addMinutes(-60) order by CreatedDate desc];
        system.debug(c[0].SuppliedEmail);
          
        if(check.size()>caseCreateLimit-1){
            c[0].addError('Automatic email loop has been terminated');
        }else if(check.size()>caseCreateLimit-2 && 
                    c[0].suppliedEmail != null && 
                    c[0].SuppliedEmail != ''){
                String[] toAddresses = new String[]{c[0].SuppliedEmail};
                String replyToAddress = 'help@livingsocial.com';
                String subject = c[0].Subject;
                String htmlMessageBody = '<h3>Case creation limit reached'+' </h3>';
                
                htmlMessageBody += '<hr/>';
                htmlMessageBody += '<h4> You have reached the maximum number of support cases you can create at this time. Please try your request again after one hour. Thanks for LivingSocial!</h4></b><p>';
                String senderDisplayName = 'LivingSocial';
                /*List <Messaging.SendEmailResult> results = 
                    CSR_EmailUtil.sendSingleEmail(toAddresses, replyToAddress, 
                        senderDisplayName, subject, htmlMessageBody);
                System.debug('Send Email Result:' +results.get(0).isSuccess());*/
        }
    }
    
    
    /*
     * Auto-Creation and Update of Contacts.
     * Will create new contacts if the email id does not exist and 
     * update contact if its Name changes from the last time it was saved.
     */     
    List<String> emailAddresses = new List<String>();
    //Get a list of email address for Cases not associated to a Contact.
    for (Case caseObj:Trigger.new) {
        if(caseObj.RecordTypeId == csrRTID
            && caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!=''){
                emailAddresses.add(caseObj.SuppliedEmail);
            }
    }
    System.debug('emailAddresses:'+emailAddresses);
    
    //Get the LivingSocial account to associate newly created Contacts to it.
    List<Account> account = new List<Account>([select id, AccountNumber from Account where (Name LIKE 'LivingSocial Consumers%' and isConsumerAccount__c = 'yes') ORDER BY AccountNumber DESC limit 3]);
    
    System.debug('ACCOUNTS IS:'+account);
    
    //Get the existing LivingSocial Consumer account ids to build Contact list to querry email addresses against
    Set<ID> acctIDs = new Set<ID>();
    
    for (Account a : account) {
        
            acctIDs.add(a.id);
            
    }
    
    System.debug('ACCTIDS IS:'+acctIDs);
    
    Map<String, Contact> existingRecords = new Map<String, Contact>();
    
    //Get a list of contacts already using one of the Email Addresses.
    for(List<Contact> contacts:[Select Id, LastName, FirstName, Email From Contact Where Email != NULL AND Email IN :emailAddresses AND AccountId in :acctIDs]){
        for (Contact cont:contacts) {
            existingRecords.put(cont.Email, cont);
        }
    }
    
    System.debug(' existingRecords:'+existingRecords);
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Contact> existingContacts = new List<Contact>();
    List<Case> casesToUpdate = new List<Case>();
    
    for (Case caseObj:Trigger.new) {
        if (caseObj.RecordTypeId == csrRTID && 
            //caseObj.ContactId==null &&
            caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!='' &&
            !existingRecords.keySet().contains(caseObj.SuppliedEmail)){
                //If case has a Web Name (Supplied Name)
                if(caseObj.SuppliedName!=null && caseObj.SuppliedName!=''){
                    String[] fullName = caseObj.SuppliedName.split(' ',5);
                    Integer listSize = fullName.size();
                    Contact cont = new Contact(AccountId = account[0].id,
                                                FirstName=fullName[0],
                                                LastName=fullName[listSize-1],
                                                Email=caseObj.SuppliedEmail);
                    emailToContactMap.put(caseObj.SuppliedEmail,cont);
                    casesToUpdate.add(caseObj);
                    }
     
                //Update Account Field to 'LivingSocial' if Case Origin is Phone
                //else if(caseObj.Origin == 'Phone'){
                    //caseObj.AccountId = account.id;
                      // }
                //If case does not have a Web Name (Supplied Name)
                else{
                    Integer index = caseObj.SuppliedEmail.indexOf('@');
                    String lastName = caseObj.SuppliedEmail.substring(0,index);
                    Contact cont = new Contact(AccountId = account[0].id,
                                               LastName=lastName,
                                               Email=caseObj.SuppliedEmail);
                    emailToContactMap.put(caseObj.SuppliedEmail,cont);
                    casesToUpdate.add(caseObj);

                }
        }
      System.debug('existing records is:'+existingRecords);
      System.debug('RTYPE IS:'+csrRTID);
      System.debug('SuppliedEmail:'+ caseObj.SuppliedEmail);                                                   
      System.debug('SuppliedEmail:'+ caseObj.SuppliedEmail);                                                   
      System.debug('CASESTOUPDATE IS:'+casesToUpdate);
      System.debug('EMAILTOCONTACTMAP IS:'+emailToContactMap);
      
        //Code to update Contact Name if different from the last time it was saved.
        /*else if(caseObj.RecordTypeId == csrRTID && 
                caseObj.SuppliedEmail!=null &&
                caseObj.SuppliedEmail!='' &&
                caseObj.SuppliedName!=null && 
                caseObj.SuppliedName!='' && 
                existingRecords.keySet().contains(caseObj.SuppliedEmail)){
            String ID = existingRecords.get(caseObj.SuppliedEmail).id;
            String[] fullName = caseObj.SuppliedName.split(' ',5);
            Integer listSize = fullName.size();
            String lName = fullName[listSize-1];
            String fName = fullName[0];
            if(existingRecords.get(caseObj.SuppliedEmail).LastName != lName ||
                existingRecords.get(caseObj.SuppliedEmail).FirstName != fName){
                existingContacts.add(new Contact(id = ID, LastName = lName, FirstName = fName));
            }
        }*/
    }
    System.debug(' emailToContactMap:'+emailToContactMap);
    
    //Create Contacts.
    List<Contact> newContacts = emailToContactMap.values();
    System.debug('newContacts:'+newContacts);
    if(!newContacts.isEmpty()){
        //Insert New Merchant Case
        Database.SaveResult[] lsr = Database.insert(newContacts,false);
        List<String> errMessages = new List<String>();
        // Iterate through the Save Results
        for(Database.SaveResult sr:lsr){
            if(!sr.isSuccess()){
                Database.Error err = sr.getErrors()[0];
                errMessages.add(err.getMessage());
            }
        }
        if(!errMessages.isEmpty()){
            system.debug('errMessages for New Contacts:'+errMessages);
        }
    }
    //Update Contacts
    System.debug(' existingContacts:'+existingContacts);
    if(!existingContacts.isEmpty()){
        //Update New Merchant Case
        Database.SaveResult[] lsr = Database.update(existingContacts,false);
        List<String> errMessages = new List<String>();
        // Iterate through the Save Results
        for(Database.SaveResult sr:lsr){
            if(!sr.isSuccess()){
                Database.Error err = sr.getErrors()[0];
                errMessages.add(err.getMessage());
            }
        }
        if(!errMessages.isEmpty()){
            system.debug('errMessages for updates to Existing Contacts:'+errMessages);
        }
    }
    
    //Associate newly created Contacts to respective Cases.
    System.debug(' casesToUpdate:'+casesToUpdate);
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(caseObj.SuppliedEmail);
        caseObj.ContactId = newContact.Id;
    }
}

 

dmchengdmcheng

Since the list and map are empty, it sounds like the case records are not meeting the IF conditions.  Have you debugged the case record values to see why?