function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Myron FairMyron Fair 

Apex Class Help for Auto-Expiring/Termination of Contracts

I have recently taken over as the admin and I am going through all of the currenty Apex Classes and have stumbled upon one that I can't seem to properly test for confirmation purposes. This particular class is suppose to be responsible for auto-expiring and terminating contracts based on the given criteria. When I create test records with the suspected criteria, the trigger seems to not happen, the records status' do not change. I don't know what I'm missing or if it's something in the code itself. The criteria for the test that I perform is below, and I typically set the record to expire or terminate the very next day. Please help me understand what this class is suppose to do!!!

Agreement Expiration
1.   All Record Types excluding ‘ Bulk Purchase Contract’, Bulk Sales Contract’, and ‘Bunker Sales Contract’.
2.  Agreement End Date: Today
3.  Auto Renew: False
4.  Evergreen: False
5.  Agreement Status: Does not equal to ‘Expired’ or ‘Terminated’.
*Once the Agreement End date occurs, the status of the record should update to Expired.

Agreement Termination
1.   All Record Types excluding ‘ Bulk Purchase Contract’, Bulk Sales Contract’, and ‘Bunker Sales Contract’.
2.   Agreement Status: Does not equal to ‘Expired’ or ‘Terminated’.
3.   Termination Date = Today
*Once the Termination Date occurs, the status of the record should update to Terminated.

Here is the Code.
 
