How the recent activity Apex Check works
AccountHasRecentActivityCheck is the Apex Check class that installs with Record Health Check. It
counts the Tasks and Events related to each Account in a date window and passes when the count meets
a minimum. Read its source as a reference implementation of the Record Health Check Apex plugin
interfaces: typed parameters, bulk queries, per-record recovery, and display text.
To configure a Check that uses this class, follow Check that an Account has recent activity. You do not need to deploy any code; the class is part of the package.
What the class does
Section titled “What the class does”| Step | What happens |
|---|---|
| Declares parameters | getDefinition() declares daysBack (default 30, range 1 to 3,650) and minimumActivities (default 1, range 1 to 1,000). capacity(200, true, 'LOW') accepts at most 200 records in one call; a larger scope returns UNABLE_ with PLUGIN_. The bulk-safe flag and LOW cost are advisory in this release. |
| Validates parameters | Record Health Check checks Apex Parameters (JSON) against the definition before evaluate runs. A wrong type, an unknown key, or a value out of range produces UNABLE_ with INVALID_. |
| Counts activity | evaluate runs two aggregate queries for the whole scope: closed Tasks with Related To (WhatId) in the scope and a due date on or after the cutoff, and Events with WhatId in the scope dated on or after the cutoff. Future Events count. |
| Decides each record | Every Account starts at 0, so an Account with no activity is a real FAIL, not a missing result. Each record passes when its count is at least the minimum. |
| Returns typed values | Found is the count, as a COUNT value; Expected is the minimum, compared with GREATER_. |
| Attaches evidence | Each outcome carries one evidence row: Account, count, minimum, and window. Apex callers that request EVALUATION_ receive it; the record-page card does not show evidence. |
| Adds display text | getDisplay() returns a message with an Open account link, fix text on failure, an Open account action, and number formats. The card shows this text instead of the Check’s message, fix, and action fields, which remain the fallback. |
A Task or Event related only to a Contact or Lead through Name (WhoId) is not counted. The
class reads data with with sharing and user-mode queries, so it counts only activities the running
user can see.
Source
Section titled “Source”The package contains this class. Inside the package, type names have no namespace prefix. A class
that you write in your own org refers to the same types with the rhc. prefix, such as
rhc.RecordHealthCheckPlugin.
/** * @author Gautam Kolan (https://github.com/gkolan) * SPDX-License-Identifier: Apache-2.0 */
/** * Example implementation of RecordHealthCheckPlugin: has the Account been touched * recently and often enough? A configurable minimum number of completed Tasks * or logged Events must fall inside a configurable look-back window, tuned per * Check through ApexParametersJson__c, for example * {"daysBack": 60, "minimumActivities": 2}. * * This is the reference implementation for the plugin contract, so it is * written the way every Check should be: all data loading happens ABOVE the * loop, and the loop does computation only. Two queries serve the whole scope, * whether that scope holds one record or two hundred. * * The class declares its JSON parameters, returns typed decision evidence, and * can add display-only context after evaluation. Check metadata still owns * identity, applicability, severity, publication, and safe fallback copy. */global with sharing class AccountHasRecentActivityCheck implements RecordHealthCheckPlugin, RecordHealthCheckPluginDefinitionSource, RecordHealthCheckDisplayPlugin { private static final Integer DEFAULT_DAYS_BACK = 30; private static final Integer MIN_DAYS_BACK = 1; private static final Integer MAX_DAYS_BACK = 3650; private static final Integer DEFAULT_MINIMUM_ACTIVITIES = 1; private static final Integer MINIMUM_ACTIVITIES = 1; private static final Integer MAXIMUM_ACTIVITIES = 1000; private Map<Id, Integer> evaluatedActivityCounts = new Map<Id, Integer>(); private Integer evaluatedDaysBack; private Integer evaluatedMinimumActivities;
/** Declares the accepted parameters and bulk scheduling characteristics. */ global RecordHealthCheckPluginDefinition getDefinition() { return new RecordHealthCheckPluginDefinition() .integerParameter( 'daysBack', DEFAULT_DAYS_BACK, MIN_DAYS_BACK, MAX_DAYS_BACK ) .describe( 'daysBack', 'Look-back days', 'Count completed Tasks and Events on or after this many days ago.' ) .integerParameter( 'minimumActivities', DEFAULT_MINIMUM_ACTIVITIES, MINIMUM_ACTIVITIES, MAXIMUM_ACTIVITIES ) .describe( 'minimumActivities', 'Required activities', 'Minimum completed Tasks and Events required inside the look-back window.' ) .capacity(200, true, 'LOW'); }
/** Evaluates recent activity once for the complete requested scope. */ global Map<Id, RecordHealthCheckOutcome> evaluate( RecordHealthCheckScope scope ) { evaluatedActivityCounts.clear(); evaluatedDaysBack = null; evaluatedMinimumActivities = null; Map<Id, RecordHealthCheckOutcome> results = new Map<Id, RecordHealthCheckOutcome>(); List<Id> recordIds = scope.recordIds; if (recordIds == null || recordIds.isEmpty()) { return results; } Set<Id> queryRecordIds = new Set<Id>(recordIds);
Integer daysBack = resolveDaysBack(scope.parameters); Integer minimumActivities = resolveMinimumActivities(scope.parameters); if (daysBack == null || minimumActivities == null) { for (Id recordId : recordIds) { results.put( recordId, RecordHealthCheckOutcome.unableToEvaluate('INVALID_CONFIG') ); } return results; } evaluatedDaysBack = daysBack; evaluatedMinimumActivities = minimumActivities; Date cutoff = Date.today().addDays(-daysBack);
// Seed every Id with zero BEFORE overlaying the aggregates. An aggregate // returns no row at all for an Account with no activity, so a map built // only from query results would leave exactly those Accounts missing, and // "no recent activity" is precisely the Accounts this check exists to // find. Zero is a real answer here, not an absent one. Map<Id, Integer> activityCounts = new Map<Id, Integer>(); for (Id recordId : recordIds) { activityCounts.put(recordId, 0); }
Map<String, Object> queryBinds = new Map<String, Object>{ 'queryRecordIds' => queryRecordIds, 'cutoff' => cutoff }; accumulateRows( activityCounts, RecordHealthCheckQueryEvaluatorSupport.runAggregateQuery( 'SELECT WhatId whatId, COUNT(Id) total FROM Task WHERE WhatId IN :queryRecordIds AND IsClosed = TRUE AND ActivityDate >= :cutoff GROUP BY WhatId', queryBinds ) ); accumulateRows( activityCounts, RecordHealthCheckQueryEvaluatorSupport.runAggregateQuery( 'SELECT WhatId whatId, COUNT(Id) total FROM Event WHERE WhatId IN :queryRecordIds AND ActivityDate >= :cutoff GROUP BY WhatId', queryBinds ) );
RecordHealthCheckValue expected = RecordHealthCheckValue.ofCount( minimumActivities ); ActivityOutcomeEvaluator recordEvaluator = new ActivityOutcomeEvaluator( activityCounts, minimumActivities, daysBack, expected ); for (Id recordId : recordIds) { Integer total = activityCounts.get(recordId); evaluatedActivityCounts.put(recordId, total); results.put( recordId, RecordHealthCheckOutcome.tryEvaluate(recordId, recordEvaluator) ); }
return results; }
public static RecordHealthCheckOutcome outcomeFor( Integer total, Integer minimumActivities ) { RecordHealthCheckOutcome outcome = total >= minimumActivities ? RecordHealthCheckOutcome.pass('APEX_PASS') : RecordHealthCheckOutcome.fail('APEX_FAIL'); return outcome.withFound(RecordHealthCheckValue.ofCount(total)); }
/** Builds one outcome with the typed evidence displayed by diagnostics 2.0. */ public static RecordHealthCheckOutcome outcomeFor( Integer total, Integer minimumActivities, Integer daysBack, Id recordId ) { RecordHealthCheckEvidence evidence = new RecordHealthCheckEvidence( 'Recent completed activity used for this decision.' ) .column('accountId', 'Account', 'ID') .column('activityCount', 'Completed activities', 'NUMBER') .column('requiredCount', 'Required activities', 'NUMBER') .column('windowDays', 'Look-back days', 'NUMBER') .row( new List<RecordHealthCheckEvidenceCell>{ RecordHealthCheckEvidenceCell.value( RecordHealthCheckValue.ofId(recordId) ), RecordHealthCheckEvidenceCell.value( RecordHealthCheckValue.ofCount(total) ), RecordHealthCheckEvidenceCell.value( RecordHealthCheckValue.ofCount(minimumActivities) ), RecordHealthCheckEvidenceCell.value( RecordHealthCheckValue.ofNumber( Decimal.valueOf(String.valueOf(daysBack)) ) ) } ) .groupBy('windowDays', 'accountId'); return outcomeFor(total, minimumActivities).withEvidence(evidence); }
/** * Adds presentation after evaluation without querying or changing outcomes. * Missing state produces no override, allowing metadata fallback copy. */ global Map<Id, RecordHealthCheckDisplayOverride> getDisplay( RecordHealthCheckScope scope ) { Map<Id, RecordHealthCheckDisplayOverride> displayByRecordId = new Map<Id, RecordHealthCheckDisplayOverride>(); if ( scope == null || evaluatedDaysBack == null || evaluatedMinimumActivities == null ) { return displayByRecordId; } for (Id recordId : scope.recordIds) { if (!evaluatedActivityCounts.containsKey(recordId)) { continue; } Integer total = evaluatedActivityCounts.get(recordId); Boolean passing = total >= evaluatedMinimumActivities; RecordHealthCheckDisplayOverride displayValue = new RecordHealthCheckDisplayOverride() .withMessage( new RecordHealthCheckDisplayText() .text( passing ? 'Recent follow-up meets the configured activity requirement.' : 'Recent follow-up is below the configured activity requirement.' ) .lineBreak() .link('Open account', '/lightning/r/Account/' + recordId + '/view') ) .withExpectedLabel('Required recent activity') .withFoundFormat('NUMBER', null) .withExpectedFormat('NUMBER', null) .withAction( new RecordHealthCheckDisplayAction( 'Open account', '/lightning/r/Account/' + recordId + '/view' ) ); if (!passing) { displayValue.withFix( new RecordHealthCheckDisplayText() .text( 'Log a completed Task or Event for this Account, then run the Check again.' ) ); } displayByRecordId.put(recordId, displayValue); } return displayByRecordId; }
/** Evaluates one record from the already loaded count map. */ private class ActivityOutcomeEvaluator implements RecordHealthCheckRecordEvaluator { private Map<Id, Integer> activityCounts; private Integer minimumActivities; private Integer daysBack; private RecordHealthCheckValue expected;
private ActivityOutcomeEvaluator( Map<Id, Integer> activityCounts, Integer minimumActivities, Integer daysBack, RecordHealthCheckValue expected ) { this.activityCounts = activityCounts; this.minimumActivities = minimumActivities; this.daysBack = daysBack; this.expected = expected; }
public RecordHealthCheckOutcome evaluateRecord(Id recordId) { return outcomeFor( activityCounts.get(recordId), minimumActivities, daysBack, recordId ) .withComparison('GREATER_THAN_OR_EQUAL', expected); } }
/** * A WhatId can point at objects other than the ones in scope, so only seeded * keys are accumulated. Anything else would add a key the engine never asked * about, which fails the whole scope. */ public static void accumulateRows( Map<Id, Integer> counts, List<AggregateResult> rows ) { for (AggregateResult row : rows) { accumulate(counts, (Id) row.get('whatId'), (Integer) row.get('total')); } }
private static void accumulate( Map<Id, Integer> counts, Id whatId, Integer total ) { if (whatId != null && counts.containsKey(whatId)) { counts.put(whatId, counts.get(whatId) + total); } }
/** * Bounded deliberately: an unbounded window is not a useful health check, and * a negative one would silently invert the question being asked. * * Null means the administrator supplied an invalid value; the caller returns * INVALID_CONFIG for every scoped record without running a query. */ private Integer resolveDaysBack(Map<String, Object> parameters) { Object raw = parameters == null ? null : parameters.get('daysBack'); if (raw == null) { return DEFAULT_DAYS_BACK; } return resolveBoundedInteger(raw, MIN_DAYS_BACK, MAX_DAYS_BACK); }
/** * Resolves the minimum completed engagements required inside the window. * Existing Check metadata remains backward-compatible because an omitted * value defaults to one. */ private Integer resolveMinimumActivities(Map<String, Object> parameters) { Object raw; if (parameters != null) { raw = parameters.get('minimumActivities'); } if (raw == null) { return DEFAULT_MINIMUM_ACTIVITIES; } return resolveBoundedInteger(raw, MINIMUM_ACTIVITIES, MAXIMUM_ACTIVITIES); }
/** Converts supported parameter types and enforces an inclusive range. */ private Integer resolveBoundedInteger( Object raw, Integer minimum, Integer maximum ) { Integer parsed; if (raw instanceof Integer) { parsed = (Integer) raw; } else if (raw instanceof Decimal) { parsed = ((Decimal) raw).intValue(); } else if (raw instanceof String) { try { parsed = Integer.valueOf((String) raw); } catch (Exception ex) { return null; } } else { return null; } return (parsed < minimum || parsed > maximum) ? null : parsed; }}Interfaces the class implements
Section titled “Interfaces the class implements”| Interface | Method | Purpose |
|---|---|---|
RecordHealthCheckPlugin | evaluate(RecordHealthCheckScope scope) | Returns one RecordHealthCheckOutcome for each ID in scope.. |
RecordHealthCheckPluginDefinitionSource | getDefinition() | Declares the parameters Record Health Check validates before evaluate runs. |
RecordHealthCheckDisplayPlugin | getDisplay(RecordHealthCheckScope scope) | Returns optional display text after evaluation. It cannot change a result. |
Two patterns in the source apply to any Apex Check:
- Load once, then loop. Both queries run before the loop over
scope.recordIds, so the class issues two queries whether the scope holds 1 record or 200. - Recover per record.
RecordHealthCheckOutcome.tryEvaluate(recordId, evaluator)turns an ordinary exception for one record intoUNABLE_TO_EVALUATEfor that record only, without losing the other records’ results.
Write an Apex Check describes every interface and outcome method.
Run the class from Apex
Section titled “Run the class from Apex”After you configure the Check in Check that an Account has recent activity, you can run it from Developer Console → Debug → Open Execute Anonymous Window. Replace the ID with an Account you can see, and run as a user with Record Health Check User or Record Health Check Admin:
// The Account to check.Id accountId = '001XXXXXXXXXXXXXXX';
// 'Account_Has_Recent_Activity' is the Check's API name. It has no rhc__ prefix because// your organization created it.rhc.RecordHealthCheckResponse response = rhc.RecordHealthCheck.evaluate( rhc.RecordHealthCheckRequest.forCheck('Account_Has_Recent_Activity', accountId) .withResultMode(rhc.RecordHealthCheckResultMode.EVALUATION_WITH_DISPLAY));System.debug(LoggingLevel.INFO, JSON.serializePretty(response));In the debug log, results[0].evaluation holds the status, reason code, and typed Found and
Expected values, and results[0].display holds the card text and the evidence.
Test the class
Section titled “Test the class”| Case | Expected result |
|---|---|
| Two or more closed Tasks or Events related to the Account within the window | PASS, Found 2 or more |
| One qualifying activity, with a minimum of 2 | FAIL, Found 1 |
| No activity | FAIL, Found exactly 0 |
| A Task related only to a Contact, an open Task, or a Task due before the window | Not counted |
{"daysBack": "90"}, an unknown key, 0, or a value above the maximum | UNABLE_ with INVALID_ |
| A user who cannot see a qualifying activity | A lower count for that user |
| A user who cannot read Task or Event | ERROR; the card shows System Error |
Change the rule
Section titled “Change the rule”Change daysBack and minimumActivities in Apex Parameters (JSON) without deploying code. To
count different activities, such as Tasks related through WhoId, write your own class from this
source in your org, give it a new name, and update its tests. Add the rhc. prefix to each Record
Health Check type. Also replace each RecordHealthCheckQueryEvaluatorSupport.runAggregateQuery
call: that helper is internal to the package, so a class in your org cannot call it. Run
Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE) instead, and cast each returned row to
AggregateResult before passing the list to accumulateRows. Do not edit the packaged class; a
package upgrade replaces it. If the Account’s Last Activity date alone answers the requirement,
use a formula Check instead.