+ Start a Discussion
EdCodeEdCode 

How to emulated a Process Builder Scheduled Action with Apex

Is there a way, with Apex, to deliver the folowing requirement:

When Now() falls withing 45 days before a deadline DateTime on the Account, then in such scenario:

First: verify if this Account already has a Case with criteria xyz; if such Case record already exist, update it;

Second: if no such Case exists, then create a Case with attributes xyz.

 
EdCodeEdCode
This the logic (diagram) that I need to implement in Apex:
User-added image
mritzimritzi
Assuming you have to do this using Apex Trigger Handler or Batch class, add following method wherever required after making required changes.
 
public static void myCustomMethod(List<Account> accountList){
    Set<Id> selectedAccIdSet = new Set<Id>();
    //Map<account Id, account>
    Map<Id, Account> accountMap = new Map<Id, Account>(accountList);
    Map<Id, Boolean> accIdCaseExistMap = new Map<Id, Boolean>();
    for(Account account : accountList){
        if(String.isNotBlank(account.Broker_KYC_Review__c)){
            selectedAccIdSet.add(account.Id);
            // set intially that this account doesn't has related case
            accIdCaseExistMap.put(account.Id, false);
        }
    }
    List<Case> caseList = new List<Case>([
        Select Id, AccountId, <Other fields>
        From Case
        Where AccountId IN:selectedAccIdSet
    ]);
    for(Case case : caseList){
        //mark that case exists for account in accIdCaseExistMap using AccountId
        accIdCaseExistMap.put(case.AccountId, true);

        // update fields of existing cases
        case.Name = 'update if required';
        //update other fields
        case.somefield__C = accountMap.get(case.AccountId).Some_Account_Field__c
    }
    //now wherever in accIdCaseExistMap  value is still false, it means cases doesnt exist for that account
    for(Id accId : accIdCaseExistMap.keySet()){
        if(accIdCaseExistMap.get(accId) == false){
            Case case  = new Case();
            case.AccountId = accId;
            case.name = 'some value as per requirement';
            case.Some_field__c = accountMap.get(accId).Some_Account_Field__c;
            // and other fields 
            caseList.add(case);
        }
    }
    Database.upsert(caseList, false);
}
change field api names, syntax as per your requirement.

If this helps solve your problem, please mark this as BEST ANSWER, so that others may benefit as well.
mritzimritzi
If the answer posted above has solved your issue, please mark it as best answer, or add details of any problems you faced after implementing suggestions