# INDI-VOUCH Backend API - Postman Collection

This directory contains Postman collection and environment files for testing the INDI-VOUCH Backend APIs.

## Files Included

1. **`INDI-VOUCH-Backend-APIs.postman_collection.json`** - Complete API collection
2. **`INDI-VOUCH-Environment.postman_environment.json`** - Environment variables
3. **`README.md`** - This documentation file

## How to Import

### Import Collection
1. Open Postman
2. Click **Import** button
3. Select **Upload Files** tab
4. Choose `INDI-VOUCH-Backend-APIs.postman_collection.json`
5. Click **Import**

### Import Environment
1. In Postman, click the **Environment** dropdown (top right)
2. Click **Import**
3. Select `INDI-VOUCH-Environment.postman_environment.json`
4. Click **Import**
5. Select the **INDI-VOUCH Environment** from the dropdown

## Collection Structure

### 📁 **System APIs**
- **Welcome Message** - `GET /`
- **Health Check** - `GET /health`
- **Database Health Check** - `GET /db-health`
- **Get Database Tables** - `GET /api/tables`
- **Get All Users (Legacy)** - `GET /api/users`

### 🔐 **User Authentication**
- **User Registration** - `POST /api/user/auth/register`
- **User Login (Username)** - `POST /api/user/auth/login`
- **User Login (Email)** - `POST /api/user/auth/login`
- **User Login (Mobile)** - `POST /api/user/auth/login`

### 👤 **User Profile Management**
- **Get User Profile** - `GET /api/user/profile` (requires auth)
- **Update User Profile** - `PUT /api/user/profile` (requires auth)
- **Update Profile (with Password)** - `PUT /api/user/profile` (includes password change)

### 💰 **Commission & Wallet Management**
- **Get Wallet Balances** - `GET /api/commission/wallet/balance` (requires auth)
- **Get Specific Wallet Balance** - `GET /api/commission/wallet/balance/:type` (commission/repurchase)
- **Get Commission History** - `GET /api/commission/history` (requires auth)
- **Get Commission Wallet Transactions** - `GET /api/commission/transactions/commission` (requires auth)
- **Get Repurchase Wallet Transactions** - `GET /api/commission/transactions/repurchase` (requires auth)
- **Get All Wallet Transactions** - `GET /api/commission/transactions` (requires auth)
- **Admin - Manual Commission Payment** - `POST /api/commission/admin/pay` (admin only)
- **Admin - Manual Wallet Deduction** - `POST /api/commission/admin/deduct` (admin only)

### 🛒 **Purchase & Stock Management**
- **Get Available Packages** - `GET /api/purchase/packages`
- **Get Package Details** - `GET /api/purchase/packages/:id`
- **Get Repurchase Wallet Balance** - `GET /api/purchase/wallet/repurchase` (requires auth)
- **Purchase Package** - `POST /api/purchase/buy` (requires auth)
- **Get Purchase History** - `GET /api/purchase/history` (requires auth)
- **Admin - Get All Purchases** - `GET /api/purchase/admin/all` (admin only)

### ⚙️ **Settings & Configuration**
- **Get Flag Value** - `GET /api/setting/flag/:flag_name`
- **Get Multiple Flag Values** - `POST /api/setting/flags`
- **Admin - Update Flag Value** - `PUT /api/setting/flag/:flag_name` (admin only)

### 👥 **Team Management**
- **Get Direct Team Members** - `GET /api/team/direct-members` (requires auth)
- **Get Team Member Details** - `GET /api/team/member/:memberId` (requires auth)
- **Get Team Statistics** - `GET /api/team/stats` (requires auth)

### 🔧 **Debug & Development**
- **Debug Commission Setup** - `GET /api/purchase/debug/commission-setup/:userId`
- **Get Stock Table Structure** - `GET /api/debug/stock`
- **Get F_Payment Table Structure** - `GET /api/debug/f_payment`
- **Get Voucher Packages Table Structure** - `GET /api/debug/voucher_packages`

### 🔑 **Admin Authentication**
- **Admin Login** - `POST /api/admin/auth/login` (not implemented)

### ❌ **Error Testing**
- **Invalid Login Credentials** - Test error handling
- **Access Profile Without Token** - Test authentication
- **Register with Duplicate Username** - Test validation
- **Register with Short Password** - Test password validation

## Environment Variables

