# Referral Module Documentation

## Overview

The referral module provides functionality for contractors to generate referral codes and earn rewards when other contractors join using their codes. This module is restricted to contractors only and includes Stripe integration for coupon rewards.

## Features

- **Generate Referral Codes**: Contractors can generate unique referral codes
- **Join with Referral**: Contractors can join using another contractor's referral code
- **Referral Statistics**: Track referral counts and referred contractors
- **Stripe Integration**: Automatic coupon generation when referral threshold is reached
- **Email Notifications**: Automatic email notifications for referral activities

## API Endpoints

### 1. Generate Referral Code

- **POST** `/api/referel/generate`
- **Authentication**: Required (Contractor only)
- **Description**: Generates a unique referral code for the authenticated contractor

### 2. Join with Referral Code

- **POST** `/api/referel/join`
- **Authentication**: Required (Contractor only)
- **Body**: `{ "code": "REF123ABC" }`
- **Description**: Allows a contractor to join using another contractor's referral code

### 3. Get Referral Statistics

- **GET** `/api/referel/stats/:id?`
- **Authentication**: Required
- **Description**: Returns referral statistics for a contractor (defaults to authenticated user)

## Environment Variables

The following environment variables are required:

```env
# Required
STRIPE_SECRET_KEY=sk_test_...          # Stripe secret key for coupon creation
APP_BASE_URL=https://example.com       # Base URL for building referral links

# Email Configuration (Required for notifications)
MAIL_HOST=smtp.gmail.com               # SMTP host
MAIL_PORT=587                          # SMTP port
MAIL_USERNAME=your-email@gmail.com     # SMTP username
MAIL_PASSWORD=your-app-password        # SMTP password

# Optional (with defaults)
REFERRAL_THRESHOLD=5                   # Number of referrals required for coupon (default: 5)
REFERRAL_COUPON_AMOUNT=1000           # Coupon amount in cents (optional, defaults to 10% off)
REFERRAL_COUPON_DURATION=once         # Coupon duration: once|repeating|forever (default: once)
```

## Database Schema

The module uses the following fields on the Contractor model:

```javascript
{
  referel: {
    code: String,                    // Unique referral code
    lastGeneratedAt: Date,          // When code was last generated
    totalReferrals: Number,         // Total number of successful referrals
    referredList: [{                // Array of referred contractors
      referredId: ObjectId,
      joinedAt: Date
    }],
    referredBy: ObjectId,           // Who referred this contractor
    referredAt: Date,               // When this contractor was referred
    couponId: String,               // Stripe coupon ID
    promoCode: String,              // Stripe promotion code
    couponIssuedAt: Date            // When coupon was issued
  }
}
```

## Security Features

- **Authentication Required**: All endpoints require valid JWT tokens
- **Contractor Only**: Only contractors can generate and use referral codes
- **Self-Referral Prevention**: Contractors cannot use their own referral codes
- **Duplicate Prevention**: Contractors cannot use multiple referral codes
- **Atomic Updates**: Database operations are atomic to prevent race conditions

## Error Handling

The module provides comprehensive error handling with appropriate HTTP status codes:

- **400**: Bad Request (invalid data, self-referral, etc.)
- **401**: Unauthorized (missing or invalid token)
- **403**: Forbidden (non-contractor access)
- **404**: Not Found (contractor not found)
- **409**: Conflict (duplicate referral usage)
- **500**: Internal Server Error

## Testing

Use the test file at `test/referral-test.js` for manual testing. The file includes:

- Test case examples
- Required environment variables
- Sample requests for all endpoints

## Email Notifications

The referral module automatically sends email notifications for:

### Referral Code Generation

- **Triggered**: When a contractor generates a referral code
- **Recipient**: The contractor who generated the code
- **Content**: Referral code, sharing link, and instructions

### Referral Join Notification

- **Triggered**: When someone joins using a referral code
- **Recipient**: The contractor whose code was used
- **Content**: Joiner details, referral progress, and next steps

## Usage Examples

### Generate Referral Code

```bash
curl -X POST http://localhost:5050/api/referel/generate \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json"
```

### Join with Referral Code

```bash
curl -X POST http://localhost:5050/api/referel/join \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"code": "REF123ABC"}'
```

### Get Referral Stats

```bash
curl -X GET http://localhost:5050/api/referel/stats \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

## Notes

- The module is designed to be non-invasive and only adds referral functionality
- Stripe integration is optional - if Stripe fails, referral creation still succeeds
- All database operations use atomic updates to prevent race conditions
- The module includes comprehensive logging for debugging and monitoring
