> ## Documentation Index
> Fetch the complete documentation index at: https://ihub.learnille.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Withdrawal System Architecture

> Migrated from the previous Learnille internal documentation hub

## Overview

The Withdrawal System enables instructors and consultants to transfer their earned funds from their Learnille wallet to their external bank accounts. The system is designed with security, compliance, and reliability as core priorities.

## Key Participants

| Role | Description |
| - | - |
| **User** | Instructor or consultant requesting a withdrawal |
| **Admin** | Platform administrator who reviews and approves withdrawal requests |
| **Payment Gateway** | External service (Flutterwave) that executes bank transfers |

## High-Level Flow

```mermaid theme={null}
flowchart TD
    A[User Requests Withdrawal] --> B{Eligibility Check}
    B -->|Pass| C[OTP Verification]
    B -->|Fail| X[Request Rejected]
    C --> D[Pending Admin Review]
    D --> E{Admin Decision}
    E -->|Approve| F[Funds Deducted from Wallet]
    E -->|Reject| G[User Notified - No Action]
    F --> H[Payout Queued]
    H --> I[Payment Gateway Processing]
    I --> J{Transfer Result}
    J -->|Success| K[Withdrawal Complete]
    J -->|Failure| L[Funds Refunded to Wallet]
    K --> M[User Notified]
    L --> M
```

## Withdrawal Lifecycle

### Status Flow

| Status | Description |
| - | - |
| `PENDING` | User initiated request, awaiting OTP verification |
| `PENDING_APPROVAL` | OTP verified, awaiting admin review |
| `APPROVED` | Admin approved, funds deducted from wallet |
| `PROCESSING` | Payout in progress with payment gateway |
| `COMPLETED` | Funds successfully transferred to bank |
| `REJECTED` | Admin rejected the request |
| `FAILED` | Payment gateway transfer failed or was cancelled; the amount is returned to the wallet |
| `CANCELLED` | User cancelled the request |

A withdrawal only leaves `PROCESSING` when Flutterwave reports a final transfer status: `SUCCESSFUL` → `COMPLETED`, `FAILED` or `CANCELLED` → `FAILED`. `NEW` and `PENDING` are ignored until the transfer finishes.

## Process Details

### 1. Withdrawal Request Initiation

When a user requests a withdrawal, the system performs the following validations:

* **Balance Check**: User must have sufficient available balance
* **KYC Verification**: User must have completed identity verification
* **Method Verification**: Selected bank account must be verified
* **Concurrent Limit**: Maximum 3 pending withdrawals allowed per user
* **System Status**: Global withdrawals must not be suspended

### 2. Two-Factor Approval

For security, withdrawals require OTP verification:

1. System sends a 6-digit code to user's registered email
2. User enters the code to confirm the withdrawal
3. Code expires after a configurable time period

### 3. Admin Review

All withdrawal requests go through manual admin review to:

* Verify the request legitimacy
* Check for suspicious activity patterns
* Ensure compliance with platform policies
* Prevent fraud and money laundering

Admins can:

* **Approve**: Proceed with payout
* **Reject**: Decline with reason
* **Request Info**: Ask user for additional verification

### 4. Payout Processing

Once approved, the system:

1. Deducts funds from user's wallet (creates ledger entry)
2. Queues the payout job for processing
3. Initiates transfer via payment gateway

**Transfer Types:**

* **Instant**: Immediate transfer to bank
* **Scheduled**: Delayed transfer (default: 3-hour delay for fraud prevention)

### 5. Bank Transfer

The payment gateway (Flutterwave) handles:

* Currency conversion (if applicable)
* Bank routing and transfer
* Status updates via webhooks (`POST /payment/flutterwave-webhook`). v3 sends `transfer.completed`; v4 sends other `transfer.*` events signed with `flutterwave-signature`. Both are handled, and the result is read from the transfer's `status`.

### 6. Completion & Notifications

Users receive notifications at key stages:

* Request submitted
* Admin approval/rejection
* Transfer completed/failed

## Security Measures

| Measure | Purpose |
| - | - |
| OTP Verification | Confirms user identity for each withdrawal |
| Admin Review | Human oversight to prevent fraud |
| Scheduled Delays | Window to detect and stop suspicious transfers |
| KYC Requirement | Ensures user identity is verified |
| Concurrent Limits | Prevents bulk fraudulent withdrawals |
| Suspension System | Emergency halt capability for all withdrawals |

## Withdrawal Methods

Users must set up and verify a withdrawal method before requesting funds:

1. **Add Bank Account**: User provides bank details (account number, bank name)
2. **Verification**: System creates a recipient profile with payment gateway
3. **Activation**: Once verified, the method can be used for withdrawals

Supported account types vary by country and payment gateway capabilities.

## System Configuration

| Setting | Description | Default |
| - | - | - |
| Transfer Type | Instant or Scheduled | Scheduled |
| Delay Duration | Hours before scheduled payout | 3 hours |
| Max Concurrent | Maximum pending withdrawals per user | 3 |
| Global Suspension | Emergency stop for all withdrawals | Off |

## Integration Points

```mermaid theme={null}
flowchart LR
    subgraph Learnille Platform
        WS[Withdrawal Service]
        WL[Wallet Service]
        NT[Notification Service]
        AU[Audit Service]
    end
    
    subgraph External
        FW[Flutterwave API]
        BK[User's Bank]
    end
    
    WS --> WL
    WS --> NT
    WS --> AU
    WS --> FW
    FW --> BK
    FW -->|Webhooks| WS
```

## Monitoring & Audit

All withdrawal activities are logged for:

* Compliance and regulatory requirements
* Dispute resolution
* Fraud detection and pattern analysis
* System performance monitoring

Key metrics tracked:

* Average processing time
* Success/failure rates
* Admin review turnaround time
* Gateway response times

## Error Handling

| Scenario | System Response |
| - | - |
| Insufficient balance | Request rejected with clear message |
| Gateway timeout | Retry with exponential backoff |
| Transfer failure | Funds automatically refunded to wallet |
| Stale withdrawals | Every 6 hours, withdrawals in `PROCESSING` for over 30 minutes are checked with Flutterwave. Only final statuses are applied; a transfer still `NEW` or `PENDING` is left alone so it can't be failed (and refunded) while it may still pay out |

## Future Considerations

* Additional payment gateways for broader coverage
* Automated approval for low-risk, verified users
* Real-time balance updates during processing
* Multi-currency wallet support


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.