0

*EDIT-I have updated my code with more explanation and debugs showing what is printed and where execution unexpectedly exits without error. I am also only working with 1 test method for now. I am receiving debugs in the Trigger's first few lines, but the AggregateResultsList is always empty so the For-each loop never executes.

This Trigger will send an email message if an Account has 8 or more cases created within 7 days. Depending on the status of the four fields in the If/Else block will dictate the destination of the email. If the status is "Active" 1 email is sent to a set email address. If the status is "Implementation" then 2 emails are sent, addresses are grabbed from SOQL.

Any help is appreciated.

trigger CaseCountAlertTrigger on Case (before insert) {
List<String> emailAdds = new List<String>();                            // Holds '2' ToAddresses from Milestone1_project__c object
Set <Id> AcctIds = new Set <Id>();                                      //Holds Account Ids from this Case Trigger  
String messageToSend;                                                   //Email body sent in email (will be in HTML format)
Map < Id, String > accountIdEmailmessageMap = new Map < Id, String > (); // map of AccountId and Email body per Account/AccountId to be sent

List < AggregateResult > AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co
                                                    FROM Case
                                                    WHERE CreatedDate = LAST_N_DAYS:7 AND Id in :Trigger.New 
                                                    GROUP BY Account.Name, AccountId
                                                    HAVING COUNT(Id) >= 8
                                                    ];

System.debug('AggregateResult:  ' + AggregateResultList);  // debugs:    'AggregateResult: ()'  --emtpy aggregate list
  System.debug('Trigger Results' + Trigger.new);           // This line will print the Case that comes in as Trigger.New, debugs as expected.

//  ******** It seems to exit here***************

for (AggregateResult aggr: AggregateResultList){
                       messageToSend = 'You are receiving this email alert due to an account ';
                       messageToSend += 'activity rule has exceeded 8 cases created within 5 business days.<br><br>';
                       messageToSend += 'Please, follow up with the account and provide guidance and assistance.<br><br>';
                       messageToSend += '<b>Account Name:  </b>' + aggr.get('name') + '<br> <br>';
                       messageToSend +=  'Thank you, <br>';
                       messageToSend +=  'Salesforce Team';

             //Crete Map of <AccountId, Message to serve as body in Email
             //                         for each accountId>       
                Id accId = (Id) aggr.get('AccountId');
                accountIdEmailmessageMap.put(accId, messageToSend);

            //Create List of AccountId's to grab email addresses
            // from child Object for 'Implementation Status 
                AcctIds.add(accId);  

         }

                System.debug(accountIdEmailmessageMap);  


    /*
    List < Case > caseList = [SELECT Id, AccountId, Account.Name, Account.Eyefinity_EHR_Status__c,
                              Account.Eyefinity_PM_Status__c, Account.OfficeMate_Status__c,
                              Account.Project_Imp_Status__c                
                              FROM Case
                              WHERE AccountId IN: AcctIds];
    */


    // SOQL to grab the four status fields on Account to check status either 'Active' or 'Implementation'
    // also grab two email addresses for use in ifElse block
    List<Account> accList = [SELECT Id, Name, Eyefinity_EHR_Status__c, Eyefinity_PM_Status__c,
                                    Project_Imp_Status__c, OfficeMate_Status__c,(select Client_Advisor_Email__c,
                                                                                 Resource_Coordinator_Email__c
                                                                                 from Projects__r) 

                             FROM Account
                             WHERE Id IN :AcctIds];

    List<Messaging.SingleEmailMessage> lstASingleEmailMessage = new List<Messaging.SingleEmailMessage>();
    List<Messaging.SingleEmailMessage> lstBSingleEmailMessage = new List<Messaging.SingleEmailMessage>();


    for (Account al: accList) {

        if (al.Eyefinity_EHR_Status__c == 'Active' ||
            al.Eyefinity_PM_Status__c == 'Active' ||
            al.Project_Imp_Status__c == 'Active'  ||
            al.OfficeMate_Status__c == 'Active') {

               // String messageBody = accountIdEmailmessageMap.get(al.accId);

                //Send Email to CustomerService if Active
                List<String> emailaddr = new List<String>();
                emailaddr.add('CustomerSuccessManagers@test.com');  

                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setSenderDisplayName(' Support');
                mail.setToAddresses(emailaddr);   
                mail.Subject = 'Notification:  Account Case activity rule exceeded';
                mail.setHtmlBody(messageToSend);
                lstASingleEmailMessage.add(mail);
            }


            else if (al.Eyefinity_EHR_Status__c == 'Implementation' ||
                     al.Eyefinity_PM_Status__c == 'Implementation' ||
                     al.Project_Imp_Status__c == 'Implementation' ||
                     al.OfficeMate_Status__c == 'Implementation'){
                String messageBody1 = accountIdEmailmessageMap.get(cl.AccountId);        

                System.debug('Accounts: ' + al);

               //Send email to Coordinator and Advisor if in Implementation

                for(Account a : accList)
                {
                    for(Milestone1_Project__c p : a.Projects__r)
                    {   
                        emailAdds.add(p.Client_Advisor_Email__c);
                        emailAdds.add(p.Resource_Coordinator_Email__c);
                    }
                }

                System.debug(emailAdds);
                Messaging.SingleEmailMessage amail = new Messaging.SingleEmailMessage();
                amail.SetSenderDisplayName('Support');
                amail.setToAddresses(emailAdds);
                amail.Subject = 'Notification:  Account Case activity rule exceeded';
                amail.setHtmlBody(messageBody1);
                lstASingleEmailMessage.add(amail); 

            }  
            else{
                System.debug(AggregateResultList);

            }
    }


    Messaging.SendEmailResult[] r = Messaging.sendEmail(lstASingleEmailMessage); 

}

