Skip to content

Class Name: AnonymizationSchedulerTwo

Last Updated: 2025-10-22 Source Code: https://github.com/AANP-IT/I2C.Salesforce.Metadata/blob/STAGING/force-app/main/default/classes/AnonymizationSchedulerTwo.cls

API Name: AnonymizationSchedulerTwo Type: Schedulable (Scheduled Job Orchestrator - Phase 2) Test Coverage: To be determined

Business Purpose

This schedulable class orchestrates the second phase of GDPR-compliant data anonymization processes, focusing on e-commerce and order fulfillment objects. It coordinates five batch jobs that systematically anonymize order summaries, delivery groups, payment summaries, shopping carts, and fulfillment orders. This class complements AnonymizationSchedulerOne to provide comprehensive coverage of all customer PII across the Salesforce Commerce Cloud implementation, ensuring complete compliance with privacy regulations.

Class Overview

Scope and Sharing

  • Sharing Model: with sharing (respects record-level security)
  • Access Modifier: public
  • Interfaces Implemented: Schedulable

Key Responsibilities

  • Orchestrate Phase 2 of data anonymization process for e-commerce data
  • Launch batch jobs for OrderSummary anonymization (Commerce Cloud)
  • Coordinate OrderDeliveryGroupSummary data obfuscation
  • Manage OrderPaymentSummary anonymization
  • Handle WebCart data anonymization
  • Process FulfillmentOrder anonymization
  • Serve as scheduled job entry point for commerce-focused privacy maintenance
  • Ensure anonymization jobs run with appropriate batch sizes (200 records)

Public Methods

execute

public void execute(SchedulableContext sc)

Purpose: Schedulable interface method that launches five batch jobs to anonymize e-commerce and order fulfillment data across Salesforce Commerce Cloud objects. This is the entry point for Phase 2 of the scheduled anonymization process.

Parameters: - sc (SchedulableContext): System-provided scheduling context containing job information. Not used in current implementation but required by Schedulable interface.

Returns: - void (no return value)

Throws: - No explicit exception handling - relies on system error handling - AsyncException: Could be thrown if batch job limits are exceeded - System.LimitException: Could occur if too many batch jobs queued simultaneously

Usage Example:

// Schedule to run daily at 3 AM (after Phase 1 completes)
String cronExpression = '0 0 3 * * ?';
String jobName = 'GDPR Anonymization Phase 2';
System.schedule(jobName, cronExpression, new AnonymizationSchedulerTwo());

// Or schedule via UI: Setup → Scheduled Jobs → Schedule Apex

Business Logic: 1. Creates instance of UpdateOrderSummaryBatch with batch size 200 2. Executes order summary anonymization batch job 3. Creates instance of OrderDeliveryGroupSummaryBatch with batch size 200 4. Executes delivery group anonymization batch job 5. Creates instance of OrderPaymentSummaryBatch with batch size 200 6. Executes payment summary anonymization batch job 7. Creates instance of UpdateWebCartBatch with batch size 200 8. Executes web cart anonymization batch job 9. Creates instance of UpdateFulfillmentOrderBatch with batch size 200 10. Executes fulfillment order anonymization batch job 11. All jobs execute asynchronously after being queued

Execution Flow: - Jobs are queued sequentially in the execute method - Actual batch execution happens asynchronously - Jobs may run in parallel depending on system resources - Order of completion not guaranteed despite queue order - Each batch processes up to 200 records per transaction

Coordination with Phase 1: - Phase 2 should run after Phase 1 (AnonymizationSchedulerOne) completes - Typical schedule: Phase 1 at 2 AM, Phase 2 at 3 AM - No built-in dependency checking between phases - Phases can technically run in parallel but not recommended


Private/Helper Methods

None - All logic contained in execute method. Delegates actual anonymization work to batch classes.


Dependencies