global class AgreementNotifierScheduler implements Schedulable {
    global void execute(SchedulableContext ctx) {
        Map<Id, List<Apttus__APTS_Agreement__c>> expiredAgreementsMap = new Map<Id, List<Apttus__APTS_Agreement__c>>();
        Map<Id, List<Apttus__APTS_Agreement__c>> terminatedAgreementsMap = new Map<Id, List<Apttus__APTS_Agreement__c>>();
        Map<Id, List<Apttus__APTS_Agreement__c>> almostExpiredAgreementsMap = new Map<Id, List<Apttus__APTS_Agreement__c>>();
        Id recType1 = Schema.SObjectType.Apttus__APTS_Agreement__c.getRecordTypeInfosByName().get('Bulk Purchase Contract').getRecordTypeId();
        Id recType2 = Schema.SObjectType.Apttus__APTS_Agreement__c.getRecordTypeInfosByName().get('Bulk Sales Contract').getRecordTypeId();
        Id recType3 = Schema.SObjectType.Apttus__APTS_Agreement__c.getRecordTypeInfosByName().get('Bunker Sales Contract').getRecordTypeId();
        List<Messaging.SingleEmailMessage> emailsToBeSent = new List<Messaging.SingleEmailMessage>();
        List<Apttus__APTS_Agreement__c> agreementsToUpdate = new List<Apttus__APTS_Agreement__c>();
        List<Apttus__APTS_Agreement__c> allAgreements = [SELECT Id, 
                                                         OwnerId, 
                                                         Name,
                                                         Apttus__FF_Agreement_Number__c,
                                                         Apttus__Contract_End_Date__c, 
                                                         Apttus__Auto_Renewal__c, 
                                                         Evergreen__c,
                                                         Apttus__Termination_Date__c FROM Apttus__APTS_Agreement__c WHERE 
                                                         Apttus__Status_Category__c != 'Terminated' AND 
                                                         Apttus__Status_Category__c != 'Expired' AND
                                                         Apttus__Status__c != 'Superseded' AND
                                                         RecordTypeId !=: recType1 AND RecordTypeId !=: recType2 AND RecordTypeId !=: recType3 AND
                                                         ( (Apttus__Termination_Date__c <=: Date.today()) OR 
                                                           (Apttus__Contract_End_Date__c <=: Date.today() AND (Apttus__Auto_Renewal__c != TRUE AND Evergreen__c != TRUE)) OR
                                                           (Apttus__Contract_End_Date__c =: Date.today()+7 AND (Apttus__Auto_Renewal__c != TRUE AND Evergreen__c != TRUE))
                                                         )];
        
        for(Apttus__APTS_Agreement__c agreement : allAgreements)
        {
            if(agreement.Apttus__Termination_Date__c <= Date.today()){
                agreement.Apttus__Status_Category__c = 'Terminated';
                agreementsToUpdate.add(agreement);
                if(!terminatedAgreementsMap.containsKey(agreement.OwnerId)){
                    List<Apttus__APTS_Agreement__c> termListAgreementsNotFound = new List<Apttus__APTS_Agreement__c>();
                    termListAgreementsNotFound.add(agreement);
                    terminatedAgreementsMap.put(agreement.OwnerId, termListAgreementsNotFound);
                }
                else{
                    List<Apttus__APTS_Agreement__c> termListAgreements = terminatedAgreementsMap.get(agreement.OwnerId);
                    termListAgreements.add(agreement);
                    terminatedAgreementsMap.put(agreement.OwnerId, termListAgreements);
                }
            }
            else if(agreement.Apttus__Contract_End_Date__c <= Date.today() && (agreement.Apttus__Auto_Renewal__c != true && agreement.Evergreen__c != true)){
                agreement.Apttus__Status_Category__c = 'Expired';
                agreementsToUpdate.add(agreement);
                /*if(!expiredAgreementsMap.containsKey(agreement.OwnerId)){
                    List<Apttus__APTS_Agreement__c> expListAgreementsNotFound = new List<Apttus__APTS_Agreement__c>();
                    expListAgreementsNotFound.add(agreement);
                    expiredAgreementsMap.put(agreement.OwnerId, expListAgreementsNotFound);
                }
                else{
                    List<Apttus__APTS_Agreement__c> expListAgreements = expiredAgreementsMap.get(agreement.OwnerId);
                    expListAgreements.add(agreement);
                    expiredAgreementsMap.put(agreement.OwnerId, expListAgreements);
                }*/
            }
            else if(agreement.Apttus__Contract_End_Date__c == Date.today()+7 && (agreement.Apttus__Auto_Renewal__c != true && agreement.Evergreen__c != true)){
                if(!almostExpiredAgreementsMap.containsKey(agreement.OwnerId)){
                    List<Apttus__APTS_Agreement__c> almExpListAgreementsNotFound = new List<Apttus__APTS_Agreement__c>();
                    almExpListAgreementsNotFound.add(agreement);
                    almostExpiredAgreementsMap.put(agreement.OwnerId, almExpListAgreementsNotFound);
                }
                else{
                    List<Apttus__APTS_Agreement__c> almExpListAgreements = almostExpiredAgreementsMap.get(agreement.OwnerId);
                    almExpListAgreements.add(agreement);
                    almostExpiredAgreementsMap.put(agreement.OwnerId, almExpListAgreements);
                }
            }
        }
        Map<Id, String> emailAddressesMap = new Map<Id, String>();
        List<User> listOwners = [SELECT Id, Email FROM User WHERE Id IN: terminatedAgreementsMap.keyset() OR Id IN: expiredAgreementsMap.keyset() OR Id IN: almostExpiredAgreementsMap.keyset()];
        if(!listOwners.isEmpty()){
            for(User u : listOwners){
                emailAddressesMap.put(u.Id, u.Email);
            }
        }
        for(Id idOfTheOwner : terminatedAgreementsMap.keySet()){
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses = new String[] {emailAddressesMap.get(idOfTheOwner)};
                message.subject = 'Terminated Agreement Notification';
            String bodyMessage = 'This notice is to inform you of the following terminated contract in NuCM:\r\n \r\n';
            Integer counter = 0;
            for(Apttus__APTS_Agreement__c agg : terminatedAgreementsMap.get(idOfTheOwner)){
                counter++;
                bodyMessage += counter+'. Agreement Number: '+agg.Apttus__FF_Agreement_Number__c+'\r\n\r\n';
                bodyMessage += 'Agreement Name: '+agg.Name+'\r\n\r\n';
                bodyMessage += 'Agreement End Date: '+String.valueOf(agg.Apttus__Termination_Date__c)+'\r\n\r\n\r\n';
            }
            bodyMessage += 'Please review the Agreement Record(s) and take any appropriate actions, if necessary.\r\n\r\nThank you!\r\nNuCM Admin Team';
            message.plainTextBody = bodyMessage;
            emailsToBeSent.add(message);
        }
        /*for(Id idOfTheOwner : expiredAgreementsMap.keySet()){
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses = new String[] {emailAddressesMap.get(idOfTheOwner)};
                message.subject = 'Expired Agreement Notification';
            String bodyMessage = 'This notice is to inform you of the following expired contract in NuCM:\r\n \r\n';
            Integer counter = 0;
            for(Apttus__APTS_Agreement__c agg : expiredAgreementsMap.get(idOfTheOwner)){
                counter++;
                bodyMessage += counter+'. Agreement Number: '+agg.Apttus__FF_Agreement_Number__c+'\r\n\r\n';
                bodyMessage += 'Agreement Name: '+agg.Name+'\r\n\r\n';
                bodyMessage += 'Agreement End Date: '+String.valueOf(agg.Apttus__Contract_End_Date__c)+'\r\n\r\n\r\n';
            }
            bodyMessage += 'Please review the Agreement Record(s) and take any appropriate actions, if necessary.\r\n\r\nThank you!\r\nNuCM Admin Team';
            message.plainTextBody = bodyMessage;
            emailsToBeSent.add(message);
        }*/
        for(Id idOfTheOwner : almostExpiredAgreementsMap.keySet()){
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses = new String[] {emailAddressesMap.get(idOfTheOwner)};
                message.subject = '7 Days From Expiration Of Agreement';
            String bodyMessage = 'This notice is to inform you that the following agreements will expire in 7 days in NuCM:\r\n \r\n';
            Integer counter = 0;
            for(Apttus__APTS_Agreement__c agg : almostExpiredAgreementsMap.get(idOfTheOwner)){
                counter++;
                bodyMessage += counter+'. Agreement Number: '+agg.Apttus__FF_Agreement_Number__c+'\r\n\r\n';
                bodyMessage += 'Agreement Name: '+agg.Name+'\r\n\r\n';
                bodyMessage += 'Agreement End Date: '+String.valueOf(agg.Apttus__Contract_End_Date__c)+'\r\n\r\n\r\n';
            }
            bodyMessage += 'Please review the Agreement Record(s) and take any appropriate actions, if necessary. The agreement status will change to expired on the Agreement End Date.\r\n\r\nThank you!\r\nNuCM Admin Team';
            message.plainTextBody = bodyMessage;
            emailsToBeSent.add(message);
        }
        update agreementsToUpdate;
        Messaging.SendEmailResult[] results = Messaging.sendEmail(emailsToBeSent);
        /*if (results[0].success) {
            System.debug('The email was sent successfully.');
        } else {
            System.debug('The email failed to send: '
                         + results[0].errors[0].message);
        }*/
        /*system.debug('Agreements to be updated: '+agreementsToUpdate);
system.debug('Number of Agreements to be updated: '+agreementsToUpdate.size());
system.debug('Emails to be sent: '+emailsToBeSent);
system.debug('Number of Emails to be sent: '+emailsToBeSent.size());*/
    }
}

 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Myron,

Can you please check the status Catageory and status fields for the agreement. As per the code the batch only picks the agreements which has 

Apttus__Status__c not equal to 'Superseded'  AND
Apttus__Status_Category__c not equal to 'Terminated' or 'Expired'


Apart for this i dont see any issue with the test data.

If this solution helps, Please mark it as best answer.

Thanks,
 
Myron FairMyron Fair
Sai,

Thank you for the response. I've looked and tried to test this code as if and it seems that sometimes it triggers a change and other times it doesn't. It's as if there is another factor in play. Is this a scheduled class that essentially looks at every record and finds the one with the criteria as true and updates, or is this something that is needing an edit on the record to update?  Please advise.
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Mayron,

Yes it is a schedular class. This should have been scheduled at some time. It only considers the records which meets the above conditions at the time it runs. Please check the time of the schedular from
setup-> Scheduled jobs 

Thanks,