Referral Link & Tracking Engine Documentation

Complete technical specification for attribution and fraud prevention

Complete Referral Tracking Flow
╔════════════════════════════════════════════════════════════════════════════════╗
║                    REFERRAL TRACKING ENGINE - COMPLETE FLOW                    ║
╚════════════════════════════════════════════════════════════════════════════════╝

┌──────────────────────────────────────────────────────────────────────────────┐
│ STAGE 1: LINK GENERATION (When Member Joins)                                │
└──────────────────────────────────────────────────────────────────────────────┘

    Member Created
         │
         ▼
    ┌─────────────────────────┐
    │ GENERATE REFERRAL CODE  │
    │                         │
    │ Algorithm:              │
    │ • Length: 8 characters  │
    │ • Charset: A-Z, 2-9     │
    │ • Exclude: O,0,I,1,L    │
    │ • Format: UPPERCASE     │
    │ • Example: A7K9M2XQ     │
    └─────────────────────────┘
         │
         ├─► Check uniqueness against existing codes
         ├─► Retry if collision (rare, ~1 in 2.8 trillion)
         │
         ▼
    ┌─────────────────────────────────────────┐
    │ BUILD REFERRAL LINK                     │
    │                                         │
    │ Structure:                              │
    │ {base_url}/refer/{referral_code}        │
    │                                         │
    │ Examples:                               │
    │ • app.com/refer/A7K9M2XQ                │
    │ • studio.com/refer/B3H8K5LP             │
    │                                         │
    │ Stored in Member record:                │
    │ • member.referral_code = "A7K9M2XQ"     │
    └─────────────────────────────────────────┘


┌──────────────────────────────────────────────────────────────────────────────┐
│ STAGE 2: LINK CLICK TRACKING (When Someone Clicks)                          │
└──────────────────────────────────────────────────────────────────────────────┘

    User clicks: app.com/refer/A7K9M2XQ
         │
         ▼
    ┌────────────────────────┐
    │  CAPTURE CLICK DATA    │
    │  Timestamp: NOW()      │
    │  IP: req.ip            │
    │  User-Agent: headers   │
    │  Referrer: headers     │
    │  Session: generate_id  │
    └────────────────────────┘
         │
         ├─► Validate referral code exists
         ├─► Validate member is active
         ├─► Validate studio is active
         │
         ▼
    ┌────────────────────────────────────────────┐
    │  CREATE REFERRAL_CLICK RECORD              │
    │  {                                         │
    │    referral_code: "A7K9M2XQ",              │
    │    member_id: "uuid",                      │
    │    studio_id: "uuid",                      │
    │    session_id: "random_session_123",       │
    │    ip_address: "192.168.1.1",              │
    │    user_agent: "Mozilla/5.0...",           │
    │    referrer_url: "instagram.com",          │
    │    device_type: "mobile",                  │
    │    click_timestamp: "2026-02-01T10:30:00Z" │
    │  }                                         │
    └────────────────────────────────────────────┘
         │
         ▼
    ┌────────────────────────────────────────────┐
    │  CREATE REFERRAL_EVENT RECORD              │
    │  event_type: "link_click"                  │
    └────────────────────────────────────────────┘
         │
         ▼
    ┌────────────────────────────────────────────┐
    │  SET ATTRIBUTION COOKIE                    │
    │                                            │
    │  Name: "referral_code"                     │
    │  Value: "A7K9M2XQ"                         │
    │  Max-Age: 2592000 (30 days)                │
    │  Path: "/"                                 │
    │  Secure: true                              │
    │  SameSite: Lax                             │
    │                                            │
    │  Also set:                                 │
    │  • session_id cookie                       │
    │  • first_click_timestamp                   │
    └────────────────────────────────────────────┘
         │
         ▼
    ┌────────────────────────────────────────────┐
    │  REDIRECT TO LANDING PAGE                  │
    │  /refer/{code} → renders form              │
    └────────────────────────────────────────────┘


