Unit test ReferralAttributionService with mocked repos
epic-membership-recruitment-core-services-task-013 — Write a comprehensive flutter_test unit test suite for ReferralAttributionService using mocked RecruitmentAttributionRepository and BadgeCriteriaIntegration. Cover: click event recording with deduplication, registration matching within and outside the time window, attribution confirmation transitions, double-confirmation guard, aggregated count calculations, milestone threshold detection at each boundary, and event publishing verification. Target 100% branch coverage.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 7 - 84 tasks
Can start after Tier 6 completes
Implementation Notes
This is a high-complexity test suite — budget time for the fake implementations, not just the tests. The FakeRecruitmentAttributionRepository needs to simulate concurrent access for the double-confirmation guard test; use a Completer-based mechanism inside the fake to inject a delay between read and write. For milestone boundary tests, parameterise using a data-driven pattern: define a list of (before_count, after_count, expected_threshold_or_null) tuples and loop over them in one group — this avoids copy-paste and makes boundary coverage obvious. Extract shared test fixtures (sample AttributionRecord, sample MilestoneEvent) into a test_helpers.dart file in test/helpers/ to keep the main test file readable.
Ensure the SpyBadgeCriteriaIntegration records events in a List
Testing Requirements
Pure unit tests with flutter_test. Use fake_async for all time-dependent scenarios (attribution window, deduplication cooldown). Organise with nested group() blocks: 'click recording' > 'deduplication', 'registration matching' > 'within window' / 'outside window' / 'multi-code conflict', 'confirmation transitions' > 'happy path' / 'guard conditions', 'aggregate counts', 'milestone detection' > 'boundary values', 'event publishing' > 'success' / 'badge layer throws'. Use a FakeRecruitmentAttributionRepository with an in-memory list and a SpyBadgeCriteriaIntegration that records all received events.
Generate coverage with flutter test --coverage and confirm 100% branch coverage on the service file. Run flutter analyze on the test file to confirm no lints.
Confirmed registration events originate from the membership system (Dynamics portal for HLF), which may call back asynchronously with significant delay. If the attribution service only accepts synchronous confirmation at registration time, late callbacks will fail to match the originating referral code, resulting in under-counted conversions.
Mitigation & Contingency
Mitigation: Design the attribution confirmation path as a webhook endpoint (Supabase Edge Function) that accepts a referral_code + new_member_id pair at any time after click. The service matches by code string, not by session. Persist pending_signup events immediately at onboarding screen submission so there is always a record to upgrade to 'confirmed' when the webhook fires.
Contingency: If the membership system cannot reliably call the webhook, implement a polling reconciliation job (Supabase pg_cron, daily) that queries the membership system for recently registered members and back-fills any unmatched attribution records.
If confirmRegistration() is called more than once for the same new member (e.g., idempotency retry from the webhook), duplicate milestone events could be emitted, causing the badge system to award badges multiple times.
Mitigation & Contingency
Mitigation: Use a UNIQUE constraint on (referral_code_id, new_member_id) in the referral_events table for confirmed events. The confirmRegistration() method uses upsert semantics; milestone evaluation reads the confirmed count from the aggregation query rather than counting individual calls.
Contingency: If duplicate awards occur in production, the badge system should support idempotent award checks (query existing badges before awarding). Add a deduplication guard in BadgeCriteriaIntegration as a secondary defence.
Stakeholder review may expand attribution requirements mid-epic to include click-through tracking per channel (WhatsApp vs SMS vs email), which is not currently in scope but was mentioned in user story discussions. This would require schema changes in the foundation epic and delay delivery.
Mitigation & Contingency
Mitigation: Capture per-channel data in the device_metadata JSONB field from day one as an unstructured field (share_channel: 'whatsapp'). This preserves data without requiring a schema column, allowing structured querying to be added later without migrations.
Contingency: If channel-level analytics become a hard requirement during this epic, timebox the change to adding a nullable channel column to referral_events and a corresponding filter parameter on the aggregation query, deferring dashboard UI to a separate task.