0

Scheduled job 'Entitlement Task Notificiations' threw unhandled exception.

caused by: System.NullPointerException: Attempt to de-reference a null object

Class.opentasks.doJob: line 40, column 1 Class.opentasks.execute: line 4, column 1

global class opentasks Implements Schedulable {

    global void execute (SchedulableContext ctx) {
        doJob();
    }

    public void doJob() {
        List<RecordType> recType = [SELECT id FROM RecordType WHERE name = 'Entitlement Task' AND sobjecttype = 'Task' AND IsActive = TRUE limit 1];
        List<messaging.SingleEmailMessage> allmails = new List<messaging.SingleEmailMessage>();

        Set<Id> users = new Set<Id>();
        Set<Id> etermIds = new Set<Id>();
        String Sub;
        List<Task> tasklistToday = new List<Task>();
        List<Task> tasklistMonday = new List<Task>();
        List<Task> tasklistMonthly = new List<Task>();
        List<Task> tasklistOverdue = new List<Task>();
        Integer daysInMonth = date.daysInMonth(system.today().year(), system.today().month());
        Date weekStart = system.today().toStartofWeek();
        Integer dayOfWeek = weekStart.daysBetween(system.today());
        Boolean Monday = dayOfWeek == 1;
        Boolean firstOfMonth = (system.today().Day() == 1);
        Integer daysBetween;
        DateTime activityDate;
        Date taskDate;
        Date today = System.today();
        String todaystring = today.format();
        Boolean futureTask;

        list<Task> open1 = [SELECT Id, OwnerId, WhoId, WhatId, ActivityDate, AssignedToEmailAddress__c,
                            Subject, Status, RecordTypeId, What.Name, Receive_Entitltement_Emails__c,
                            No_Daily_Task_Emails__c, No_Monthly_Task_Emails__c, No_Weekly_Task_Emails__c, No_Overdue_Task_Emails__c
                            FROM Task WHERE IsClosed=false AND RecordTypeId = :recType[0].Id
                            AND (ActivityDate = LAST_N_DAYS:30 OR ActivityDate = NEXT_N_DAYS:30)
                            ORDER BY OwnerId, ActivityDate, Subject];
        //system.debug('XXXX open1 size ' + open1.size());

        for (Task t :open1) {
            // only care about Tasks for Entitlement Terms
            if (String.valueof(t.WhatId).substring(0, 3) == 'a0Y') {
                users.add(t.OwnerId);
                etermIds.add(t.WhatId);                
            }
        }

        Map <Id, sm1e__smCObject_B__c> eterms = new Map<Id, sm1e__smCObject_B__c>([SELECT Id, Reference_Information__c, SpecialTrunc__c,  ET_Plant__c, ETCustomerNumber__c FROM sm1e__smCObject_B__c WHERE Id IN :etermIds]);
    List<Attachment> docs = new List<Attachment>([SELECT Id, ParentId, Name FROM Attachment WHERE ParentId = :etermIds AND Name Like 'Task Attachment%' ORDER BY Id]);        
        Map <Id, Attachment> etermDocs = new Map<Id, Attachment>();
        for (Attachment a :docs)
            etermDocs.put(a.ParentId, a);
        //system.debug('XXXX users ' + users.size() + ' eterms ' + eterms.size() + ' docs ' + docs.size() + ' etermDoc ' + etermDocs.size());

        for (Id uid :users) {
            tasklistOverdue.clear();
            tasklistMonday.clear();
            tasklistMonthly.clear();
            tasklistToday.clear();
            for (Task t :open1) {
                activityDate = t.ActivityDate.addDays(1);
                taskdate = activityDate.date();
                futureTask = (taskdate >= today);
                if (futureTask) {
                    daysbetween = today.daysbetween(taskdate);
                }
                if (t.OwnerId == uid) {
                    If (today == taskdate && !t.No_Daily_Task_Emails__c)
                        tasklistToday.add(t);
                    If (today > taskdate && !t.No_Overdue_Task_Emails__c)
                        tasklistOverdue.add(t);
                    If (Monday && futureTask && daysbetween < 7 && !t.No_Weekly_Task_Emails__c)
                        tasklistMonday.add(t);
                    If (FirstOfMonth && futureTask && daysbetween < daysInMonth && !t.No_Monthly_Task_Emails__c)
                        tasklistMonthly.add(t);
                }
            }

            if (tasklistToday.size() > 0) {
                Sub = 'NOTIFICATION: Due Today ' + todaystring;
                buildemails(tasklistToday, eterms, allmails, Sub, etermDocs);
            }
            if (tasklistMonday.size() > 0) {
                Sub = 'NOTIFICATION: Due This Week ' + todaystring;
                buildemails(tasklistMonday, eterms, allmails, Sub, etermDocs);
            }
            if (tasklistMonthly.size() > 0) {
                Sub = 'NOTIFICATION: Due This Month ' + todaystring;
                buildemails(tasklistMonthly, eterms, allmails, Sub, etermDocs);
            }
            if (tasklistOverdue.size() > 0) {
                Sub = 'NOTIFICATION: Past Due ' + todaystring;
                buildemails(tasklistOverdue, eterms, allmails, Sub, etermDocs);
            }            
        }
        Messaging.sendEmail(allmails);
    }

    public static void buildemails(List<Task>tasklist, Map<Id, sm1e__smCObject_B__c> eterms, messaging.SingleEmailMessage[] emails, String Sub, Map<Id, Attachment> etermDocs) {
        String[] toAddresses,bccAddresses;
        //system.debug('XXXX buildemails email ' + tasklist[0].AssignedToEmailAddress__c);
        //system.debug('XXXX buildmails tasks,terms,sub ' + tasklist + ' ' + eterms + ' ' + Sub);
        // if the user is not receiving emails, send them to admin for now while we test
        if (tasklist[0].Receive_Entitltement_Emails__c)
            toAddresses = new String[] {tasklist[0].AssignedToEmailAddress__c};
        else
            toAddresses = new String[] {'john.reed@powerfactorscorp.com'};
        messaging.SingleEmailMessage mail = new messaging.SingleEmailMessage();
        bccAddresses = new String[] {'john.reed@powerfactorscorp.com','steve.hanawalt@powerfactorscorp.com'};
        mail.setToAddresses(toAddresses);
        mail.setBccAddresses(bccAddresses);
        mail.setReplyTo('support@powerfactorscorp.com');
        mail.setOrgWideEmailAddressId('0D216000000L6O9');
        mail.setSubject(Sub + ' for ' + tasklist[0].AssignedToEmailAddress__c);
        String body = getTableEmailBody(tasklist, eterms, Sub, etermDocs);
        mail.setHtmlBody(body);
        emails.add(mail);            
    }

    public static string getTableEmailBody(List<Task> tsks, Map<Id, sm1e__smCObject_B__c> eterms, String Sub, Map<Id, Attachment> etermDocs) {
        Datetime due;
        Date dateDue;
        String htmlBody;
        Boolean futureTask;
        Attachment a;
        String Entitlement_Term_Prefix = Schema.SObjectType.sm1e__smCObject_B__c.getKeyPrefix(),taskWhatId;

        htmlBody = '<table border="2" bordercolor="#FFCC00" style="font-size:9px; font-family:sans-serif; background-color:#FFFFFF" cellpadding="5" cellspacing="5" >';
        htmlBody += '<caption>' + Sub + '</caption>';
        htmlBody += '<tr><th>Plant #</th><th>Plant Name</th><th>Subject</th><th>Reference Information</th><th>Status</th><th>Due Date</th><th>Link to Term</th><th>Completion Variance (Days)</th><th>Special Instructions (Truncated)</th><th>Link to Attachment</th></tr>';

        for(Task t : tsks) {           
            if (t.WhatId != null) {
                taskWhatId = t.WhatId;              
                if(taskWhatId.startsWith(Entitlement_Term_Prefix)) {
                    due = t.ActivityDate.AddDays(1);
                    String dt =  due.format('M/d/yy');
                    dateDue = t.ActivityDate;
                    futureTask = DateDue >= system.today();
                    Integer daysBetween = system.today().daysBetween(dateDue);                  
                    sm1e__smCObject_B__c etermr = eterms.get(t.WhatId);
                    a = etermDocs.get(t.WhatId);
                    htmlBody += '<tr><td>' + etermr.ETCustomerNumber__c + '</td><td>' + etermr.ET_Plant__c + '</td><td>' + t.Subject;
                    htmlBody += '</td><td>' + etermr.Reference_Information__c + '</td><td>' + t.Status + '</td><td>' + dt;
                    htmlBody += '</td><td>' + '<a href="https://na23.salesforce.com/' + t.WhatId + '">' + t.What.Name + '</a>' + '</td>';
                    htmlBody += '<td style="font-weight:bold; color:';
                    if (daysBetween <= 0)
                        htmlBody += '#ff0000';
                    else
                        htmlBody += '#66CD00';
                    htmlBody += '">' + daysBetween + '</td>';
                    htmlBody += '<td>' + etermr.SpecialTrunc__c + '</td>';
                    if (a != null)
                        htmlBody += '<td>' + '<a href="https://na23.salesforce.com/' + a.Id + '">' + a.Name + '</a>' + '</td>';
                    else
                        htmlBody += '<td>(N/A)</td>';
                    htmlBody += '</tr>';
                }
            }   
        }        
        htmlBody += '</table>';
        return htmlBody;
    }
}

This Schedule job runs everyday. But we received the unhandled exception error only yesterday. what's going wrong?

1

This line is giving you error.

if (String.valueof(t.WhatId).substring(0, 3) == 'a0Y') {

because if any of your task dosen't contain whatId then you will get null pointer exception so you need to update your condition and put a null check. You might also need to add this null check in all place where you are using this field.

if (t.WhatId != null && String.valueof(t.WhatId).substring(0, 3) == 'a0Y') {
| improve this answer | |

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.