┌──────────────────────────────────────────────────────────────────────────────┐
│ STAGE 3: LEAD SIGNUP (When Visitor Submits Form)                            │
└──────────────────────────────────────────────────────────────────────────────┘

    Visitor fills out form
         │
         ▼
    ┌─────────────────────────────┐
    │  FRAUD CHECK #1             │
    │  Self-Referral Prevention   │
    │                             │
    │  IF lead.email ==           │
    │     member.user.email       │
    │  THEN reject                │
    └─────────────────────────────┘
         │
         ▼
    ┌─────────────────────────────┐
    │  FRAUD CHECK #2             │
    │  Duplicate Email            │
    │                             │
    │  IF email exists in         │
    │     leads for this studio   │
    │  THEN reject                │
    └─────────────────────────────┘
         │
         ▼
    ┌─────────────────────────────┐
    │  READ ATTRIBUTION COOKIE    │
    │  referral_code: "A7K9M2XQ"  │
    │  session_id: "sess_123"     │
    └─────────────────────────────┘
         │
         ▼
    ┌──────────────────────────────────────────────┐
    │  CREATE LEAD RECORD                          │
    │  {                                           │
    │    studio_id: "uuid",                        │
    │    referred_by_member_id: "uuid",            │
    │    referral_code_used: "A7K9M2XQ",           │
    │    first_name: "John",                       │
    │    last_name: "Doe",                         │
    │    email: "john@example.com",                │
    │    phone: "(555) 123-4567",                  │
    │    status: "new",                            │
    │    source_url: "app.com/refer/A7K9M2XQ",     │
    │    utm_params: {...}                         │
    │  }                                           │
    └──────────────────────────────────────────────┘
         │
         ▼
    ┌──────────────────────────────────────────────┐
    │  CREATE ATTRIBUTION RECORD                   │
    │  (FIRST-TOUCH MODEL)                         │
    │  {                                           │
    │    lead_id: "lead_uuid",                     │
    │    member_id: "member_uuid",                 │
    │    studio_id: "studio_uuid",                 │
    │    referral_code: "A7K9M2XQ",                │
    │    attribution_model: "first_touch",         │
    │    first_click_date: "2026-02-01T10:30:00Z", │
    │    signup_date: "2026-02-01T10:35:00Z",      │
    │    locked: false,                            │
    │    all_referral_codes_clicked: ["A7K9M2XQ"], │
    │    source_channel: "instagram"               │
    │  }                                           │
    └──────────────────────────────────────────────┘
         │
         ├─► Update ReferralClick.converted_to_lead = true
         ├─► Create ReferralEvent (event_type: "lead_signup")
         ├─► Increment Member.total_referrals
         │
         ▼
    ┌──────────────────────────────────────────────┐
    │  NOTIFY STUDIO                               │
    │  Send email: "New referral lead received"    │
    └──────────────────────────────────────────────┘


┌──────────────────────────────────────────────────────────────────────────────┐
│ STAGE 4: CONVERSION TRACKING (Trial → Paid Member)                          │
└──────────────────────────────────────────────────────────────────────────────┘

    Studio marks lead as "trial_started"
         │
         ▼
    ┌────────────────────────────────┐
    │  CREATE REFERRAL_EVENT         │
    │  event_type: "trial_started"   │
    └────────────────────────────────┘
         │
         │
    Studio marks lead as "converted"
         │
         ▼
    ┌────────────────────────────────────────────────┐
    │  LOCK ATTRIBUTION                              │
    │  AttributionRecord.locked = true               │
    │  AttributionRecord.locked_date = NOW()         │
    │  AttributionRecord.conversion_date = NOW()     │
    │                                                │
    │  REASON: Once converted, attribution is final  │
    │  and cannot be disputed or changed             │
    └────────────────────────────────────────────────┘
         │
         ├─► Update Lead.status = "converted"
         ├─► Update Lead.conversion_date
         ├─► Increment Member.successful_referrals
         │
         ▼
    ┌────────────────────────────────────────────────┐
    │  CREATE REWARD_TRIGGER RECORD                  │
    │  {                                             │
    │    member_id: "uuid",                          │
    │    lead_id: "uuid",                            │
    │    campaign_id: "uuid",                        │
    │    trigger_event: "paid_membership",           │
    │    trigger_date: NOW(),                        │
    │    verification_status: "pending",             │
    │    verification_delay_days: 7,                 │
    │    reward_eligible_date: NOW() + 7 days        │
    │  }                                             │
    └────────────────────────────────────────────────┘
         │
         ▼
    ┌────────────────────────────────────────────────┐
    │  AFTER VERIFICATION DELAY (7 days default)     │
    │                                                │
    │  IF no refund/chargeback:                      │
    │    • Create Reward record                      │
    │    • Update RewardTrigger.reward_id            │
    │    • Notify member: "You earned a reward!"     │
    │    • Increment Member.total_rewards_earned     │
    └────────────────────────────────────────────────┘


