/** * Nightly recalculation of Trailing_12_Month_Revenue__c and Customer_Tier__c. * * Schedule with CustomerTierRecalcBatch.scheduleNightly(). Only accounts whose revenue or * tier changed are updated, keeping DML and trigger work proportional to real change. */ public inherited sharing class CustomerTierRecalcBatch implements Database.Batchable, Database.Stateful, Schedulable { public static final String JOB_NAME = 'Customer Tier Recalculation'; public static final String NIGHTLY_CRON = '0 0 2 * * ?'; public static final Integer BATCH_SIZE = 200; private static final Integer TRAILING_DAYS = 365; @TestVisible private Integer updatedCount = 0; @TestVisible private Integer failedCount = 0; public static Id scheduleNightly() { return System.schedule(JOB_NAME, NIGHTLY_CRON, new CustomerTierRecalcBatch()); } public void execute(SchedulableContext context) { Database.executeBatch(new CustomerTierRecalcBatch(), BATCH_SIZE); } public Database.QueryLocator start(Database.BatchableContext context) { return new AccountsSelector(System.AccessLevel.SYSTEM_MODE).queryLocatorForTierRecalc(); } public void execute(Database.BatchableContext context, List scope) { Map accountsById = new Map(scope); Map revenueByAccount = new OrdersSelector(System.AccessLevel.SYSTEM_MODE) .sumActivatedRevenueSince(accountsById.keySet(), Date.today().addDays(-TRAILING_DAYS)); CustomerTierCalculator calculator = new CustomerTierCalculator(); List changed = new List(); for (Account customer : scope) { Decimal revenue = CreditPolicy.nullToZero(revenueByAccount.get(customer.Id)); String tier = calculator.tierFor(revenue); if (customer.Trailing_12_Month_Revenue__c != revenue || customer.Customer_Tier__c != tier) { changed.add( new Account(Id = customer.Id, Trailing_12_Month_Revenue__c = revenue, Customer_Tier__c = tier) ); } } if (changed.isEmpty()) { return; } List results = Database.update(changed, false, System.AccessLevel.SYSTEM_MODE); for (Integer i = 0; i < results.size(); i++) { if (results[i].isSuccess()) { updatedCount++; } else { failedCount++; Logger.error( 'CustomerTierRecalcBatch.execute', 'Tier update failed: ' + results[i].getErrors(), null, changed[i].Id ); } } Logger.flush(); } public void finish(Database.BatchableContext context) { Logger.info( 'CustomerTierRecalcBatch.finish', 'Tier recalculation complete. Updated: ' + updatedCount + ', failed: ' + failedCount ); Logger.flush(); } }