0

This email will send an email alert when an account has 8 cases open within 7 days. The email is being sent, but multiple emails for the Same account are being sent. I believe it has something to do with the loop creating the message.

*Edit, Judging by the debug lines in the console, the trigger is only firing once. For each record that sends an email, there is a duplicate email sent. I have updated my code as well.

Trigger:

    trigger CaseHandlerCountAlert on Case (after insert, after update) {

            If(!TrggrUtility.RunOnce) 
        {
            //Case trigger that will send email alert when 8 cases are created within 7 days.



Set <String> ListOfMessages = new Set <String>();
    Set <Id> AcctIds = new Set <Id>();


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


                                 FROM Case
                                                WHERE CreatedDate = LAST_N_DAYS:7
                                                GROUP BY Account.Name, AccountId
                                                HAVING COUNT(Id) >= 8
                                               ];

Map < Id, String > accountIdEmailmessageMap = new Map < Id, String > ();

Integer d=0;
while(d<AggregateResultList.size()){
    for (AggregateResult aggr: AggregateResultList){
            String messageToSend =+ 'Account name: ' + aggr.get('name') +
                ' has ' + (Integer) aggr.get('co') +
                ' cases opened in the last 8 days.';
            Id accId = (Id) aggr.get('AccountId');
            accountIdEmailmessageMap.put(accId, messageToSend);
            AcctIds.add(accId);
        d++;
    }  
     }

System.debug('Results from Trigger: ' + AggregateResultList);
List < Case > caseList = [SELECT Id, AccountId, Account.Name, Parent_Project_if_applicable__r.Implementation_status__c,
                          Parent_Project_if_applicable__r.PM_Implementation_Status__c,
                          Parent_Project_if_applicable__r.RCM_Implementation_Status__c,
                          Parent_Project_if_applicable__r.Resource_Coordinator_Email__c,
                          Parent_Project_if_applicable__r.Client_Advisor_Email__c                      
                          FROM Case
                          WHERE AccountId IN: AcctIds];

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



for (Case cl: caseList) {

    if (cl.Parent_Project_if_applicable__r.Implementation_status__c == 'Live - Closed Project' ||
        cl.Parent_Project_if_applicable__r.PM_Implementation_Status__c == 'Live - Closed Project' ||
        cl.Parent_Project_If_Applicable__r.RCM_Implementation_Status__c == 'Live - Closed Project') {

            String messageBody = accountIdEmailmessageMap.get(cl.AccountId);

            List<String> emailaddr = new List<String>();
            emailaddr.add('TestingEmail@gmail.com');  

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setSenderDisplayName('Support');
            mail.setToAddresses(emailaddr);   
            mail.Subject = 'Multiple cases created alert message';
            mail.setPlainTextBody(messageBody);
            lstASingleEmailMessage.add(mail);
            System.debug('The message Body is: ' + messageBody);
            break;


        }else{
            String messageBody1 = accountIdEmailmessageMap.get(cl.AccountId);        

            List<String> emailAdds = new List<String>();
            emailAdds.add(cl.Parent_Project_if_applicable__r.Resource_Coordinator_Email__c);
            emailAdds.add(cl.Parent_Project_if_applicable__r.Client_Advisor_Email__c); 

            Messaging.SingleEmailMessage amail = new Messaging.SingleEmailMessage();
            amail.SetSenderDisplayName('Support');
            amail.setToAddresses(emailAdds);
            amail.Subject = 'Multiple cases created alert message';
            amail.setPlainTextBody(messageBody1);
            lstBSingleEmailMessage.add(amail);


        }  
}


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



    System.debug('Email Message at end: ' + lstASingleEmailMessage[0]);
    System.debug('Emails sent: ' + limits.getEmailInvocations());
    boolean RunOnce = False;
}
}

RunOnce Method:

    Public class TrggrUtility{

   public static boolean RunOnce = False;

}

Test class:

    @isTest
private class TestCaseHandlerAlert {

