From 736d43fbd22384c79cf11836a918a2a7a9ebc0e5 Mon Sep 17 00:00:00 2001 From: Kipa24 Date: Tue, 2 Jul 2024 21:38:01 +0530 Subject: [PATCH] ALR-1707 --- .../default/classes/ScheduleSendEmail.cls | 159 ++++++++------- .../default/classes/ScheduledEmailTrigger.cls | 184 +++++++++++------- .../classes/ScheduledEmailTriggerTest.cls | 31 ++- 3 files changed, 226 insertions(+), 148 deletions(-) diff --git a/src/main/default/classes/ScheduleSendEmail.cls b/src/main/default/classes/ScheduleSendEmail.cls index 46c7197e..976d0962 100644 --- a/src/main/default/classes/ScheduleSendEmail.cls +++ b/src/main/default/classes/ScheduleSendEmail.cls @@ -10,121 +10,134 @@ public with sharing class ScheduleSendEmail implements Schedulable { public static Set accountIds = new Set(); public void execute(SchedulableContext sc) { - try { + try { Map> accountIdToContactIdsMap = new Map>(); - List accounts = [ + List accounts = [ SELECT Id ,ParentId FROM Account WHERE Status__c IN ('Registered Active', 'Registered Active with Conditions', 'Registered Active Progressive Enforcement') ]; - - for (Account acc : accounts) { + + for (Account acc : accounts) { accountIds.add(acc.Id); accountIds.add(acc.ParentId); accountIdToContactIdsMap.put(acc.Id, new Set()); accountIdToContactIdsMap.put(acc.ParentId, new Set()); } - - Map accountIdToAccountMap = new Map([ + + Map accountIdToAccountMap = new Map([ SELECT Id,parentId, - (SELECT Id, ContactId, Contact.Name, Contact.Email - FROM AccountContactRelations - WHERE IsActive = true AND Contact.Email != null) + (SELECT Id, ContactId, Contact.Name, Contact.Email + FROM AccountContactRelations + WHERE IsActive = true AND Contact.Email != null) FROM Account WHERE Id IN :accountIds ]); - + for (Account account : [ - SELECT parentId, - (SELECT Id, ContactId, Contact.Name, Contact.Email - FROM AccountContactRelations - WHERE IsActive = true AND Contact.Email!= null) - FROM Account - WHERE Id IN : accountIds -]) { - accountIdToAccountMap.put(account.Id, account); -} - + SELECT parentId, + (SELECT Id, ContactId, Contact.Name, Contact.Email + FROM AccountContactRelations + WHERE IsActive = true AND Contact.Email!= null) + FROM Account + WHERE Id IN : accountIds + ]) { + accountIdToAccountMap.put(account.Id, account); + } + for (Account acc : accountIdToAccountMap.values()) { for (AccountContactRelation acr : acc.AccountContactRelations) { accountIdToContactIdsMap.get(acc.Id).add(acr.ContactId); } } - + List contactIdsList = new List(); for (Set contactIds : accountIdToContactIdsMap.values()) { contactIdsList.addAll(contactIds); } - - if (!contactIdsList.isEmpty()) { + + if (!contactIdsList.isEmpty()) { sendRenewalDueEmail(contactIdsList); } - + } catch (Exception e) { System.debug('Exception occurred in execute method: ' + e.getMessage()); } - - } + + } public static void sendRenewalDueEmail(List contactIds) { + List accListforKeepingIds = new List(); try { - EmailTemplate emailTemplate = getEmailTemplate('Upcoming_Renewal_Email_Template'); - - OrgWideEmailAddress orgWideAddr = [ - SELECT Id, DisplayName, Address - FROM OrgWideEmailAddress - WHERE DisplayName = 'ALR Support Email' - ]; - - List contactRec =[Select Id,Email from Contact WHERE Id IN: contactIds]; - - Integer batchSize = 100; - List> emailBatches = new List>(); - List emails = new List(); - for (Contact contact : contactRec){ - Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); - email.setTemplateId(emailTemplate.Id); - email.setOrgWideEmailAddressId(orgWideAddr.Id); - email.setToAddresses(new String[] {contact.Email}); - email.setTargetObjectId(contact.Id); - String emailSubject = emailTemplate.Subject; - String emailBody = emailTemplate.HtmlValue; - email.setSubject(emailSubject); - email.setHtmlBody(emailBody); - emails.add(email); - if (emails.size() == batchSize) { - emailBatches.add(emails); - emails = new List(); + EmailTemplate emailTemplate = getEmailTemplate('Upcoming_Renewal_Email_Template'); + + OrgWideEmailAddress orgWideAddr = [ + SELECT Id, DisplayName, Address + FROM OrgWideEmailAddress + WHERE DisplayName = 'ALR Support Email' + ]; + List AccountcontactRecList = [SELECT Id, AccountId, Account.Name, ContactId, Contact.Email, Contact.IsEmailBounced FROM AccountContactRelation WHERE ContactId IN :contactIds]; + + for(AccountContactRelation AccountconList : AccountcontactRecList){ + accListforKeepingIds.add(AccountconList.ContactId); } + + List emails = new List(); + Map> processedEmails = new Map>(); + + for (AccountContactRelation acrList : AccountcontactRecList) { + if (acrList.contact.Email != null) { + String key = acrList.AccountId + '_' + acrList.contact.Email.toLowerCase(); + if (!processedEmails.containsKey(key)) { + Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); + email.setTemplateId(emailTemplate.Id); + email.setOrgWideEmailAddressId(orgWideAddr.Id); + email.setToAddresses(new String[]{acrList.contact.Email}); + email.setTargetObjectId(acrList.contact.Id); + String emailBody = emailTemplate.HtmlValue; + String emailSubject = emailTemplate.Subject; + email.setSubject(emailSubject); + email.setHtmlBody(emailBody); + emails.add(email); + processedEmails.put(key, new List{acrList.contact.Email}); + } + } + } + + + + if (!emails.isEmpty()) { + sendEmailBatch(emails); + } + } catch (Exception e) { + System.debug('Exception occurred in sendRenewalDueEmail method: ' + e.getMessage()); } - if (!emails.isEmpty()) { - emailBatches.add(emails); - } - for (List emailBatch : emailBatches) { + } + + public static void sendEmailBatch(List emailBatch) { + for (Messaging.SingleEmailMessage email : emailBatch) { try { - List results = Messaging.sendEmail(emailBatch); - for (Integer i = 0; i < results.size(); i++) { - if (results[i].isSuccess()) { - System.debug('Email sent successfully to ' + emailBatch[i].getToAddresses()[0]); + List singleEmailList = new List(); + singleEmailList.add(email); + List results = Messaging.sendEmail(singleEmailList); + + if (results[0].isSuccess()) { + System.debug('Email sent successfully to ' + email.getToAddresses()[0]); + } else { + String errorMessage = results[0].getErrors()[0].getMessage(); + if (errorMessage.contains('EMAIL_ADDRESS_BOUNCED')) { + System.debug('Bounced email address: ' + email.getToAddresses()[0]); } else { - String errorMessage = results[i].getErrors()[0].getMessage(); - if (errorMessage.contains('EMAIL_ADDRESS_BOUNCED')) { - System.debug('Bounced email address: ' + emailBatch[i].getToAddresses()[0]); - } else { - System.debug('Failed to send email to ' + emailBatch[i].getToAddresses()[0] + - '. Error message: ' + errorMessage); - } + System.debug('Failed to send email to ' + email.getToAddresses()[0] + + '. Error message: ' + errorMessage); } } } catch (Exception e) { - System.debug('Exception occurred in sendEmails method: ' + e.getMessage()); + System.debug('Exception occurred while sending email to ' + email.getToAddresses()[0] + ': ' + e.getMessage()); } } - }catch (Exception e) { - System.debug('Exception occurred in sendRenewalDueEmail method: ' + e.getMessage()); - } } - + public static EmailTemplate getEmailTemplate(String templateDevName) { EmailTemplate emailTemplateRec = null; try { diff --git a/src/main/default/classes/ScheduledEmailTrigger.cls b/src/main/default/classes/ScheduledEmailTrigger.cls index 7d8100b1..bec5598b 100644 --- a/src/main/default/classes/ScheduledEmailTrigger.cls +++ b/src/main/default/classes/ScheduledEmailTrigger.cls @@ -6,63 +6,67 @@ **/ public with sharing class ScheduledEmailTrigger implements Schedulable { - public static Set accountIds = new Set(); - - public void execute(SchedulableContext sc) { - try { - + public static Set accountIds = new Set(); + + public void execute(SchedulableContext sc) { + try { Map> accountIdToContactIdsMap = new Map>(); + List blaId = new List(); List fees = [ - SELECT Id,AccountId,Account.ParentId,ParentRecordId + SELECT Id, AccountId, Account.ParentId, ParentRecordId FROM RegulatoryTrxnFee WHERE FeeType__c = 'Renewal Unit Fee' - AND Status = 'Due' + AND Status = 'Due' ]; - for (RegulatoryTrxnFee fee : fees) { + + for (RegulatoryTrxnFee fee : fees) { accountIds.add(fee.AccountId); accountIds.add(fee.Account.ParentId); accountIdToContactIdsMap.put(fee.AccountId, new Set()); accountIdToContactIdsMap.put(fee.Account.ParentId, new Set()); + blaId.add(fee.ParentRecordId); } - - Map accountIdToAccountMap = new Map([ - SELECT Id,parentId, - (SELECT Id, ContactId, Contact.Name, Contact.Email - FROM AccountContactRelations - WHERE IsActive = true AND Contact.Email != null) + + Map accountIdToAccountMap = new Map([ + SELECT Id, ParentId, + (SELECT Id, ContactId, Contact.Name, Contact.Email + FROM AccountContactRelations + WHERE IsActive = true AND Contact.Email != null) FROM Account - WHERE Id IN: accountIds + WHERE Id IN :accountIds ]); - for (Account account : [ - SELECT parentId, - (SELECT Id, ContactId, Contact.Name, Contact.Email - FROM AccountContactRelations - WHERE IsActive = true AND Contact.Email!= null) - FROM Account - WHERE Id IN : accountIds -]) { - accountIdToAccountMap.put(account.Id, account); -} - for (Account acc : accountIdToAccountMap.values()) { + for (Account account : [ + SELECT ParentId, + (SELECT Id, ContactId, Contact.Name, Contact.Email + FROM AccountContactRelations + WHERE IsActive = true AND Contact.Email != null) + FROM Account + WHERE Id IN :accountIds + ]) { + accountIdToAccountMap.put(account.Id, account); + } + + for (Account acc : accountIdToAccountMap.values()) { for (AccountContactRelation acr : acc.AccountContactRelations) { accountIdToContactIdsMap.get(acc.Id).add(acr.ContactId); } } - List contactIdsList = new List(); + List contactIdsList = new List(); for (Set contactIds : accountIdToContactIdsMap.values()) { contactIdsList.addAll(contactIds); } - if(!contactIdsList.isEmpty()){ - sendRenewalDueEmail(contactIdsList); + if (!contactIdsList.isEmpty()) { + sendRenewalDueEmail(contactIdsList, blaId); } - } - catch (Exception e) { + } catch (Exception e) { System.debug('Exception occurred in execute method: ' + e.getMessage()); } - } - public static void sendRenewalDueEmail(List contactIds) { + } + + public static void sendRenewalDueEmail(List contactIds, List blaId) { + List accListforKeepingIds = new List(); try { EmailTemplate emailTemplate = getEmailTemplate('Renewal_Reminder_Email'); OrgWideEmailAddress orgWideAddr = [ @@ -70,61 +74,101 @@ public with sharing class ScheduledEmailTrigger implements Schedulable { FROM OrgWideEmailAddress WHERE DisplayName = 'ALR Support Email' ]; - - List contactRec = [SELECT Id, Email FROM Contact WHERE Id IN :contactIds]; - - Integer batchSize = 100; - List> emailBatches = new List>(); + + List AccountcontactRecList = [SELECT Id, AccountId, Account.Name, ContactId, Contact.Email, Contact.IsEmailBounced FROM AccountContactRelation WHERE ContactId IN :contactIds]; + + for(AccountContactRelation AccountconList : AccountcontactRecList){ + accListforKeepingIds.add(AccountconList.ContactId); + } + + List blaList = [SELECT Id, RenewalYear__c FROM BusinessLicenseApplication WHERE Id IN :blaId]; List emails = new List(); - for (Contact contact : contactRec) { - Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); - email.setTemplateId(emailTemplate.Id); - email.setOrgWideEmailAddressId(orgWideAddr.Id); - email.setToAddresses(new String[] {contact.Email}); - email.setTargetObjectId(contact.Id); - String emailSubject = emailTemplate.Subject; - String emailBody = emailTemplate.HtmlValue; - email.setSubject(emailSubject); - email.setHtmlBody(emailBody); - emails.add(email); - if (emails.size() == batchSize) { - emailBatches.add(emails); - emails = new List(); + Map> processedEmails = new Map>(); + + for (BusinessLicenseApplication blaRec : blaList) { + for (AccountContactRelation acrList : AccountcontactRecList) { + if (acrList.contact.Email != null) { + String key = acrList.AccountId + '_' + acrList.contact.Email.toLowerCase(); + if (!processedEmails.containsKey(key)) { + Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); + email.setTemplateId(emailTemplate.Id); + email.setOrgWideEmailAddressId(orgWideAddr.Id); + email.setToAddresses(new String[]{acrList.contact.Email}); + email.setTargetObjectId(acrList.contact.Id); + String emailBody = replaceMergeFields(emailTemplate, blaRec, acrList.Account.Name); + String emailSubject = emailTemplate.Subject; + email.setSubject(emailSubject); + email.setHtmlBody(emailBody); + emails.add(email); + processedEmails.put(key, new List{acrList.contact.Email}); + } + } } + } + + if (!emails.isEmpty()) { - emailBatches.add(emails); + sendEmailBatch(emails); } - for (List emailBatch : emailBatches) { - try { - List results = Messaging.sendEmail(emailBatch); - for (Integer i = 0; i < results.size(); i++) { - if (results[i].isSuccess()) { - System.debug('Email sent successfully to ' + emailBatch[i].getToAddresses()[0]); + } catch (Exception e) { + System.debug('Exception occurred in sendRenewalDueEmail method: ' + e.getMessage()); + } +} + + public static void sendEmailBatch(List emailBatch) { + for (Messaging.SingleEmailMessage email : emailBatch) { + try { + List singleEmailList = new List(); + singleEmailList.add(email); + List results = Messaging.sendEmail(singleEmailList); + + if (results[0].isSuccess()) { + System.debug('Email sent successfully to ' + email.getToAddresses()[0]); } else { - String errorMessage = results[i].getErrors()[0].getMessage(); + String errorMessage = results[0].getErrors()[0].getMessage(); if (errorMessage.contains('EMAIL_ADDRESS_BOUNCED')) { - System.debug('Bounced email address: ' + emailBatch[i].getToAddresses()[0]); + System.debug('Bounced email address: ' + email.getToAddresses()[0]); } else { - System.debug('Failed to send email to ' + emailBatch[i].getToAddresses()[0] + - '. Error message: ' + errorMessage); + System.debug('Failed to send email to ' + email.getToAddresses()[0] + + '. Error message: ' + errorMessage); } } + } catch (Exception e) { + System.debug('Exception occurred while sending email to ' + email.getToAddresses()[0] + ': ' + e.getMessage()); } - } catch (Exception e) { - System.debug('Exception occurred in sendEmails method: ' + e.getMessage()); } } - } catch (Exception e) { - System.debug('Exception occurred in sendRenewalDueEmail method: ' + e.getMessage()); + + public static String replaceMergeFields(EmailTemplate emailTemplate, BusinessLicenseApplication blaRec, String name) { + String mergeFieldValue = ''; + try { + for (TemplateMergeFieldMapping__mdt templateMapping : TemplateMergeFieldMapping__mdt.getAll().values()) { + if (templateMapping.EmailTemplate__c == emailTemplate.Id && templateMapping.ObjectName__c == 'Account') { + emailTemplate.HtmlValue = emailTemplate.HtmlValue.replace(templateMapping.MergeField__c, name); + } else if (templateMapping.EmailTemplate__c == emailTemplate.Id && templateMapping.ObjectName__c == 'BusinessLicenseApplication') { + if (templateMapping.FieldAPIName__c == 'RenewalYear__c') { + emailTemplate.HtmlValue = emailTemplate.HtmlValue.replace(templateMapping.MergeField__c, + Date.valueOf(blaRec.get(templateMapping.FieldAPIName__c)).format()); + } else { + emailTemplate.HtmlValue = emailTemplate.HtmlValue.replace(templateMapping.MergeField__c, + blaRec.get(templateMapping.FieldAPIName__c).toString()); + } + } else if (templateMapping.EmailTemplate__c == emailTemplate.Id && templateMapping.MergeFieldFormula__c == 'nextYear') { + emailTemplate.HtmlValue = emailTemplate.HtmlValue.replace(templateMapping.MergeField__c, BCMOH_Constants.nextYear); + } + } + } catch (Exception err) { + System.debug('Exception occurred in replaceMergeFields method: ' + err.getMessage()); + } + return emailTemplate.HtmlValue; } -} + public static EmailTemplate getEmailTemplate(String templateDevName) { EmailTemplate emailTemplateRec = null; - List contactIdsList = new List(); try { emailTemplateRec = [ - SELECT Id, DeveloperName, Subject, HtmlValue ,Body + SELECT Id, DeveloperName, Subject, HtmlValue, Body FROM EmailTemplate WHERE DeveloperName = :templateDevName LIMIT 1 diff --git a/src/main/default/classes/ScheduledEmailTriggerTest.cls b/src/main/default/classes/ScheduledEmailTriggerTest.cls index 2efe5b1f..f4ada919 100644 --- a/src/main/default/classes/ScheduledEmailTriggerTest.cls +++ b/src/main/default/classes/ScheduledEmailTriggerTest.cls @@ -44,6 +44,8 @@ private class ScheduledEmailTriggerTest { System.assertEquals(True, emailTem.size()>0, 'No Email is sent'); } + + @isTest static void testSendRenewalDueEmail() { @@ -53,15 +55,34 @@ private class ScheduledEmailTriggerTest { Email = 'test.contact@example.com' ); insert con; - + + List contactIds = new List{ con.Id }; + List blaId = new List(); + Test.startTest(); - - List contactIds = new List{ con.Id }; - ScheduledEmailTrigger.sendRenewalDueEmail(contactIds); - + ScheduledEmailTrigger.sendRenewalDueEmail(contactIds , blaId); + //sendEmailBatch Test.stopTest(); List emailTem = [SELECT Id FROM EmailTemplate]; System.assertEquals(True, emailTem.size()>0, 'No Email is sent'); } + + @isTest + static void testSendEmailBatch_Success() { + Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); + email.setToAddresses(new List{'test@example.com'}); + email.setSubject('Test Subject'); + email.setPlainTextBody('Test Body'); + + List emailBatch = new List(); + emailBatch.add(email); + + Test.startTest(); + ScheduledEmailTrigger.sendEmailBatch(emailBatch); + Test.stopTest(); + + List emailTem = [SELECT Id FROM EmailTemplate]; + System.assertEquals(True, emailTem.size()>0, 'No Email is sent'); + } } \ No newline at end of file