┌──────────────────────────────────────────────────────────────────────────────┐
│ STAGE 5: FRAUD DETECTION (Continuous Monitoring)                            │
└──────────────────────────────────────────────────────────────────────────────┘

    ┌─────────────────────────┐
    │  FRAUD RULES ENGINE     │
    │  (runs on every event)  │
    └─────────────────────────┘
              │
    ┌─────────┴─────────────────────────────────┐
    │                                           │
    ▼                                           ▼
┌──────────────────┐                   ┌──────────────────┐
│ PREVENTION RULES │                   │ DETECTION RULES  │
│ (auto-block)     │                   │ (flag & review)  │
└──────────────────┘                   └──────────────────┘
    │                                           │
    ├─► Rule: Self-referral                    ├─► Rule: Low conversion rate
    │   Check: lead.email == member.email      │   Check: 10+ leads, <5% converted
    │   Action: REJECT signup                  │   Action: FLAG member
    │                                           │
    ├─► Rule: Duplicate email                  ├─► Rule: Rapid referrals
    │   Check: email in leads table            │   Check: 5+ leads in 24 hours
    │   Action: REJECT signup                  │   Action: FLAG member
    │                                           │
    ├─► Rule: Suspended member                 ├─► Rule: Same IP pattern
    │   Check: member.status != active         │   Check: 80%+ leads from same IP
    │   Action: REJECT (show error)            │   Action: FLAG member
    │                                           │
    └─► Rule: Inactive studio                  ├─► Rule: Email pattern similarity
        Check: studio.status != active         │   Check: similar email prefixes
        Action: REJECT (show error)            │   Action: FLAG member
                                                │
                                                └─► Rule: Click fraud
                                                    Check: 100+ clicks, 0 signups
                                                    Action: FLAG member


┌──────────────────────────────────────────────────────────────────────────────┐
│ STAGE 6: ATTRIBUTION CONFLICT RESOLUTION                                     │
└──────────────────────────────────────────────────────────────────────────────┘

    Scenario: Lead clicks MULTIPLE referral links before signing up
         │
         ▼
    ┌────────────────────────────────────────────────────┐
    │  ATTRIBUTION RULES (applied in order)              │
    └────────────────────────────────────────────────────┘
         │
    ┌────┴─────────────────────────────────────────────┐
    │                                                   │
    ▼                                                   ▼
┌─────────────────┐                           ┌──────────────────┐
│ FIRST-TOUCH     │  <-- DEFAULT              │  LAST-TOUCH      │
│ (recommended)   │                           │  (alternative)   │
└─────────────────┘                           └──────────────────┘
    │                                                   │
    │ Logic:                                            │ Logic:
    │ • Credit goes to FIRST code clicked               │ • Credit goes to LAST code clicked
    │ • Stored in attribution.first_click_date          │ • Stored in attribution.last_click_date
    │ • Cookie tracks original code                     │ • Cookie overwrites on each click
    │ • Fair to early advocates                         │ • Favors recent touchpoints
    │                                                   │
    └────────────────────┬──────────────────────────────┘
                         │
                         ▼
                ┌──────────────────┐
                │ LOCK ATTRIBUTION │
                │ (on conversion)  │
                └──────────────────┘
                         │
                         ├─► Set attribution.locked = true
                         ├─► Set attribution.conversion_date
                         └─► IMMUTABLE after this point


