# Telegram Referral Testing Strategy (No-App Approach)

This document outlines how to test the referral system for the Telegram Mini App without requiring the actual Telegram mobile or desktop application.

## Overview

The referral system relies on:
1.  **`start_param` in `initData`:** Passed when opening the Mini App via a referral link (e.g., `t.me/bot?start=ref123`).
2.  **`start_param` in API calls:** The frontend extracts this from the launch parameters and sends it to the backend during authentication.

To test this without the app, we need to simulate valid `initData` payloads that contain specific `start_param` values.

## How Referral Codes Work

### Referral Code Generation
- Every user automatically gets a unique `referral_code` when they sign up (10-character alphanumeric string, e.g., `1oaw3cbi3n`)
- This code is stored in the `users` table and can be found in the user's profile

### Referral Flow
1. **Referrer shares their link:** User A (referrer) shares a link like `t.me/yourbot?start=1oaw3cbi3n` where `1oaw3cbi3n` is their `referral_code`
2. **New user clicks link:** User B (referee) clicks the link, which opens the Mini App with `start_param=1oaw3cbi3n` in the `initData`
3. **Backend processes referral:** When User B authenticates:
   - Backend receives `start_param=1oaw3cbi3n`
   - Backend looks up the user with `referral_code=1oaw3cbi3n` (User A)
   - Backend sets User B's `referred_by` field to User A's ID
   - This only happens if User B doesn't already have a referrer (referrals are set once)

### Key Points
- **`referral_code`** = The unique code belonging to the referrer (stored in their user record)
- **`start_param`** = The value passed in the Telegram link, which should match a referrer's `referral_code`
- To test referrals, you need:
  1. An existing user in the database (the referrer) with a `referral_code`
  2. A new user's `initData` with `start_param` set to that referrer's `referral_code`

## Testing Methods

### 1. Automated Dev Testing (Recommended)

We have implemented a streamlined workflow for testing referrals directly in the development environment without needing external scripts.

**Prerequisites:**
- `DEBUG=True` in backend
- `ENABLE_DEV_TELEGRAM_AUTH=True` in backend `.env`
- `VITE_ENABLE_MOCK_TELEGRAM=true` in frontend `.env`

**Workflow:**
1.  **Login as Referrer:**
    - Open the frontend (`http://localhost:5173`).
    - Login as a user who will be the "Referrer".
2.  **Generate Test Link:**
    - Go to the **Referrals** tab.
    - Click **"Share Link"**.
    - In dev mode, this attempts to "share" but intercepts the action.
    - A prompt appears: Enter a name for the *New User* (Referee).
    - A modal appears with a **Test URL**.
3.  **Simulate Referral:**
    - Copy the generated URL.
    - Open a **Incognito/Private Window** (or clear localStorage).
    - Paste the URL.
    - The mock authentication system detects the URL parameters (`#tgWebAppData=...`).
    - It automatically logs you in as the new user and attributes the referral.
4.  **Verify:**
    - Check the new user's profile or backend to confirm `referred_by` is set.

### 2. Manual `initData` Generation (Legacy/Script)

If you need to generate data manually for backend testing or other scenarios:

**Tools:**
-   `scripts/generate_telegram_init_data.py`: A helper script to generate valid `initData` strings.

**Usage:**
```bash
# Run from project root
python scripts/generate_telegram_init_data.py --user-id 12345 --start-param REF_CODE_XYZ
```

This will output a signed `initData` string.

### 3. API Level Testing (Backend)

You can test the referral logic directly against the backend API using `curl` or Postman.

**Endpoint:** `POST /api/users/auth/telegram/`

**Steps:**
1.  Generate a test `initData` string using the methods above.
2.  Send a POST request:

```bash
curl -X POST http://localhost:8000/api/users/auth/telegram/ \
     -H "Content-Type: application/json" \
     -d '{
           "init_data": "<GENERATED_INIT_DATA_STRING>",
           "start_param": "REF_CODE_XYZ"
         }'
```

3.  **Verify:**
    -   Check the response `user` object; `referred_by` should match the ID of the referrer.

### 4. Frontend Integration Testing (Custom URL)

If you manually constructed a URL using the script in step 2:

1.  **Construct URL:**
    -   Base URL: `http://localhost:5173/`
    -   Append hash params: `#tgWebAppData=<URL_ENCODED_INIT_DATA>`
2.  **Load:**
    -   Open in browser.
    -   The `useTelegram` hook detects the hash, saves it to `localStorage`, and authenticates user.

### 5. End-to-End Commission Testing

To fully verify the referral system, test that commissions are paid when the referee invests.

**Prerequisite - Fund the Referee:**
```bash
# Add 1000 credits to the referee
python manage.py manage_wallet <REFEREE_ID> 1000 add --remarks "Test Funding"
```

**Trigger Commission:**
1.  Login as the **Referee**.
2.  Create an investment via `POST /api/investments/` or UI.
3.  This should trigger a commission payout.

**Verify Payout:**
1.  Login as the **Referrer**.
2.  Check `GET /api/distribute-rewards/` logs or transaction history.

## Summary Checklist for Testing

-   [ ] **Referrer Exists:** Ensure the user owning the `referral_code` exists.
-   [ ] **New User:** The "referee" must be new (referrals set only on creation/first auth).
-   [ ] **Correct Mapping:** The `start_param` must match the referrer's `referral_code`.
-   [ ] **Self-Referral:** Backend prevents self-referral.
