# Withdrawal System Documentation

## Overview
Users can withdraw funds from their wallet to Alipay. The withdrawal process requires admin approval before funds are transferred.

## Withdrawal Flow

### User Side
1. User clicks "Withdraw" button on dashboard
2. Modal opens with withdrawal form
3. User enters:
   - Amount (minimum ¥10.00, maximum: wallet balance)
   - Alipay Name
   - Alipay Account Number
   - Additional Notes (optional)
4. User submits request
5. System creates pending withdrawal transaction
6. User receives confirmation with reference number
7. User waits for admin approval
8. User receives notification when approved/rejected

### Admin Side
1. Admin sees pending withdrawal count in sidebar
2. Admin navigates to "Withdrawals" section
3. Admin views all withdrawal requests with:
   - Reference number
   - User name
   - Amount
   - Alipay details (name, account, notes)
   - Date
   - Status
4. Admin can:
   - Approve withdrawal → Funds deducted from user wallet, user notified
   - Reject withdrawal → Request marked as failed, user notified
5. Admin can filter by: Pending, Completed, Rejected

## Key Features

### No Immediate Deduction
- Funds are NOT deducted when user submits request
- Funds only deducted when admin approves
- This prevents funds being locked if admin rejects

### Admin Notifications
- Admin receives notification when new withdrawal request submitted
- Notification includes user name, amount, and reference

## User Notifications

### Withdrawal Request Submitted
When user submits withdrawal request:
- **In-app**: None (only admin notified)
- **Email**: Confirmation with amount, reference, and Alipay details
- **SMS**: "Your withdrawal request of ¥X (Ref: WTH-XXX) has been submitted. You'll be notified once reviewed."

### Withdrawal Approved
When admin approves withdrawal:
- **In-app**: Notification in dashboard
- **Email**: "Your withdrawal request of ¥X (Ref: WTH-XXX) has been approved and processed. The funds will be transferred to your Alipay account shortly."
- **SMS**: "Your withdrawal of ¥X (Ref: WTH-XXX) has been approved."

### Withdrawal Rejected
When admin rejects withdrawal:
- **In-app**: Notification in dashboard
- **Email**: "Your withdrawal request of ¥X (Ref: WTH-XXX) has been rejected. Please contact support for more information."
- **SMS**: "Your withdrawal of ¥X (Ref: WTH-XXX) has been rejected. Contact support."

### Exchange Order Completed
When admin marks exchange order as completed:
- **In-app**: Notification in dashboard
- **Email**: "Your exchange order #XXX has been completed. ¥X has been added to your wallet."
- **SMS**: "Your exchange order #XXX is complete. ¥X added to your wallet."

### Wallet Top-Up Successful
When Paystack payment succeeds:
- **In-app**: None (redirect with success message)
- **Email**: "Your wallet top-up of ¥X has been completed successfully. Your new balance is ¥X."
- **SMS**: "Top-up of ¥X successful. New balance: ¥X"

### Balance Validation
- System checks if user has sufficient balance before creating request
- Maximum withdrawal amount = current wallet balance

## Database Structure

### wallet_transactions Table
Withdrawal records have:
- `type`: 'withdraw'
- `status`: 'pending', 'completed', or 'failed'
- `payment_method`: 'alipay'
- `reference`: 'WTH-XXXXX'
- `notes`: JSON with Alipay details
  ```json
  {
    "alipay_name": "John Doe",
    "alipay_account": "123456789",
    "additional_notes": "Optional notes"
  }
  ```

## API Endpoints

### POST /wallet/withdraw
Creates withdrawal request (user)

**Request:**
```json
{
  "amount": 100.00,
  "alipay_name": "John Doe",
  "alipay_account": "123456789",
  "notes": "Optional additional information"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Withdrawal request submitted successfully.",
  "transaction": {
    "id": 1,
    "reference": "WTH-65F8A9B2D",
    "amount": "100.00",
    "status": "pending"
  }
}
```

### POST /admin/withdrawals/{id}/approve
Approves withdrawal request (admin only)

**Actions:**
1. Deducts amount from user wallet
2. Updates transaction status to 'completed'
3. Sends notification to user

### POST /admin/withdrawals/{id}/reject
Rejects withdrawal request (admin only)

**Actions:**
1. Updates transaction status to 'failed'
2. Sends notification to user
3. No funds deducted

## Admin Dashboard Integration

### Sidebar Navigation
- "Withdrawals" menu item
- Shows pending count badge
- Positioned between Orders and Members

### Withdrawals Section
- Table view with all withdrawal details
- Filter tabs: Pending, Completed, Rejected
- Action buttons: Approve, Reject (for pending only)
- Empty state when no requests

### Statistics
- `pending_withdrawals` count in dashboard stats
- Displayed in sidebar badge

## User Dashboard Integration

### Withdraw Modal
- Opens when "Withdraw" button clicked
- Form fields:
  - Amount input (with min/max validation)
  - Alipay Name input
  - Alipay Account input
  - Additional Notes textarea (optional)
- Shows available balance
- Submit button with loading state

### Wallet Display
- Shows current balance in CNY (¥)
- Balance updates after admin approval

## Testing

### Test Withdrawal Request (User)
1. Login as user with wallet balance
2. Click "Withdraw" button
3. Enter amount (e.g., 50.00)
4. Enter Alipay name and account
5. Submit request
6. Verify success message with reference
7. Check database: `SELECT * FROM wallet_transactions WHERE type='withdraw' AND status='pending';`

### Test Approval (Admin)
1. Login as admin
2. Navigate to Withdrawals section
3. See pending request
4. Click "Approve"
5. Confirm action
6. Verify:
   - Transaction status = 'completed'
   - User wallet balance decreased
   - User received notification
7. Check database: `SELECT * FROM wallet_transactions WHERE id=X;`

### Test Rejection (Admin)
1. Login as admin
2. Navigate to Withdrawals section
3. See pending request
4. Click "Reject"
5. Confirm action
6. Verify:
   - Transaction status = 'failed'
   - User wallet balance unchanged
   - User received notification

## Security Considerations

- CSRF protection on all forms
- Authentication required for withdrawal requests
- Admin-only access to approve/reject
- Balance validation before request creation
- Unique reference numbers
- User can only withdraw their own funds
- Funds not deducted until admin approval

## Future Enhancements

1. **Automated Processing**
   - Alipay API integration
   - Automatic transfer on approval
   - Real-time status updates

2. **Withdrawal Limits**
   - Daily/weekly withdrawal limits
   - Minimum holding period
   - Verification requirements

3. **Enhanced Notifications**
   - SMS alerts for large withdrawals
   - Email receipts with transaction details
   - Push notifications

4. **Audit Trail**
   - Admin action logging
   - Approval/rejection reasons
   - Transaction history export

5. **Batch Processing**
   - Approve multiple withdrawals at once
   - Scheduled processing times
   - Bulk export for accounting