┌──────────────────────────────────────────────────────────────────────────────┐
│ COOKIE & SESSION PERSISTENCE LOGIC                                          │
└──────────────────────────────────────────────────────────────────────────────┘

    Cookie Configuration:
    ┌─────────────────────────────────────────────────────┐
    │ Name:      referral_code                            │
    │ Value:     A7K9M2XQ                                 │
    │ Duration:  30 days (2,592,000 seconds)              │
    │ Path:      / (entire domain)                        │
    │ Secure:    true (HTTPS only)                        │
    │ SameSite:  Lax (allows cross-site navigation)       │
    │ HttpOnly:  false (needs JS read access)             │
    └─────────────────────────────────────────────────────┘

    Session Persistence Rules:
    • Survives browser refresh ✓
    • Survives form validation errors ✓
    • Survives multi-step signup ✓
    • Survives browser close/reopen (if within 30 days) ✓
    • Does NOT survive cookie clear ✗
    • Does NOT survive incognito mode close ✗

    Fallback Strategy:
    IF cookie missing BUT session_id in URL params:
      → Restore from URL
    ELSE IF neither available:
      → Attribution = NULL (direct signup, no referral)


┌──────────────────────────────────────────────────────────────────────────────┐
│ EVENT TRACKING SCHEMA                                                        │
└──────────────────────────────────────────────────────────────────────────────┘

    All tracked events (in order):

    1. link_click
       ├─ When: User clicks referral link
       ├─ Data: IP, device, channel, timestamp
       └─ Creates: ReferralClick + ReferralEvent

    2. lead_signup
       ├─ When: Visitor submits contact form
       ├─ Data: Lead info, session, attribution
       └─ Creates: Lead + AttributionRecord + ReferralEvent

    3. trial_started (optional)
       ├─ When: Studio marks lead as trial
       ├─ Data: Trial start date
       └─ Creates: ReferralEvent

    4. visit_scheduled
       ├─ When: Studio schedules lead's visit
       ├─ Data: Appointment datetime
       └─ Creates: ReferralEvent

    5. visit_completed
       ├─ When: Lead attends first visit
       ├─ Data: Attendance confirmed
       └─ Creates: ReferralEvent

    6. membership_purchased
       ├─ When: Lead converts to paying member
       ├─ Data: Payment amount, membership type
       ├─ Creates: ReferralEvent
       └─ LOCKS AttributionRecord

    7. reward_triggered
       ├─ When: Conversion verified (after delay)
       ├─ Data: Reward amount, campaign
       └─ Creates: RewardTrigger + ReferralEvent

    8. reward_fulfilled
       ├─ When: Member receives/redeems reward
       ├─ Data: Fulfillment method
       └─ Creates: ReferralEvent + updates Reward