Apex Classes

  • UpdateOrderSummaryBatch: Anonymizes OrderSummary records (Commerce Cloud)
  • OrderDeliveryGroupSummaryBatch: Anonymizes delivery group information
  • OrderPaymentSummaryBatch: Anonymizes payment summary data
  • UpdateWebCartBatch: Anonymizes shopping cart data
  • UpdateFulfillmentOrderBatch: Anonymizes fulfillment and shipping orders

All batch classes must exist and be properly implemented for this scheduler to function.

Salesforce Objects

Objects accessed depend on batch class implementations (Salesforce Commerce Cloud): - OrderSummary: Aggregated order data with customer information - OrderDeliveryGroupSummary: Delivery addresses and shipping details - OrderPaymentSummary: Payment methods and billing information - WebCart: Active and abandoned shopping carts with customer data - FulfillmentOrder: Warehouse and shipping fulfillment records

Custom Settings/Metadata

  • None directly - But batch classes may use:
  • Anonymization_Settings__c: Configuration for anonymization rules
  • GDPR_Compliance__mdt: Metadata controlling anonymization behavior
  • Data_Retention__mdt: Policies for data retention periods

External Services

  • None - Pure internal data processing
  • No callouts or external system integrations
  • Operates entirely within Salesforce Commerce Cloud

Design Patterns

  • Scheduler Pattern: Implements Schedulable for automated execution
  • Orchestrator Pattern: Coordinates multiple batch jobs without implementing anonymization logic
  • Batch Processing Pattern: Uses Database.executeBatch for large-scale data processing
  • Phase Pattern: Part of multi-phase anonymization strategy (Phase 2 of 2)
  • Separation of Concerns: Phase 2 handles e-commerce while Phase 1 handles account/contact data

Why These Patterns: - Scheduler enables automated compliance with data retention policies - Orchestrator separates coordination from implementation - Batch processing handles large data volumes within governor limits - Phasing prevents single job from hitting limits and separates functional areas - Two-phase approach allows independent scheduling and error handling

Governor Limits Considerations

SOQL Queries: 0 (no queries in scheduler - handled by batch classes) DML Operations: 0 (no DML in scheduler - handled by batch classes) CPU Time: Minimal (only instantiates and queues batch jobs) Heap Size: Minimal (no data processing in scheduler)

Bulkification: N/A (scheduler only coordinates batch jobs) Async Processing: Yes - queues 5 batch jobs for asynchronous execution

Scheduler-Specific Limits: - Max scheduled jobs: 100 per org - Max batch jobs queued: 5 at a time (CRITICAL - this class queues 5, using entire limit) - Max batch jobs in 24 hours: 250,000 - Batch size: 200 records per transaction (hardcoded)

Governor Limit Risks: - CRITICAL: Queues 5 batch jobs simultaneously - USES ENTIRE 5-batch limit - CRITICAL: If Phase 1 (4 batches) and Phase 2 (5 batches) overlap, will fail - HIGH: No check if batch job queue is full before queueing - HIGH: Running both Phase 1 and Phase 2 simultaneously = 9 batch jobs (exceeds limit) - MEDIUM: Hardcoded batch size of 200 - no configuration flexibility - LOW: Multiple schedulers running could exhaust daily batch job limit

Recommendations: - CRITICAL: Add at least 1-hour gap between Phase 1 and Phase 2 schedules - Add queue availability check before launching batches - Implement sequential batch chaining instead of parallel queueing - Make batch size configurable via custom metadata - Add monitoring for batch job queue depth - Consider reducing to 4 or fewer batches per phase

Error Handling

Strategy: None - relies entirely on system error handling

Logging: - None - No logging of scheduler execution - No tracking of which batches were queued - No success/failure notification - Batch classes may have their own logging

User Notifications: - None - Silent execution with no notifications - Administrators must manually check: - Setup → Apex Jobs to see batch status - Setup → Scheduled Jobs to verify scheduler ran - Debug logs if enabled - Email notifications if batch classes implement them

Rollback Behavior: - Scheduler transaction separate from batch transactions - If batch job queueing fails, subsequent batches may still queue - Partial success possible - some batches queue, others don't - No compensating transactions or cleanup - Failed anonymization could result in compliance violations

