Untitled

 avatar
unknown
plain_text
2 months ago
2.9 kB
8
Indexable
public without sharing class LatestApprovalProcessBackfillBatch
    implements Database.Batchable<SObject>, Database.Stateful {

    private Integer updatedCount = 0;
    private Integer errorCount = 0;
    private Integer skippedCount = 0;

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([
            SELECT Id, Related_Record_Id__c, CreatedDate
            FROM Approval_Process__c
            WHERE Status__c = 'Active'
            AND Related_Record_Id__c != null
            ORDER BY Related_Record_Id__c, CreatedDate ASC
        ]);
    }

    public void execute(Database.BatchableContext context, List<Approval_Process__c> approvals) {
        Map<String, Map<Id, SObject>> objectApiNameToRecords = new Map<String, Map<Id, SObject>>();

        for (Approval_Process__c approval : approvals) {
            Id relatedRecordId;

            try {
                relatedRecordId = Id.valueOf(approval.Related_Record_Id__c);
            } catch (Exception e) {
                skippedCount++;
                continue;
            }

            Schema.SObjectType sObjectType = relatedRecordId.getSObjectType();
            Schema.DescribeSObjectResult describeResult = sObjectType.getDescribe();

            if (!describeResult.fields.getMap().containsKey('Latest_Approval_Process__c')) {
                skippedCount++;
                continue;
            }

            String objectApiName = describeResult.getName();

            if (!objectApiNameToRecords.containsKey(objectApiName)) {
                objectApiNameToRecords.put(objectApiName, new Map<Id, SObject>());
            }

            SObject recordToUpdate = sObjectType.newSObject(relatedRecordId);
            recordToUpdate.put('Latest_Approval_Process__c', approval.Id);

            objectApiNameToRecords.get(objectApiName).put(relatedRecordId, recordToUpdate);
        }

        for (String objectApiName : objectApiNameToRecords.keySet()) {
            List<SObject> recordsToUpdate = objectApiNameToRecords.get(objectApiName).values();

            Database.SaveResult[] results = Database.update(recordsToUpdate, false);

            for (Database.SaveResult result : results) {
                if (result.isSuccess()) {
                    updatedCount++;
                } else {
                    errorCount++;
                    System.debug(LoggingLevel.ERROR, result.getErrors());
                }
            }
        }
    }

    public void finish(Database.BatchableContext context) {
        System.debug('LatestApprovalProcessBackfillBatch updatedCount: ' + updatedCount);
        System.debug('LatestApprovalProcessBackfillBatch skippedCount: ' + skippedCount);
        System.debug('LatestApprovalProcessBackfillBatch errorCount: ' + errorCount);
    }
}
Editor is loading...
Leave a Comment