| Variable | Description | Default Value |
|----------|-------------|---------------|
| `base_url` | API base URL | `http://localhost:3000` |
| `auth_token` | JWT token (auto-set after login) | `` |
| `admin_token` | Admin JWT token (set after admin login) | `` |
| `test_username` | Test username for examples | `john_doe` |
| `test_email` | Test email for examples | `john@example.com` |
| `test_mobile` | Test mobile for examples | `9876543210` |
| `test_password` | Test password for examples | `secure123` |
| `test_sponsor_username` | Test sponsor for MLM registration | `root_sponsor` |
| `test_user_id` | Test user ID (auto-set after registration) | `` |
| `api_version` | API version | `v1` |

## Usage Instructions

### 1. **Setup**
- Make sure your backend server is running on `http://localhost:3000`
- Import both collection and environment files
- Select the INDI-VOUCH Environment

### 2. **Testing Complete MLM System**
1. **Setup Database**: Ensure settings table exists with commission flags
2. **Create Root Sponsor**: First create a root sponsor user manually or via database
3. **Set Sponsor Username**: Update `test_sponsor_username` environment variable
4. **Register Users**: Run "MLM User Registration" request
5. **Check Commission**: Registration response includes commission processing info
6. **Test Wallets**: Use wallet balance APIs to verify commission payments
7. **Login**: Run any of the login requests (Username/Email/Mobile)
8. **Access Profile**: The auth token is automatically saved, so you can now access protected endpoints

### 3. **Testing Commission System**
1. **Check Settings**: Use "Get Flag Value" to verify commission settings
2. **Register with Commission**: Use "Test Registration with Commission"
3. **Check Wallet Balances**: Use "Get Wallet Balances" to see commission and repurchase wallets
4. **View Commission History**: Use "Get Commission History" to see transaction details
5. **Admin Functions**: Use admin APIs to manually pay/deduct commissions

### 4. **Automatic Token Management**
- Login requests automatically save the JWT token to `auth_token` variable
- Protected endpoints automatically use the saved token
- No need to manually copy/paste tokens

### 5. **Test Scripts Included**
Each request includes test scripts that:
- Verify response status codes
- Check response structure
- Validate data types
- Save tokens automatically
- Test error scenarios

## Sample Test Flow

### Complete MLM User Journey
1. **Check Settings**: Run "Get Flag Value" to verify commission settings
2. **Register**: Create new user with "MLM User Registration"
3. **Verify Commission**: Check registration response for commission info
4. **Login**: Authenticate with "User Login by Username"
5. **Check Wallets**: Get wallet balances with "Get Wallet Balances"
6. **View History**: Check commission history with "Get Commission History"
7. **Profile**: Get user details with "Get User Profile"
8. **Update**: Modify profile with "Update User Profile"

### Commission Testing
1. **Flag Values**: Test "Get Flag Value" and "Get Multiple Flag Values"
2. **Registration Commission**: Use "Test Registration with Commission"
3. **Wallet Balances**: Test both commission and repurchase wallet endpoints
4. **Admin Functions**: Test manual commission payment and deduction (requires admin login)

### Purchase & Stock Testing
1. **Available Packages**: Use "Get Available Packages" to see all voucher packages
2. **Package Details**: Use "Get Package Details" to check specific package info
3. **Repurchase Balance**: Use "Get Repurchase Wallet Balance" to check buying power
4. **Purchase Flow**: Use "Purchase Package" to buy packages with repurchase wallet
5. **Purchase History**: Use "Get Purchase History" to see user's stock records
6. **Admin Monitoring**: Use "Admin - Get All Purchases" to monitor all transactions

### Error Testing
1. **Invalid Credentials**: Test with wrong password
2. **Missing Auth**: Try accessing profile without token
3. **Invalid Sponsor**: Try registering with non-existent sponsor
4. **Missing Fields**: Test registration with missing required fields
5. **Weak Password**: Test password validation
6. **Insufficient Balance**: Try purchasing with low repurchase wallet balance
7. **Invalid Package**: Try purchasing non-existent package

## Request Examples

### MLM Registration Request
```json
{
  "name": "John Doe",
  "mobile": "9876543210",
  "email": "john@example.com",
  "sponsor_username": "root_sponsor",
  "password": "secure123"
}
```

**Note:** Username is automatically generated in format `IN` + 6 random digits (e.g., `IN123456`, `IN789012`). No need to provide username in the request.

### Login Request
```json
{
  "username": "IN123456",
  "password": "secure123"
}
```