┌──────────────────────────────────────────────────────────────────────────────┐
│ ANALYTICS & REPORTING HOOKS                                                  │
└──────────────────────────────────────────────────────────────────────────────┘

    Conversion Funnel Tracking:
    
    Click → Signup → Trial → Paid → Reward
     │       │        │       │       │
     │       │        │       │       └─► reward_triggered event
     │       │        │       └─► membership_purchased event + LOCK
     │       │        └─► trial_started event
     │       └─► lead_signup event + AttributionRecord
     └─► link_click event + ReferralClick

    Queryable Metrics:
    • Click-through rate: (signups / clicks) * 100
    • Signup-to-trial rate: (trials / signups) * 100
    • Trial-to-paid rate: (paid / trials) * 100
    • Overall conversion rate: (paid / clicks) * 100
    • Average time to convert: AVG(conversion_date - first_click_date)
    • Top performing channels: GROUP BY source_channel
    • Top performing members: ORDER BY successful_referrals DESC
    • Revenue generated: SUM(conversion_value) WHERE attributed = member_id

    Dashboard Queries:
    ┌──────────────────────────────────────────────────────────┐
    │ For Studio Owner:                                        │
    │ • Total clicks (all members)                             │
    │ • Total leads by campaign                                │
    │ • Conversion funnel visualization                        │
    │ • Top referring members                                  │
    │ • Channel performance (IG vs FB vs Email)                │
    │                                                          │
    │ For Member:                                              │
    │ • My total clicks                                        │
    │ • My leads (with status)                                 │
    │ • My conversion rate                                     │
    │ • My rewards earned                                      │
    │ • My best performing channel                             │
    └──────────────────────────────────────────────────────────┘