  @testSetup static void setup(){
        Account a = new Account();
        Account b = new Account();
            a.name = 'testacctIfBlock';
            b.name = 'testacctElseBlock';

        //Insert Accounts
            insert a;
            insert b;

         //Create User:
        User tuser = new User(  firstname = 'tuserFname',
                            lastName = 'tuserLastname',
                            email = 'test@testingTrigger.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;

    }




    @isTest static void DontSendNotLimit(){
            // Send to Global Email Address 
            List<Case> casestoInsertIf = new List<Case>();  

        //Create Project
        Milestone1_Project__c project1 = new Milestone1_Project__c();
            //project.RecordTypeId = '01214000001RYp2AAG';
            project1.Name = 'triggerProjectIFBLOCK';
            project1.RCM_Implementation_Status__c= 'LIVE - CLOSED PROJECT';
            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;  
                insert project1;

        for (Integer i=1; i<4; i++){
            Case c1 = new Case();
                c1.AccountId = [Select Id FROM Account Where name ='testacctIfBlock'].id;
                c1.Origin = 'Phone';
                c1.Impact__c = 'Low';
                c1.Severity__c = 'Minor';
                c1.Type = 'Bridge';
                c1.Parent_Project_if_applicable__c = project1.id;
            casesToInsertIf.add(c1);
         }

        Test.startTest();
            insert casesToInsertIf; 
            System.debug('Emails Sent, should be zero 0, Actual is:  ' + Limits.getEmailInvocations()); 
        //  System.assertEquals(0, Limits.getEmailInvocations());
        Test.stopTest();


    }







@isTest static void SendElseBlock (){
        // Send to Global Email Address 
        List<Case> casestoInsertIf = new List<Case>();  

    //Create Project
    Milestone1_Project__c project1 = new Milestone1_Project__c();
        //project.RecordTypeId = '01214000001RYp2AAG';
        project1.Name = 'triggerProjectIFBLOCK';
        project1.RCM_Implementation_Status__c = 'DISCOVERY & DESIGN';
        project1.PM_Implementation_Status__c = 'DISCOVERY & DESIGN';
        project1.Implementation_Status__c = 'DISCOVERY & DESIGN';
        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;  
            insert project1;

    for (Integer i=1; i<10; i++){
        Case c1 = new Case();
            c1.AccountId = [Select Id FROM Account Where name ='testacctIfBlock'].id;
            c1.Origin = 'Phone';
            c1.Impact__c = 'Low';
            c1.Severity__c = 'Minor';
            c1.Type = 'Bridge';
            c1.Parent_Project_if_applicable__c = project1.id;
        casesToInsertIf.add(c1);
     }
        Test.startTest();
            insert casesToInsertIf;
                 System.debug('Emails Sent, should be zero 2, Actual is:  ' + Limits.getEmailInvocations()); //Debug shows 6 emails sent
            //   System.assertEquals(2, Limits.getEmailInvocations());
        Test.stopTest();




    }


@isTest static void SendIfBlock (){
        // Send to Global Email Address 
        List<Case> casestoInsertIf = new List<Case>();  

    //Create Project
    Milestone1_Project__c project1 = new Milestone1_Project__c();
        //project.RecordTypeId = '01214000001RYp2AAG';
        project1.Name = 'triggerProjectIFBLOCK';
        project1.RCM_Implementation_Status__c = 'LIVE - CLOSED PROJECT';
        project1.PM_Implementation_Status__c = 'LIVE - CLOSED PROJECT';
        project1.Implementation_Status__c = 'LIVE - CLOSED PROJECT';
        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;  
            insert project1;

    for (Integer i=1; i<10; i++){
        Case c1 = new Case();
            c1.AccountId = [Select Id FROM Account Where name ='testacctIfBlock'].id;
            c1.Origin = 'Phone';
            c1.Impact__c = 'Low';
            c1.Severity__c = 'Minor';
            c1.Type = 'Bridge';
            c1.Parent_Project_if_applicable__c = project1.id;
        casesToInsertIf.add(c1);
     }

    Test.startTest();
        insert casesToInsertIf;
            System.debug('Emails Sent, should be zero 1, Actual is:  ' + Limits.getEmailInvocations()); //Debug shows 6 emails sent
     //     System.assertEquals(1, Limits.getEmailInvocations());
    Test.stopTest();

    }

}
  • 1
    More likely is that you probably have a workflow rule that performs a field update (or a process builder) that causes you trigger to be run a second time. – Derek F Nov 16 at 14:00
  • have you written any test class to assert this that emails are sent once? – Pranay Jaiswal Nov 16 at 14:09
  • @Pranay Just added my test class. – Tim Nov 16 at 14:40
  • 2
    static flags to prevent recursion have all sorts of issues when transaction exceeds 200 recs; better to use Id sets. There are lots of examples elsewhere in SFSE on this topic – cropredy Nov 17 at 2:10
  • 1
    Much better to record that the email was sent to a specific user. The great thing about this is the the record will be reverted if the overall flow gets reverted due to some issue, so a re-try can be performed. – Phil W Nov 17 at 10:43

Your Answer

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

Browse other questions tagged or ask your own question.