Implementation Plan

Salesforce-to-Xero Integration — Business Rules Engine with Automated Testing

7Phases
1Complete
6Remaining
47Business Rules
87Tests Passing
Context: The Salesforce-Xero integration has 11 mature Apex service classes (3,226 lines) with all business logic hardcoded. 47 business rules have been captured in YAML and generated as Custom Metadata records, but nothing reads them at runtime yet. All 47 rules have CFO Decision = "Open" (none formally approved). This plan takes the project from current state to a production-ready rules engine with human-readable automated tests.
0
Test Safety Net for Existing Code
Dependencies: None
COMPLETE
Build regression coverage before touching service classes. Independent of CFO approval.
0.1
Create XeroHttpMock.cls — reusable HttpCalloutMock implementation covering all Xero API endpoints, with canned JSON responses
0.2
Create unit tests for all 11 service classes (one test class each)
  • XeroApiServiceTest, XeroContactServiceTest, XeroInvoiceServiceTest
  • XeroCreditNoteServiceTest, XeroJournalServiceTest
  • XeroWebhookHandlerTest, XeroWebhookProcessorTest, XeroWebhookEventHandlerTest
  • XeroTokenRefreshJobTest, XeroTokenRefreshSchedulerTest, XeroApiLoggerTest
0.3
Create LWC Jest test for xeroIntegrationTest component with mocked @wire and imperative Apex calls
0.4
Verify sf apex run test passes in sandbox — 87 tests, 100% pass rate
Deliverables: 11 Apex test classes, 1 HTTP mock class, 1 test data factory, 87 passing tests
1
Business Rule Formalisation & CFO Approval
Dependencies: None (runs in parallel with Phase 0)
NOT STARTED
Rules must be approved before they can be activated. This is a governance process.
1.1
Triage the 47 rules into tiers:
  • Tier 1 — Directly implementable now (validation rules: BR-001 through BR-004, BR-007, BR-012, BR-018, BR-020, BR-022, BR-029, BR-040, BR-041)
  • Tier 2 — Need new fields/objects first (rules referencing Billing_Schedule__c, Contracted_Asset_Start_Date__c, etc.)
  • Tier 3 — Need business clarification (rules with conflicting proposed_change notes)
1.2
Run CFO review sessions using the HTML viewer, grouped by category. For each rule: confirm conditions, confirm actions, set CFO decision
1.3
After each review session: update YAML, regenerate CMT (python3 scripts/yaml-to-cmt.py), rebuild viewer (python3 scripts/build-rules-viewer.py), deploy to sandbox
1.4
Document missing schema for Tier 2 rules (which custom fields/objects need creating)
Deliverables: Approved rule subset (target: all Tier 1), updated YAML with CFO decisions, list of schema gaps for Tier 2
2
Rules Engine Core
Dependencies: Phase 0 (need test safety net before refactoring)
NOT STARTED
Build the engine that reads Business_Rule__mdt at runtime and evaluates rules against records.
2.1
Create BusinessRuleEngine.cls — the core evaluator
  • Queries active Business_Rule__mdt records filtered by object name and event
  • Deserialises Conditions_JSON__c and evaluates against SObject using dynamic field access
  • Supports condition logic: all (AND) / any (OR)
  • Returns List<RuleEvaluationResult> with rule ID, action, message
  • Caches CMT query results in static variable (one query per transaction)
  • Accepts optional List<Business_Rule__mdt> parameter for testability
2.2
Create action handler framework
  • IRuleActionHandler interface
  • Concrete handlers: BlockSyncHandler, FlagRecordHandler, AlertHandler, MapFieldHandler, ExecuteApexHandler, LogHandler, RequireApprovalHandler
  • RuleActionFactory to instantiate handler by action name