Complete Data Model Schema
{
  "referral_identifier_system": {
    "referral_code": {
      "format": "8-character uppercase alphanumeric",
      "charset": "ABCDEFGHJKLMNPQRSTUVWXYZ23456789",
      "excluded_chars": ["O", "0", "I", "1", "L"],
      "uniqueness": "globally unique across all studios",
      "generation": "crypto-random",
      "collision_probability": "1 in 2.8 trillion",
      "examples": ["A7K9M2XQ", "B3H8K5LP", "X9F4N7WM"],
      "regeneration_rules": {
        "allowed_by": ["studio_owner"],
        "reason_required": true,
        "invalidates_old_code": true,
        "creates_audit_log": true
      }
    },
    "referral_link": {
      "structure": "{base_url}/refer/{referral_code}",
      "examples": [
        "https://app.referralhub.com/refer/A7K9M2XQ",
        "https://studio.com/refer/B3H8K5LP"
      ],
      "with_utm": "{base_url}/refer/{code}?utm_source=instagram&utm_medium=story&utm_campaign=spring",
      "uniqueness": "unique per member, persistent across studio",
      "expiration": "never (unless member removed or code regenerated)"
    }
  },

  "tracking_entities": {
    "referral_click": {
      "id": "uuid",
      "referral_code": "string (indexed)",
      "member_id": "uuid (indexed)",
      "studio_id": "uuid (indexed)",
      "session_id": "string (unique per visit)",
      "ip_address": "string (fraud detection)",
      "user_agent": "string (device/browser info)",
      "referrer_url": "string (where they came from)",
      "utm_source": "string | null",
      "utm_medium": "string | null",
      "utm_campaign": "string | null",
      "device_type": "enum: mobile | tablet | desktop | unknown",
      "browser": "string (Chrome, Safari, etc.)",
      "country": "string (from IP geolocation)",
      "city": "string (from IP geolocation)",
      "converted_to_lead": "boolean (default: false)",
      "lead_id": "uuid | null (if converted)",
      "click_timestamp": "datetime",
      "created_date": "datetime (auto)",
      "indexes": ["referral_code", "member_id", "session_id", "ip_address"]
    },

    "referral_event": {
      "id": "uuid",
      "event_type": "enum: link_click | lead_signup | trial_started | visit_scheduled | visit_completed | membership_purchased | reward_triggered | reward_fulfilled",
      "member_id": "uuid (indexed)",
      "lead_id": "uuid | null (indexed)",
      "studio_id": "uuid (indexed)",
      "campaign_id": "uuid | null",
      "referral_code": "string",
      "session_id": "string",
      "metadata": {
        "source_channel": "string (instagram, facebook, email, sms, whatsapp, direct)",
        "device_type": "string",
        "conversion_value": "number (revenue generated)",
        "reward_amount": "number"
      },
      "timestamp": "datetime",
      "ip_address": "string",
      "created_date": "datetime (auto)",
      "indexes": ["event_type", "member_id", "lead_id", "timestamp"]
    },

    "attribution_record": {
      "id": "uuid",
      "lead_id": "uuid (indexed, unique)",
      "member_id": "uuid (indexed)",
      "studio_id": "uuid (indexed)",
      "referral_code": "string (indexed)",
      "attribution_model": "enum: first_touch | last_touch | manual_override",
      "first_click_date": "datetime",
      "last_click_date": "datetime",
      "signup_date": "datetime",
      "conversion_date": "datetime | null",
      "locked": "boolean (default: false, becomes true on conversion)",
      "locked_date": "datetime | null",
      "all_referral_codes_clicked": "array<string> (multi-touch tracking)",
      "source_channel": "string (primary channel)",
      "cookie_id": "string (browser identifier)",
      "override_reason": "string | null",
      "override_by": "uuid | null (user who made override)",
      "created_date": "datetime (auto)",
      "updated_date": "datetime (auto)",
      "indexes": ["lead_id", "member_id", "locked"]
    },

    "reward_trigger": {
      "id": "uuid",
      "member_id": "uuid (indexed)",
      "lead_id": "uuid (indexed)",
      "campaign_id": "uuid",
      "studio_id": "uuid",
      "trigger_event": "enum: lead_signup | trial_started | paid_membership",
      "trigger_date": "datetime",
      "verification_status": "enum: pending | verified | rejected",
      "verification_delay_days": "number (default: 7)",
      "reward_eligible_date": "datetime (trigger_date + delay)",
      "reward_id": "uuid | null (created reward)",
      "reward_amount": "number",
      "auto_approved": "boolean (from campaign settings)",
      "verified_by": "uuid | null (staff who verified)",
      "rejection_reason": "string | null",
      "created_date": "datetime (auto)",
      "indexes": ["member_id", "verification_status", "reward_eligible_date"]
    }
  },

  "attribution_rules": {
    "first_touch_attribution": {
      "description": "Credit goes to the first referral link clicked (default)",
      "logic": "attribution.referral_code = first_code_in_all_codes_clicked",
      "use_case": "Fair to members who introduced the lead",
      "benefits": ["Rewards early advocates", "Prevents attribution stealing"],
      "implementation": "Store first_click_date, use it as source of truth"
    },
    "last_touch_attribution": {
      "description": "Credit goes to the most recent referral link clicked",
      "logic": "attribution.referral_code = last_code_in_all_codes_clicked",
      "use_case": "Studios that want to reward closing touchpoint",
      "benefits": ["Rewards final convincer", "Simpler logic"],
      "implementation": "Overwrite cookie on each click, use last_click_date"
    },
    "multi_touch_attribution": {
      "description": "Future: Split credit among multiple referrers",
      "status": "not_implemented",
      "planned_logic": "40% first touch, 40% last touch, 20% middle touches",
      "complexity": "requires reward splitting, more complex disputes"
    },
    "conflict_resolution": {
      "same_member_multiple_clicks": "Ignore duplicates, count as 1 attribution",
      "different_members_same_lead": "Use first_touch (default) or last_touch (if configured)",
      "manual_override": {
        "allowed_by": ["studio_owner", "platform_admin"],
        "requires_reason": true,
        "creates_audit_log": true,
        "only_before_lock": true
      }
    },
    "locking_rules": {
      "when_locked": "On lead.status = 'converted' AND payment verified",
      "locked_fields": ["member_id", "referral_code", "attribution_model"],
      "unlocked_fields": ["Can still update conversion_date, metadata"],
      "override_locked_attribution": {
        "allowed": false,
        "exception": "platform_admin with critical fraud evidence"
      }
    }
  },

  "fraud_prevention_rules": {
    "prevention_layer_1_auto_block": {
      "self_referral": {
        "check": "lead.email === member.user.email",
        "action": "reject_signup",
        "error_message": "You cannot refer yourself",
        "severity": "critical"
      },
      "duplicate_email": {
        "check": "lead.email EXISTS IN leads WHERE studio_id = X",
        "action": "reject_signup",
        "error_message": "This email has already been referred to this studio",
        "severity": "high"
      },
      "suspended_member": {
        "check": "member.status === 'suspended'",
        "action": "reject_signup",
        "error_message": "This referral link is no longer active",
        "severity": "high"
      },
      "inactive_studio": {
        "check": "studio.status !== 'active'",
        "action": "reject_signup",
        "error_message": "This studio is not currently accepting referrals",
        "severity": "medium"
      }
    },
    "detection_layer_2_flagging": {
      "low_conversion_rate": {
        "check": "member.total_referrals >= 10 AND (successful_referrals / total_referrals) < 0.05",
        "action": "flag_member_for_review",
        "severity": "medium",
        "review_message": "Member has 10+ referrals but <5% conversion rate"
      },
      "rapid_referrals": {
        "check": "5+ leads created within 24 hours from same member",
        "action": "flag_member_for_review",
        "severity": "medium",
        "review_message": "Unusual referral velocity detected"
      },
      "same_ip_pattern": {
        "check": "80%+ of member's leads from same IP address",
        "action": "flag_member_for_review",
        "severity": "high",
        "review_message": "Suspicious IP clustering detected"
      },
      "email_pattern_similarity": {
        "check": "2+ leads with same email prefix (before @)",
        "action": "flag_member_for_review",
        "severity": "medium",
        "review_message": "Similar email patterns detected"
      },
      "click_fraud": {
        "check": "100+ clicks but 0 signups within 30 days",
        "action": "flag_member_for_review",
        "severity": "medium",
        "review_message": "High click volume with zero conversions"
      }
    },
    "prevention_layer_3_device_fingerprinting": {
      "status": "future_enhancement",
      "description": "Track device fingerprint to detect same-device self-referrals",
      "implementation": "Use FingerprintJS or similar library"
    }
  }
}
Error Handling & Edge Cases
Invalid Referral Links