Recommended Improvements: - Add try-catch around each batch launch - Log scheduler execution to custom object (Anonymization_Log__c) - Send email notification on errors to compliance team - Publish platform events for monitoring integration - Track which batches were successfully queued vs failed - Implement retry mechanism for failed queueing - Add dependency check to verify Phase 1 completed before running

Security Considerations

Sharing Rules: RESPECTED - Uses 'with sharing' keyword - Scheduler respects running user's sharing rules - Scheduled jobs typically run as automated process user - Batch classes may have different sharing rules (check each batch)

Field-Level Security: RESPECTED - FLS enforced for scheduler (though no field access in scheduler) - Batch classes responsible for FLS enforcement

CRUD Permissions: RESPECTED - Scheduler requires read access to batch classes - Batch classes require appropriate object permissions

Input Validation: N/A - Scheduler takes no input parameters - No user input to validate

Security Risks: - LOW: 'with sharing' appropriate for scheduler - MEDIUM: Batch classes may run 'without sharing' - check each batch - LOW: Scheduled jobs run as system - ensure proper audit trails - MEDIUM: No verification that user has authorization to anonymize data

Data Privacy Considerations: - CRITICAL: This class handles PII anonymization - GDPR/CCPA compliance - Must ensure complete data obfuscation in Commerce Cloud - Audit trail required for compliance (EU GDPR Article 30) - Anonymization must be irreversible per GDPR requirements - Batch classes must implement approved anonymization algorithms - Commerce data includes payment information - PCI DSS considerations

Compliance Requirements: - GDPR Right to be Forgotten (Article 17) - GDPR Right to Data Portability (Article 20) - CCPA deletion requirements (CCPA § 1798.105) - PCI DSS data retention (Requirement 3.1) - SOC 2 data handling requirements - State-specific privacy laws (CPRA, VCDPA, etc.)

Test Class

Test Class: AnonymizationSchedulerTwoTest.cls (assumed name - verify in codebase) Coverage: To be determined

Test Scenarios That Should Be Covered: - ✓ Scheduler executes and queues all 5 batch jobs - ✓ Each batch job is queued with batch size 200 - ✓ Scheduler runs successfully with proper SchedulableContext - ✓ Multiple scheduler executions don't cause errors - ✓ Batch jobs execute independently if one fails - ✓ Governor limits not exceeded when queuing batches - ✓ Test with System.schedule() to verify actual scheduling - ✓ Verify job runs under automated process user - ✓ Check that 'with sharing' is properly enforced - ✓ Test coordination with Phase 1 (if applicable) - ✓ Test batch job queue limit scenarios

Testing Challenges: - Cannot easily test batch job execution within scheduler test - Must use Test.startTest()/Test.stopTest() for async completion - Batch job queue limits make testing multiple schedulers difficult - Cannot easily verify anonymization effectiveness from scheduler test - Difficult to test Phase 1 → Phase 2 coordination in single test

Test Data Requirements: - Create test OrderSummary records marked for anonymization - Create OrderDeliveryGroupSummary with delivery addresses - Create OrderPaymentSummary with payment methods - Create WebCart records (active and abandoned) - Create FulfillmentOrder records - Mark records with anonymization flags - Verify batch classes can find and process test data

Changes & History

  • Initial creation date: Unknown (check git history)
  • Created as part of: GDPR compliance implementation
  • Related to: Salesforce Commerce Cloud data privacy initiative
  • Companion class: AnonymizationSchedulerOne (Phase 1)
  • Focus: E-commerce and order fulfillment data anonymization

Recommended: - Document GDPR compliance requirements that drove creation - Link to data retention policy documents - Reference legal/compliance requirements - Document relationship with AnonymizationSchedulerOne

⚠️ Pre-Go-Live Concerns

