# Referral System API Documentation

## Overview

The Referral System is a dynamic multi-level referral program where:
- Admin can configure the number of referral levels (e.g., 3 levels, 5 levels)
- Each user gets a unique referral code
- Users can refer others using their referral code
- Referrers earn commissions when their referrals perform actions (signup, top-up)
- Commissions are automatically calculated and added to the referrer's wallet
- Users can view their downline (people they referred) and earnings

---

## Table of Contents

1. [Admin APIs](#admin-apis)
   - [Get Referral Settings](#get-referral-settings)
   - [Update Referral Settings](#update-referral-settings)
   - [Get Referral Statistics](#get-referral-statistics)

2. [User APIs](#user-apis)
   - [Get Referral Code](#get-referral-code)
   - [Get Downline](#get-downline)
   - [Get Earnings](#get-earnings)
   - [Credit Earnings to Wallet](#credit-earnings-to-wallet)

3. [Integration with Signup](#integration-with-signup)
4. [Integration with Top-Up](#integration-with-top-up)
5. [How It Works](#how-it-works)

---

## Admin APIs

All admin APIs require authentication using Bearer token in the Authorization header.

**Base URL:** `https://api.alldigtalseva.com/api/admin/referral`

### Get Referral Settings

Get the current active referral settings.

**Endpoint:** `GET /admin/referral/settings`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Response:**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "referral_levels": 3,
        "level_commissions": {
            "1": 10,
            "2": 5,
            "3": 2
        },
        "commission_type": "percentage",
        "signup_bonus": 50.00,
        "is_active": true,
        "created_by": 1,
        "created_at": "2025-12-05T10:00:00.000000Z",
        "updated_at": "2025-12-05T10:00:00.000000Z"
    }
}
```

**If no settings exist:**
```json
{
    "success": true,
    "data": null,
    "message": "No referral settings configured"
}
```

---

### Update Referral Settings

Create or update referral settings. This will deactivate any existing active settings and create new ones.

**Endpoint:** `POST /admin/referral/settings` or `PUT /admin/referral/settings`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "referral_levels": 3,
    "level_commissions": {
        "1": 10,
        "2": 5,
        "3": 2
    },
    "commission_type": "percentage",
    "signup_bonus": 50.00,
    "is_active": true
}
```

**Parameters:**
- `referral_levels` (required): Integer, 1-10. Number of referral levels.
- `level_commissions` (required): Object. Commission rates for each level. Keys must be level numbers (1, 2, 3, etc.), values must be numeric (0 or greater).
- `commission_type` (required): String, either "percentage" or "fixed".
  - If "percentage": Commission is calculated as (amount × rate) / 100
  - If "fixed": Commission is the fixed rate value
- `signup_bonus` (optional): Decimal. Bonus amount credited to referrer when someone signs up using their code. Default: 0.00
- `is_active` (optional): Boolean. Whether the settings are active. Default: true

**Example for Fixed Commission:**
```json
{
    "referral_levels": 3,
    "level_commissions": {
        "1": 100,
        "2": 50,
        "3": 25
    },
    "commission_type": "fixed",
    "signup_bonus": 50.00,
    "is_active": true
}
```

**Response:**
```json
{
    "success": true,
    "message": "Referral settings updated successfully",
    "data": {
        "id": 1,
        "referral_levels": 3,
        "level_commissions": {
            "1": 10,
            "2": 5,
            "3": 2
        },
        "commission_type": "percentage",
        "signup_bonus": 50.00,
        "is_active": true,
        "created_by": 1,
        "created_at": "2025-12-05T10:00:00.000000Z",
        "updated_at": "2025-12-05T10:00:00.000000Z"
    }
}
```

**Error Response (Validation):**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "referral_levels": ["The referral levels field is required."],
        "level_commissions.1": ["Commission rate for level 1 is required"]
    }
}
```

---

### Get Referral Statistics

Get overall referral system statistics.

**Endpoint:** `GET /admin/referral/statistics`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Response:**
```json
{
    "success": true,
    "data": {
        "total_referrals": 150,
        "total_earnings": 50000.00,
        "pending_earnings": 5000.00,
        "total_signup_bonuses": 7500.00,
        "total_topup_commissions": 42500.00
    }
}
```

---

## User APIs

**Base URL:** `https://api.alldigtalseva.com/api/referral`

### Get Referral Code

Get user's referral code and referral link.

**Endpoint:** `GET /referral/code`

**Query Parameters:**
- `user_id` (required): Integer. User ID.

**Example Request:**
```
GET /referral/code?user_id=1
```

**Response:**
```json
{
    "success": true,
    "data": {
        "referral_code": "ABC12345",
        "referral_link": "https://api.alldigtalseva.com/signup?ref=ABC12345"
    }
}
```

**Note:** If the user doesn't have a referral code, one will be automatically generated.

---

### Get Downline

Get list of users referred by a specific user (downline).

**Endpoint:** `GET /referral/downline`

**Query Parameters:**
- `user_id` (required): Integer. User ID.
- `level` (optional): Integer, 1-10. Filter by referral level. Default: 1 (direct referrals).

**Example Request:**
```
GET /referral/downline?user_id=1&level=1
```

**Response:**
```json
{
    "success": true,
    "level": 1,
    "summary": {
        "total_level_1": 10,
        "total_level_2": 25,
        "total_level_3": 50
    },
    "data": [
        {
            "id": 2,
            "name": "John Doe",
            "email": "john@example.com",
            "phone_number": "9876543210",
            "referral_code": "XYZ67890",
            "joined_at": "2025-12-01T10:00:00.000000Z",
            "level": 1
        },
        {
            "id": 3,
            "name": "Jane Smith",
            "email": "jane@example.com",
            "phone_number": "9876543211",
            "referral_code": "DEF11111",
            "joined_at": "2025-12-02T10:00:00.000000Z",
            "level": 1
        }
    ]
}
```

---

### Get Earnings

Get user's referral earnings with filtering options.

**Endpoint:** `GET /referral/earnings`

**Query Parameters:**
- `user_id` (required): Integer. User ID.
- `status` (optional): String. Filter by status: "pending", "credited", "cancelled".
- `earning_type` (optional): String. Filter by type: "signup", "topup", "transaction".
- `limit` (optional): Integer, 1-100. Number of records to return. Default: 50.

**Example Request:**
```
GET /referral/earnings?user_id=1&status=pending&limit=20
```

**Response:**
```json
{
    "success": true,
    "summary": {
        "total_earnings": 5000.00,
        "pending_earnings": 1000.00,
        "total_count": 50,
        "credited_count": 40
    },
    "data": [
        {
            "id": 1,
            "referrer_id": 1,
            "referred_id": 2,
            "level": 1,
            "earning_type": "topup",
            "source_id": 10,
            "source_type": "TopUpRequest",
            "amount": 1000.00,
            "commission_amount": 100.00,
            "status": "pending",
            "credited_at": null,
            "created_at": "2025-12-05T10:00:00.000000Z",
            "referred": {
                "id": 2,
                "name": "John Doe",
                "email": "john@example.com",
                "phone_number": "9876543210"
            }
        },
        {
            "id": 2,
            "referrer_id": 1,
            "referred_id": 3,
            "level": 1,
            "earning_type": "signup",
            "source_id": null,
            "source_type": null,
            "amount": 0.00,
            "commission_amount": 50.00,
            "status": "credited",
            "credited_at": "2025-12-05T10:05:00.000000Z",
            "created_at": "2025-12-05T10:00:00.000000Z",
            "referred": {
                "id": 3,
                "name": "Jane Smith",
                "email": "jane@example.com",
                "phone_number": "9876543211"
            }
        }
    ]
}
```

---

### Credit Earnings to Wallet

Credit pending referral earnings to user's wallet.

**Endpoint:** `POST /referral/credit-earnings`

**Request Body:**
```json
{
    "user_id": 1,
    "earning_ids": [1, 2, 3]
}
```

**Parameters:**
- `user_id` (required): Integer. User ID.
- `earning_ids` (optional): Array of integers. Specific earning IDs to credit. If not provided, all pending earnings will be credited.

**Response:**
```json
{
    "success": true,
    "message": "₹1000.00 credited to wallet successfully",
    "data": {
        "credited_amount": 1000.00,
        "new_wallet_balance": 5000.00
    }
}
```

**Error Response:**
```json
{
    "success": false,
    "message": "No pending earnings to credit"
}
```

---

## Integration with Signup

### User Signup with Referral Code

When a user signs up, they can provide a referral code. The referral will be processed after OTP verification.

**Endpoint:** `POST /user/signup`

**Request Body:**
```json
{
    "email": "newuser@example.com",
    "phone_number": "9876543210",
    "user_type": "user",
    "referral_code": "ABC12345"
}
```

**Note:** The `referral_code` is optional. If provided, it will be processed during OTP verification.

### OTP Verification with Referral

**Endpoint:** `POST /user/verify-otp`

**Request Body:**
```json
{
    "email": "newuser@example.com",
    "otp": "123456",
    "password": "password123",
    "referral_code": "ABC12345"
}
```

**What Happens:**
1. User is verified and password is set
2. If `referral_code` is provided:
   - System finds the referrer by code
   - Sets `referred_by` on the new user
   - Creates referral relationships for all configured levels
   - If signup bonus is configured, creates an earning record for the referrer
3. New user gets their own referral code generated

**Response includes referral_code:**
```json
{
    "success": true,
    "message": "Signup completed successfully",
    "data": {
        "id": 4,
        "email": "newuser@example.com",
        "phone_number": "9876543210",
        "user_type": "user",
        "wallet_balance": 0.00,
        "is_verified": true,
        "referral_code": "NEW12345"
    }
}
```

---

## Integration with Top-Up

When an admin approves a top-up request, referral earnings are automatically processed for all referrers in the chain.

**What Happens:**
1. Admin approves top-up request
2. User's wallet is credited with the final amount (including discounts/cashback)
3. System automatically:
   - Finds all referrers in the chain (up to configured levels)
   - Calculates commission for each level based on settings
   - Creates earning records with status "pending"
   - Commissions are based on the `final_credited_amount`

**Example:**
- User (ID: 2) has a top-up of ₹1000 approved
- Final credited amount: ₹1100 (includes ₹100 cashback)
- Referral chain:
  - Level 1 referrer (User ID: 1): 10% = ₹110
  - Level 2 referrer (User ID: 5): 5% = ₹55
  - Level 3 referrer (User ID: 10): 2% = ₹22
- All three earning records are created with status "pending"
- Referrers can credit these to their wallet using the credit earnings API

---

## How It Works

### Referral Chain Example

Let's say admin configures 3 levels with these commissions:
- Level 1: 10%
- Level 2: 5%
- Level 3: 2%

**Scenario:**
- User A refers User B (Level 1)
- User B refers User C (Level 2 from A's perspective)
- User C refers User D (Level 3 from A's perspective)

**When User D does a ₹1000 top-up:**
- User A (Level 1) earns: ₹100 (10%)
- User B (Level 2) earns: ₹50 (5%)
- User C (Level 3) earns: ₹20 (2%)

### Commission Calculation

**Percentage Type:**
```
Commission = (Amount × Rate) / 100
Example: (1000 × 10) / 100 = ₹100
```

**Fixed Type:**
```
Commission = Rate (fixed amount)
Example: If rate is ₹100, commission is always ₹100
```

### Earning Status Flow

1. **Pending**: Earning is created but not yet credited to wallet
2. **Credited**: Earning has been added to wallet balance
3. **Cancelled**: Earning was cancelled (e.g., if top-up was rejected)

### Automatic vs Manual Credit

- **Signup Bonus**: Can be automatically credited or manually credited (configurable)
- **Top-up Commissions**: Created as "pending" and must be manually credited using the credit earnings API

---

## Database Schema

### referral_settings
- `id`: Primary key
- `referral_levels`: Number of levels (1-10)
- `level_commissions`: JSON object with commission rates per level
- `commission_type`: "percentage" or "fixed"
- `signup_bonus`: Bonus amount for signup
- `is_active`: Boolean
- `created_by`: Admin ID
- `timestamps`

### referral_relationships
- `id`: Primary key
- `referrer_id`: User who referred (foreign key)
- `referred_id`: User who was referred (foreign key)
- `level`: Referral level (1, 2, 3, etc.)
- `timestamps`

### referral_earnings
- `id`: Primary key
- `referrer_id`: User who earned (foreign key)
- `referred_id`: User who generated earning (foreign key)
- `level`: Referral level
- `earning_type`: "signup", "topup", "transaction"
- `source_id`: ID of source (e.g., top_up_request_id)
- `source_type`: Type of source (e.g., "TopUpRequest")
- `amount`: Original amount
- `commission_amount`: Commission earned
- `status`: "pending", "credited", "cancelled"
- `credited_at`: Timestamp when credited
- `timestamps`

### users (additional fields)
- `referral_code`: Unique referral code (8 characters)
- `referred_by`: User ID who referred this user (foreign key)

---

## Error Responses

### 401 Unauthorized
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

### 422 Validation Error
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "user_id": ["The user id field is required."],
        "referral_code": ["The selected referral code is invalid."]
    }
}
```

### 404 Not Found
```json
{
    "success": false,
    "message": "User not found"
}
```

---

## Testing Examples

### cURL Examples

**1. Get Referral Code:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/referral/code?user_id=1"
```

**2. Get Downline:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/referral/downline?user_id=1&level=1"
```

**3. Get Earnings:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/referral/earnings?user_id=1&status=pending"
```

**4. Credit Earnings:**
```bash
curl -X POST "https://api.alldigtalseva.com/api/referral/credit-earnings" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": 1,
    "earning_ids": [1, 2, 3]
  }'
```

**5. Update Referral Settings (Admin):**
```bash
curl -X POST "https://api.alldigtalseva.com/api/admin/referral/settings" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "referral_levels": 3,
    "level_commissions": {
      "1": 10,
      "2": 5,
      "3": 2
    },
    "commission_type": "percentage",
    "signup_bonus": 50.00,
    "is_active": true
  }'
```

**6. Get Referral Statistics (Admin):**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/referral/statistics" \
  -H "Authorization: Bearer {admin_token}"
```

---

## Notes

1. **Referral Code Generation**: Each user gets a unique 8-character alphanumeric referral code automatically generated when they sign up.

2. **Referral Code Validation**: When a user signs up with a referral code, the system validates that the code exists and belongs to an active user.

3. **Circular References**: The system prevents users from referring themselves or creating circular referral chains.

4. **Multiple Referrals**: A user can refer multiple people, and each referral creates a separate relationship.

5. **Commission Calculation**: Commissions are calculated based on the `final_credited_amount` for top-ups, which includes any discounts or cashback from recharge offers.

6. **Earning Credit**: Earnings must be manually credited to wallet using the credit earnings API. This allows for review and approval if needed.

7. **Settings Management**: Only one active referral setting can exist at a time. Creating new settings deactivates previous ones.

---

## Support

For issues or questions, please contact the development team.