### Profile Update Request
```json
{
  "name": "John Smith",
  "email": "johnsmith@example.com",
  "mobile": "9876543211"
}
```

### Profile Update with Password Request
```json
{
  "name": "John Smith",
  "email": "johnsmith@example.com",
  "mobile": "9876543211",
  "password": "newpassword123"
}
```

### Purchase Package Request
```json
{
  "package_id": 1,
  "quantity": 2
}
```

## Response Examples

### Successful Login Response
```json
{
  "success": true,
  "message": "Login successful",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": 1,
      "name": "John Doe",
      "username": "john_doe",
      "email": "john@example.com",
      "mobile": "9876543210",
      "status": 1
    }
  }
}
```

### Purchase Success Response
```json
{
  "success": true,
  "message": "Package purchased successfully",
  "data": {
    "stock_id": 123,
    "package_name": "Premium Package",
    "total_cost": 1000,
    "remaining_balance": 500,
    "purchase_commission_paid": true,
    "purchase_commission_amount": 100,
    "future_commissions_created": true,
    "commission_entries_count": 10,
    "user_status_updated": true
  }
}
```

### Transaction History Response
```json
{
  "success": true,
  "message": "Commission Wallet transactions retrieved successfully",
  "data": {
    "user_id": 123,
    "wallet_type": "commission",
    "current_balance": 1500.50,
    "transactions": [
      {
        "id": 456,
        "amount": 100,
        "details": "Referal Purches Reward",
        "status": "completed",
        "date2": "2025-11-02T05:22:00.000Z"
      }
    ],
    "pagination": {
      "total_count": 25,
      "current_page": 1,
      "per_page": 20,
      "has_next": true
    }
  }
}
```

### Team Members Response
```json
{
  "success": true,
  "message": "Direct team members retrieved successfully",
  "data": {
    "user_id": 123,
    "total_direct_members": 5,
    "members": [
      {
        "id": 456,
        "name": "John Doe",
        "username": "IN123456",
        "mobile": "*****43210",
        "joining_date": "2025-11-01T10:30:00.000Z",
        "joining_date_formatted": "01/11/2025, 04:00:00 PM",
        "current_status": 1,
        "status_text": "Active",
        "member_type": "Paid Member"
      },
      {
        "id": 457,
        "name": "Jane Smith",
        "username": "IN789012",
        "mobile": "*****98765",
        "joining_date": "2025-11-02T08:15:00.000Z",
        "joining_date_formatted": "02/11/2025, 01:45:00 PM",
        "current_status": 0,
        "status_text": "Inactive",
        "member_type": "Free Member"
      }
    ],
    "pagination": {
      "total_count": 5,
      "current_page": 1,
      "per_page": 20,
      "has_next": false
    }
  }
}
```

### Team Statistics Response
```json
{
  "success": true,
  "message": "Team statistics retrieved successfully",
  "data": {
    "user_id": 123,
    "statistics": {
      "total_direct_members": 10,
      "active_direct_members": 6,
      "free_direct_members": 4,
      "inactive_direct_members": 4,
      "recent_joinings_30_days": 3
    }
  }
}
```

**Note:** 
- `active_direct_members` = Paid members (status = 1)
- `free_direct_members` = Free members (status = 0)  
- `inactive_direct_members` = Same as `free_direct_members` (for backward compatibility)

### Error Response
```json
{
  "success": false,
  "message": "Invalid credentials"
}
```

## Customization

### Change Base URL
1. Go to Environment settings
2. Update `base_url` variable
3. Save changes

### Add New Requests
1. Right-click on appropriate folder
2. Select "Add Request"
3. Configure method, URL, headers, and body
4. Add test scripts if needed

## Troubleshooting

### Common Issues

1. **Connection Refused**
   - Ensure backend server is running
   - Check if port 3000 is correct
   - Verify base_url in environment

2. **Database Errors**
   - Check if MySQL/MariaDB is running
   - Verify database exists
   - Check database credentials in .env

3. **Authentication Errors**
   - Ensure you've logged in first
   - Check if token is saved in environment
   - Verify JWT_SECRET is set in backend

4. **Validation Errors**
   - Check required fields
   - Verify password length (min 6 characters)
   - Ensure unique username/email/mobile

## Support

For issues or questions:
1. Check the main API documentation: `API_DOCUMENTATION.md`
2. Review server logs for detailed error messages
3. Verify environment variables are set correctly
4. Test individual endpoints to isolate issues

---

**Happy Testing! 🚀**
