I have a custom object called Daily Assessment and this object has a master detail relation ship with Entitlements. Every day a Daily Assessment record has to be under the entitlements (Meaning that daily assessment report was generated for that Entitlement).I wanted a Scheduled class which will fire an email if there are no child records created on the entitlement on any given day. The following is the code i have:
global class DailyAssessmentSchedulable implements Schedulable {
public static String emailAddress = '****.******@example.com';
global void execute(SchedulableContext ctx) {
List<Entitlement> entitlementList = new List<Entitlement>();
List<Entitlement> notificationList = new List<Entitlement>();
List<Daily_Assessment__c> dailyAssessmentList = new List<Daily_Assessment__c>();
MAP<Id, Entitlement> entitlementMap = new Map<Id, Entitlement>([SELECT Id,
Name,
(SELECT Id,
CreatedDate,
Entitlement_Name__c
FROM Daily_Assessments__r
WHERE CreatedDate = TODAY)
FROM Entitlement
WHERE Name LIKE '%MSO%']);
entitlementList = entitlementMap.values();
for(Entitlement ent : entitlementList){
//logic to decide which user has not submitted and
//add it to a list and send email using sendEmail() method
dailyAssessmentList = new List<Daily_Assessment__c>();
dailyAssessmentList = ent.Daily_Assessments__r;
if(dailyAssessmentList.isEmpty()){
notificationList.add(ent);
}
}
sendEmail(notificationList);
}
//send email method
private void sendEmail(List<Entitlement> notificationList){
if(notificationList != null){
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] {emailAddress};
message.subject = 'Entitlement Daily Assessment reports update';
message.plainTextBody = 'Daily Assessments for the following entitlements were not submitted today: ';
for(Entitlement ent : notificationList){
message.plainTextBody += ent.Name + ', ';
}
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
if (results[0].success) {
System.debug('The email was sent successfully.');
} else {
System.debug('The email failed to send: ' + results[0].errors[0].message);
}
}
}
}
The issue with this code is whenever i run this class it is looking for the entitlement's child record created date and if all the entitlements are having new child date on that calendar day then an empty Email is being sent with the foloowing text (Daily Assessments for the following entitlements were not submitted today). How can i add a condition so that i will not fire the email if the Entitlements have child records on a calendar day.
for (Entitlement ent : [select ...]) { if (!ent.Daily_Assessments__r.isEmpty()) notifcationList.add(ent);}