CRITICAL - Fix Before Go-Live

  • No Error Handling: Zero exception handling - any failure is silent and untracked. Could result in PCI DSS and GDPR compliance violations.
  • Batch Queue Limit MAXED: Queues 5 batches simultaneously - USES ENTIRE 5-batch limit. ANY other batch job will fail. If Phase 1 still running, will cause failures.
  • Phase Coordination Missing: No check that Phase 1 completed before Phase 2 runs. Could cause conflicts or incomplete anonymization.
  • No Execution Logging: Zero visibility into whether scheduler ran or which batches were queued. Compliance audit trail completely missing.
  • No Monitoring: No alerts if batches fail to queue or execute. Could miss GDPR compliance deadlines resulting in legal penalties.
  • Hardcoded Batch Size: Batch size of 200 cannot be adjusted without code deployment. May not be optimal for Commerce Cloud data volumes.

HIGH - Address Soon After Go-Live

  • No Status Tracking: No way to verify all Phase 2 anonymization completed successfully
  • No Coordination Logic: Batches may run in parallel and conflict with each other or with Phase 1 batches
  • Missing Notifications: Compliance team not notified of scheduler execution, completion, or failures
  • No Configuration: Cannot enable/disable individual batches without code changes
  • Performance Unknown: No monitoring of how long anonymization takes or Commerce Cloud resource consumption
  • No Retry Logic: Failed batch queueing not automatically retried
  • Schedule Conflicts: No safeguards against Phase 1 and Phase 2 overlapping

MEDIUM - Future Enhancement

  • Sequential Execution: Should chain batches to run sequentially rather than parallel queuing to avoid hitting limits
  • Configurable Batch Size: Make batch size adjustable via custom metadata based on data volumes
  • Selective Execution: Add ability to run only specific anonymization batches
  • Retry Logic: Add automatic retry if batch queueing fails
  • Dashboard Integration: Create monitoring dashboard for anonymization job status
  • Dependency Checking: Verify Phase 1 completed before starting Phase 2
  • Dynamic Scheduling: Adjust schedule based on data volumes and processing times

LOW - Monitor

  • Class Naming: "Two" naming not intuitive - consider "EcommerceAnonymizationScheduler"
  • No Documentation: No inline comments explaining why split into two phases or which objects handled
  • No Version Control: No versioning if anonymization rules change over time
  • Missing Context: SchedulableContext parameter not used - remove if not needed
  • Schedule Timezone: Ensure schedule accounts for UTC vs local time and Daylight Saving Time

Maintenance Notes

Complexity: Low (simple orchestrator) but High (critical compliance function for Commerce) Recommended Review Schedule: Monthly (compliance-critical), Quarterly (functional review), After every Salesforce release

Key Maintainer Notes:

🔒 COMPLIANCE CONSIDERATIONS: - This is CRITICAL for GDPR/CCPA/PCI DSS compliance - failures could result in legal penalties and fines - Anonymization must be complete, irreversible, and auditable - E-commerce data includes payment information - extra scrutiny required - Audit trail required for compliance audits (must prove deletion) - Must run reliably on schedule - SLA compliance important for legal obligations - Coordinate with legal/compliance team before ANY changes

📋 Usage and Scheduling: - Typically scheduled to run daily during off-peak hours (3-4 AM) - Must run AFTER AnonymizationSchedulerOne completes (minimum 1-hour gap recommended) - Phase 2 focuses on Commerce Cloud objects - May need more frequent execution for high-transaction orgs - Consider timezone when scheduling (UTC vs local time) - Adjust schedule during peak sales periods (Black Friday, etc.)

🧪 Testing Requirements: - Test in sandbox with production-like Commerce data volumes - Verify all 5 batch classes execute successfully - Monitor execution time to ensure completion within maintenance window - Test impact on Commerce Cloud performance during peak hours - Validate anonymization is complete and irreversible - Test with Phase 1 running to ensure no conflicts - Load test with maximum expected data volumes

🔧 Batch Class Dependencies: - CRITICAL: All 5 batch classes must exist and be deployed - Changes to batch classes may require scheduler changes - Test batch classes independently before scheduler testing - Batch class failures won't prevent scheduler from completing but will leave data un-anonymized - Commerce Cloud upgrades may affect batch class behavior