2.3
Add rule evaluation hooks to existing service classes (minimal intrusion — ~5-10 new lines per service method)
2.4
Create missing custom fields/objects for Tier 2 rules (from Phase 1.4 output)
2.5
Create engine unit tests: BusinessRuleEngineTest.cls, RuleActionFactoryTest.cls — using in-memory CMT records
Deliverables: Rules engine framework (~10 new Apex classes), service class integration hooks, engine unit tests
3
Human-Readable BDD Test Layer
Dependencies: Phase 1 (approved rules), Phase 2 (engine to test against)
BLOCKED
Generate human-readable tests that the finance team can review and that execute as real Apex tests.
3.1
Create TestDataFactory.cls — shared test data builder with methods like createOpportunity(stage, tcv, currency)
3.2
Create scripts/generate-test-specs.py — reads YAML, outputs Gherkin scenarios for each approved rule. This is the CFO sign-off document.
3.3
Create BusinessRuleBDDTest.cls — one @IsTest method per approved rule, using GIVEN/WHEN/THEN comments
3.4
Create XeroIntegrationBDDTest.cls — integration-level tests calling @AuraEnabled service methods through the rules engine
Deliverables: TestDataFactory, BDD Apex test classes, generated Gherkin test specification, test spec generation script
4
Sandbox Configuration & Validation
Dependencies: Phase 2
BLOCKED
Configure the sandbox for full testing with real data and verified connectivity.
4.1
Prepare test data: Account records covering all rule scenarios, Opportunity records at various stages, Invoice/Credit Note records in various states
4.2
Verify Named Credential (Xero_API) and OAuth token refresh. Confirm XeroTokenRefreshScheduler is running.
4.3
Deploy everything: abort scheduled jobs, deploy objects/fields, deploy Apex classes, deploy CMT records, deploy permission sets, reschedule jobs
4.4
Run full test suite: sf apex run test --test-level RunAllTests. Target: 85%+ coverage, all tests green.
4.5
Manual smoke test via the xeroIntegrationTest LWC — verify rules are blocking/allowing syncs as expected
Deliverables: Fully configured sandbox, all tests passing, manual verification complete
5
End-to-End Tests (Playwright + Xero API)
Dependencies: Phase 4
BLOCKED
Verify the complete flow from Salesforce through to Xero and back via webhooks.
5.1
Add Playwright as devDependency. Create test config with SF sandbox login credentials. Build page object models.
5.2
Create Xero API verification helper (Node.js) — authenticates to Xero independently and verifies records arrived correctly
5.3
Write E2E test scenarios in BDD style:
  • Contact sync: create Account, sync, verify Xero Contact exists with correct name (BR-026 suffix stripping)
  • Invoice sync: Closed-Won Opp, invoice created as DRAFT (BR-016), correct VAT (BR-018), correct nominal code (BR-023)
  • Rule blocking: zero-value Opp, verify sync blocked (BR-003), verify flag set
  • Webhook round-trip: trigger change in Xero, webhook received, SF records updated
5.4
Test data cleanup in afterEach hooks — delete test records from both SF and Xero
Deliverables: Playwright test suite, page object models, Xero API verification utility, E2E test report
6
Production Deployment
Dependencies: All prior phases
BLOCKED
Deploy to production with phased rule activation and rollback plan.
6.1
Pre-deployment checklist:
  • All Apex tests passing with 85%+ coverage
  • All approved rules have corresponding BDD test methods
  • E2E tests passing in sandbox
  • CFO has signed off on test specification document
  • No rule has Is_Active__c = true where CFO_Decision__c != 'Accepted'
  • Production Named Credential configured (different Xero tenant)
  • Production Xero_Integration_Settings__c values prepared
6.2
Deployment sequence: abort scheduled jobs, deploy objects/fields, deploy Apex, deploy CMT, deploy permission sets, reschedule jobs, run all tests
6.3
Phased activation: start with Tier 1 validation rules only (lowest risk). Monitor. Then activate Tier 2 mapping/workflow rules. Then Tier 3.
6.4
Rollback plan: deactivating all rules reverts to original behaviour without code deployment. Individual rules can be deactivated via CMT update.
Deliverables: Production deployment, phased rule activation, monitoring

Phase Dependencies

Phase 0 (Existing tests) ─────────> Phase 2 (Engine) ─────> Phase 4 (Sandbox) │ │ [parallel] │ │ v v Phase 1 (CFO Approval) ──────────> Phase 3 (BDD Tests) ───> Phase 5 (E2E) │ v Phase 6 (Production)