Scenario 1: Code doesn't exist

→ Show: "Referral code not found"

→ Action: Display error page, offer direct studio link

Scenario 2: Code exists but member suspended

→ Show: "This referral link is no longer active"

→ Action: Allow direct signup without referral attribution

Scenario 3: Studio paused/cancelled

→ Show: "This studio is not currently accepting referrals"

→ Action: Display studio contact info for direct inquiry

Duplicate Leads

Scenario: Email already in system

→ Check 1: Exact email match in Lead entity

→ Check 2: Same studio_id

→ Show: "This email has already been referred to this studio"

→ Alternative: "Already interested? Contact us directly at [studio email]"

Missing Attribution Data

Scenario: Cookie deleted before signup

→ Fallback 1: Check session_id in URL params

→ Fallback 2: Check referrer header for /refer/ pattern

→ Last resort: Create lead with attribution = NULL (direct signup)

Scenario: Lead created but attribution fails

→ Create lead normally

→ Log error to monitoring system

→ Studio owner can manually assign attribution later

Member Removed from Program

Scenario: Member deleted before lead converts

→ AttributionRecord remains (historical data)

→ RewardTrigger not created (member ineligible)

→ Lead still visible to studio (attribution shown as "Former Member")

Scenario: Member removed AFTER earning rewards

→ Existing rewards remain (contractual obligation)

→ New referrals from old links rejected

→ Recommendation: Mark member inactive instead of deleting

Campaign Deactivated Mid-Funnel

Scenario: Lead signed up during Campaign A, converts after Campaign A ended

→ Attribution still uses Campaign A (campaign_id locked)

→ Reward uses Campaign A's reward structure

→ Principle: Honor the terms active when lead signed up

All System Messages
Success Messages

✓ "Thank you! The studio will contact you soon."

✓ "Referral tracked! When you become a member, your friend will earn their reward."

✓ "Click recorded successfully"

✓ "Attribution locked to member [NAME]"

✓ "Reward triggered! Pending verification."

Error Messages

✗ "Invalid referral link"

✗ "Referral code not found"

✗ "This referral link is no longer active"

✗ "This studio is not currently accepting referrals"