⚠️ Gotchas and Warnings: - CRITICAL: Queuing 5 batches uses 100% of the 5-batch limit - If Phase 1 (4 batches) still running, Phase 2 will fail - Any other process trying to queue batches will fail while this runs - Batch execution order not guaranteed despite queue order - Large Commerce data volumes may cause batches to run for hours - Scheduled jobs can be paused/stopped - verify after deployments - Daylight Saving Time can affect scheduled execution times - Commerce Cloud releases may change object structures

📅 When to Review This Class: - After any GDPR/CCPA/PCI DSS regulation changes - Before and after major Salesforce releases (3x per year) - Before and after Commerce Cloud upgrades - When adding new Commerce fields that need anonymization - If anonymization SLAs not being met - During compliance audits - When system performance issues occur during anonymization - Before major sales events (Black Friday, holiday season) - After any Commerce Cloud integration changes

🛑 Deactivation/Emergency Stop:

To temporarily stop Phase 2 anonymization:

// Delete or abort the scheduled job
List<CronTrigger> jobs = [SELECT Id FROM CronTrigger
    WHERE CronJobDetail.Name LIKE '%Anonymization%Phase%2%'];
for(CronTrigger job : jobs) {
    System.abortJob(job.Id);
}

// Or via UI: Setup → Scheduled Jobs → Delete/Pause

Alternative: Add custom metadata check:

public void execute(SchedulableContext sc) {
    Anonymization_Settings__mdt settings =
        Anonymization_Settings__mdt.getInstance('Phase2');
    if (settings != null && settings.Enabled__c == false) {
        System.debug('Phase 2 anonymization disabled via metadata');
        return; // Skip execution
    }
    // ... rest of code
}

🔍 Debugging Tips: - Monitor: Setup → Apex Jobs to see all 5 batch statuses - Check: Setup → Scheduled Jobs for next scheduled run time - Enable debug logs for batch classes, not scheduler - Create monitoring dashboard for batch job status and queue depth - Set up email alerts for failed batches to compliance team - Use Platform Events for real-time monitoring - Monitor Commerce Cloud performance during anonymization - Check for orphaned batch jobs (stuck in queue)

📊 Monitoring Checklist: - Scheduler execution frequency (should match schedule exactly) - Batch job success rate (should be >99.9% for compliance) - Average execution time per batch (trend over time) - Records processed per batch run (compare to expected volumes) - Compliance SLA adherence (must meet legal deadlines) - Commerce Cloud performance impact during execution - Batch job queue depth before and after execution - Phase 1 completion time vs Phase 2 start time (gap sufficient?) - Failed anonymization records (should be zero) - Audit trail completeness

🔗 Related Components: - AnonymizationSchedulerOne: Phase 1 of anonymization process (prerequisite) - UpdateOrderSummaryBatch: Order summary anonymization logic - OrderDeliveryGroupSummaryBatch: Delivery address anonymization - OrderPaymentSummaryBatch: Payment data anonymization (PCI DSS) - UpdateWebCartBatch: Shopping cart anonymization - UpdateFulfillmentOrderBatch: Fulfillment order anonymization - Commerce Cloud triggers that mark records for anonymization - Flows that initiate anonymization requests - Data retention policies that determine anonymization schedule

Business Owner

Primary: Legal/Compliance Team (GDPR/Data Privacy Officer, PCI DSS Compliance) Secondary: IT Operations / Data Governance Team / Commerce Team Stakeholders: Security Team, Legal Counsel, Commerce Operations, Customer Service, System Administrators, Payment Processing Team

Compliance Officers: - Must verify Commerce Cloud anonymization completeness - Responsible for audit documentation and legal defense - Define data retention policies for commerce data - Approve anonymization rule changes - Coordinate with payment processor on PCI requirements

IT Operations: - Monitor scheduler execution daily - Troubleshoot batch failures immediately - Manage deployment and testing - Performance optimization for Commerce Cloud - Coordinate with Salesforce support on Commerce issues