Match confirmed registrations to referral codes
epic-membership-recruitment-core-services-task-007 — Implement the matchRegistrationToCode method in ReferralAttributionService. When a new member registration is confirmed, the service looks up the most recent click event for that device or session token, resolves the originating referral code, and creates a pending attribution record linked to both the new member and the referring peer mentor. Implement time-window matching (configurable, default 72 hours) and handle the case where no matching click event is found.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 2 - 518 tasks
Can start after Tier 1 completes
Implementation Notes
Method signature: `Future
To prevent duplicates, add a UNIQUE constraint on attribution_records(new_member_id) at the DB level, and catch the unique violation in the Dart layer to return AlreadyMatched. The Supabase query should be: `.from('click_events').select().eq('device_fingerprint', fp).gte('clicked_at', cutoff).order('clicked_at', ascending: false).limit(1)`. After finding the click event, resolve mentor_id by joining referral_codes. Create the AttributionRecord in a single insert.
Use sealed classes for MatchResult: MatchFound(attributionId), NoMatchFound, AlreadyMatched.
Testing Requirements
Unit tests (flutter_test + Mockito): mock IRecruitmentAttributionRepository. Test cases must include: (1) single click event within window — attribution created; (2) two click events within window — most recent used; (3) click event at exactly 72h boundary — included (use inclusive comparison); (4) click event at 72h+1s — excluded; (5) no click events — NoMatchFound returned; (6) existing pending attribution — AlreadyMatched returned without DB insert; (7) repository insert failure — exception propagated, no partial state. Use fake DateTime injection to control 'now' in tests. Aim for 95% branch coverage.
Add a concurrency test using Future.wait with two simultaneous calls to confirm only one attribution record is created.
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.