✗ "You cannot refer yourself"

✗ "This email has already been referred to this studio"

✗ "Please fill in all required fields"

✗ "Please enter a valid email address"

✗ "Please accept the terms to continue"

✗ "Failed to submit. Please try again."

✗ "Failed to load referral information"

Info Messages

ℹ "Loading referral..."

ℹ "Validating referral code..."

ℹ "Processing your information..."

ℹ "This referral was tracked from [CHANNEL]"

Warning Messages

⚠ "Attribution cookie not found - referral may not be tracked"

⚠ "Multiple referral codes detected - using first-touch attribution"

⚠ "This lead is pending review for fraud detection"

Tooltips & Help Text

💡 Referral Code: "Your unique 8-character code that tracks all your referrals"

💡 Cookie Notice: "We use cookies to track your referral for 30 days"

💡 First-Touch: "Credit goes to whoever referred you first"

💡 Locked Attribution: "Once a lead converts, the attribution is permanent and cannot be changed"

💡 Verification Delay: "Rewards are granted 7 days after conversion to allow for refund period"

Future Tracking Enhancements
Phase 1: Enhanced Tracking
  • 🔹 UTM parameter support: Full campaign tracking (source, medium, campaign, content, term)
  • 🔹 Device fingerprinting: Detect same-device self-referrals even with different emails
  • 🔹 Click heatmaps: Visualize where clicks are coming from geographically
  • 🔹 Time-to-convert analytics: Measure days from click to conversion
  • 🔹 Channel attribution: Which platform drives best conversions (IG vs FB)
Phase 2: Multi-Touch Attribution
  • 🔹 Linear attribution: Equal credit to all touchpoints
  • 🔹 Time decay: More credit to recent touchpoints
  • 🔹 Position-based: 40-20-40 (first-middle-last)
  • 🔹 Custom weights: Studio configures attribution split
  • 🔹 Fractional rewards: Split reward among multiple referrers
Phase 3: Advanced Analytics
  • 🔹 Cohort analysis: Track cohorts by signup month
  • 🔹 LTV prediction: Estimate lifetime value of referred members
  • 🔹 A/B testing: Test different landing page versions
  • 🔹 Funnel drop-off: Identify where leads abandon
  • 🔹 Member scoring: Predict which members will be top referrers
Phase 4: Integration & API
  • 🔹 Webhook events: Real-time notifications on conversions
  • 🔹 Zapier integration: Connect to 5000+ apps
  • 🔹 CRM sync: Push leads to HubSpot, Salesforce
  • 🔹 Analytics platforms: Send events to Google Analytics, Mixpanel
  • 🔹 Custom domain tracking: track.yourstudio.com/ref/CODE
Technical Implementation Notes

Cookie Management

Why 30 days? Industry standard attribution window. Long enough to allow consideration time, short enough to be fair (prevents stale attributions).

Cookie Attributes:

  • • Secure: Only transmitted over HTTPS
  • • SameSite=Lax: Allows referral from social media
  • • HttpOnly=false: Needs JavaScript read access for tracking
  • • Path=/: Available across entire site

Performance Considerations

  • • Index strategy: Index on referral_code, member_id, session_id for fast lookups
  • • Async tracking: Click tracking runs async (doesn't block page load)
  • • Batch updates: Member stats updated in background job, not real-time
  • • Cache attribution: Cache active referral codes in Redis for instant validation

Data Retention

  • • ReferralClick: Retain 2 years (analytics, fraud detection)
  • • ReferralEvent: Retain indefinitely (audit trail)
  • • AttributionRecord: Retain indefinitely (legal/disputes)
  • • RewardTrigger: Retain 7 years (tax/accounting)

Security Best Practices

  • • Never expose member_id or user_id in public URLs
  • • Use opaque referral codes only
  • • Rate limit click tracking (prevent DDoS on tracking endpoint)
  • • Validate all input on server-side (email format, required fields)
  • • Log all fraud detections to AuditLog for investigation