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
Lindsay TackettLindsay Tackett 

Approval Process Approval Question

Good Morning All!

In my organization, we have created an Approval Process on a custom object (Job) which gets automatically submited to a specific role (GM) 50 days after "Contract Date."  The business has now requested that after 3 days, if the GM has not approved or declined the request, that it is automatically marked as approved.

Is there anyway to create an Apex Class or trigger with these requirements?  I was thinking to add a step to my Process Builder with that criteria to fire an Apex Class if the GM Approved and GM Declined date are both blank after 3 days of the approval process start date but not sure how to approve via that Apex Class.  I've found a lot of posts about submitting and then approving a request but having trouble locating anything about approving a pending request.

Thanks for any help!
Best Answer chosen by Lindsay Tackett
Arunkumar RArunkumar R
Hi Lindsay,

You have to write a batch class. I have posted sample code here and update query according to your need.
 
global class AutoApproval implements Database.batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext info){ 
        return Database.getQueryLocator('SELECT Id, CaseNumber, Status FROM Case WHERE IsClosed=FALSE'); //Adjust your query based on your need
    } 
    
    global void execute(Database.BatchableContext info, List<Case> caseList){ // Update List<Case> to your custom object.
        List<Approval.ProcessWorkitemRequest> approvalActions = new List<Approval.ProcessWorkitemRequest>();
        
        for(ProcessInstanceWorkitem workItem : [SELECT Id, ProcessInstanceId FROM ProcessInstanceWorkitem WHERE ProcessInstance.TargetObjectId IN : caseList]){
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setWorkitemId(workItem.Id);
            req.setAction('Approved');
            req.setComments('Auto Approved');
            approvalActions.add(req);
        }
        
        if(!approvalActions.isEmpty()){
            Approval.ProcessResult[] processResults = Approval.process(approvalActions);
        }      
    }
    
    global void finish(Database.BatchableContext info){
    }
}

You can execute a batch or schedule it accordingly.