Test Case:

    @isTest
private class TestCaseHandlerAlert {

  @testSetup static void setup(){
      List<Account> testAccounts = new List<Account>();

        Account a = new Account();
            a.name = 'AccountEHRImplement';
            a.RecordTypeId = '01230000000v58OAAQ';
            a.Eyefinity_EHR_Status__c = 'Implementation';
            a.Tax_Id__c = '123456789';
      testAccounts.add(a);

        //Insert Account
            insert testAccounts;

         //Create User:  THis user will fill required fields on the Milestone1_Project1 allowing for a an email address to populate
        User tuser = new User(  firstname = 'tuserFname',
                            lastName = 'tuserLastname',
                            email = 'test@tester.com',
                            Username = 'tuserleielkwl@test18278391.org',
                            EmailEncodingKey = 'ISO-8859-1',
                            Alias ='Blah',
                            TimeZoneSidKey = 'America/Los_Angeles',
                            LocaleSidKey = 'en_US',
                            LanguageLocaleKey = 'en_US',
                            ProfileId =[Select Id From Profile Where Name='Eyefinity Managers'].id
                           );  
        insert tuser;

      //Create Project
        Milestone1_Project__c project1 = new Milestone1_Project__c();
            project1.Customer_Account__c = [Select Id FROM Account Where Name ='AccountEHRImplement'].id;
            project1.Name = 'triggerProject';
            project1.Client_Advisor__c = [Select Id FROM User Where Username ='tuserleielkwl@test18278391.org'].id;
            project1.Resource_Coordinator__c = [Select Id FROM User Where Username ='tuserleielkwl@test18278391.org'].id;  
            project1.RecordTypeId = '01214000001RYp7AAG';    
                insert project1;
    }

    @isTest static void AccountEHRImplement (){

          //Create and insert more than more than 8 cases  
            List<Case> casestoInsert = new List<Case>();     
        for (Integer i=1; i<10; i++){
            Case cas1 = new Case();
                cas1.RecordTypeId = '01214000001NcOYAA0';
                cas1.AccountId = [Select Id FROM Account Where name ='AccountEHRImplement'].id;
                cas1.Origin = 'Phone';
                cas1.Impact__c = 'Low';
                cas1.Severity__c = 'Minor';
                cas1.Type = 'Bridge';
            casesToInsert.add(cas1);
         }

        Test.startTest();
            insert casesToInsert; 
        Test.stopTest();  

        System.debug('Expected: 2, actual: ' + Limits.getEmailInvocations());  
    }
}

I can see the empty AggregateResult debug and the Trigger Results showing that Account that was created, but then nothing.

!]1

enter image description here

  • The async testing flag has nothing to do with the failures of these tests. What do your debug logs tell you about which branches are executing? I'd strongly recommend rethinking that runOnce pattern; I don't think it's at fault here but it causes lots of nasty behaviors. – David Reed Nov 22 '19 at 16:51
  • Another note, there is never any reason to have more than one email invocation from a single trigger. You should combine all of the messages and send them with one call to Messaging.sendEmail. – Adrian Larson Nov 22 '19 at 17:00
  • The log lines shown there are not coming from this trigger. Consider adding System.debug() calls to show where the path of execution goes, or use the Apex replay debugger. – David Reed Nov 22 '19 at 17:57
1

You're trying to query for records in a before insert trigger that are currently being processed by the trigger; i.e., have not yet been committed to the database and cannot be seen via SOQL.

Trigger is before insert:

trigger CaseCountAlertTrigger on Case (before insert) {

Your test class performs exactly one DML operation:

    Test.startTest();
        insert casesToInsert; 
    Test.stopTest();  

As a result, when you run your aggregate query:

List < AggregateResult > AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co

there is nothing in the database to return. All N cases are in Trigger.new, but as it's before insert they have no Ids and haven't been committed yet.

Either (a) run the trigger after insert (which I think makes more sense in this use case) or (b) perform multiple DML inserts in your test case so that the responsive Cases will be committed to the database by the time you attempt to test the trigger's behavior.

  • I just realized that, thank you. In all of my copy/paste, I didn't look too close. Thanks – Tim Nov 24 '19 at 20:54
0

Put your assert after the stop test - start test stop test is supposed to enclose the asynchronous code that you want to run, and wait for it to complete.

Then you can make your assertion after it has finished.

  • Thank you for the response, but I am receving same result of `2 expected, 0 actual" – Tim Nov 22 '19 at 17:25
  • Could this be the issue - salesforce.stackexchange.com/questions/252796/… - a problem with assert either inside or outside the starttest/stop test. Also - is your trigger doing what you want it to do ? I'd assume that that SOQL query would only return accounts with 8 cases created in the last 7 days which are currently being inserted or updated. So, if you are inserting all cases at once, it'll work, otherwise not. – eaeaoo Nov 22 '19 at 19:55
  • I have debugged the number of emails inside and outside of the test start/stop. Both result in a 0 emails sent. Also, do you know what the SOQL would look like for cases added over a few days and not added at the same time? – Tim Nov 22 '19 at 21:09
  • Yes, according to the answer from the link above it isn't possible to test for sent emails in this way since if you put it inside the test start/stop emaithe assert can't measure the email (since it is a future method), while outside it is operating in a different context so it can't detect the sent emails - you have to rewrite to test in some other way. – eaeaoo Nov 22 '19 at 21:53
  • SOQL - extract the account ids from the trigger cases, stick it in a list or set, use your same query but remove the AND id IN :Trigger.new And replace with AND accountId IN accountList ? – eaeaoo Nov 22 '19 at 22:00
0

I have no idea how but issue resolved. This was after a recent Sandbox refresh. I copied/pasted and renamed the trigger. No issues. I don't have an explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.