# 🚀 TimCash API - Exemples d'Utilisation

## 📋 Guide Pratique d'Utilisation de l'API

Ce guide présente des exemples concrets d'utilisation de l'API TimCash avec toutes les nouvelles fonctionnalités implémentées.

## 🔐 Authentification

### 1. Connexion et Obtention des Tokens

```bash
# Connexion utilisateur
curl -X POST "http://localhost:8000/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@timcash.com",
    "password": "password"
  }'
```

**Réponse :**
```json
{
  "user": {
    "id": "user-12345678",
    "email": "user@timcash.com",
    "first_name": "Demo",
    "last_name": "User",
    "role": "user"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 86400
}
```

### 2. Renouvellement du Token

```bash
curl -X POST "http://localhost:8000/auth/refresh" \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }'
```

### 3. Déconnexion

```bash
curl -X POST "http://localhost:8000/auth/logout" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }'
```

## 💰 Gestion des Portefeuilles

### 1. Consultation du Portefeuille

```bash
curl -X GET "http://localhost:8000/wallet" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

**Réponse :**
```json
{
  "id": "wallet-87654321",
  "user_id": "user-12345678",
  "balance": 5000.0,
  "currency": "USD",
  "is_active": true,
  "created_at": "2024-09-20T10:00:00Z",
  "updated_at": "2024-09-20T15:30:00Z"
}
```

### 2. Rechargement du Portefeuille via CinetPay

```bash
curl -X POST "http://localhost:8000/wallet/reload" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 1000.0,
    "payment_method": "cinetpay"
  }'
```

**Réponse :**
```json
{
  "transaction_id": "reload-abc123",
  "payment_url": "https://checkout.cinetpay.com/payment/abc123",
  "status": "pending"
}
```

### 3. Retrait du Portefeuille

```bash
curl -X POST "http://localhost:8000/wallet/withdraw" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 500.0,
    "destination": "Compte Bancaire - BNP Paribas"
  }'
```

**Réponse :**
```json
{
  "transaction_id": "txn-def456",
  "amount": 500.0,
  "status": "pending",
  "message": "Withdrawal request submitted successfully"
}
```

### 4. Transfert entre Utilisateurs

```bash
curl -X POST "http://localhost:8000/wallet/transfer" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "recipient_email": "friend@example.com",
    "amount": 200.0,
    "description": "Remboursement restaurant"
  }'
```

**Réponse :**
```json
{
  "transfer_id": "transfer-ghi789",
  "amount": 200.0,
  "fee": 2.0,
  "recipient": "friend@example.com",
  "status": "completed"
}
```

### 5. Historique des Transactions

```bash
curl -X GET "http://localhost:8000/wallet/history?limit=10&offset=0" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

**Réponse :**
```json
{
  "transactions": [
    {
      "id": "txn-123",
      "type": "transfer",
      "amount": -202.0,
      "description": "Transfer to friend@example.com",
      "status": "completed",
      "created_at": "2024-09-20T16:00:00Z"
    }
  ],
  "total": 25,
  "limit": 10,
  "offset": 0
}
```

## 🏦 Système de Prêts

### 1. Demande de Prêt avec Alimentation Compte Stock

```bash
curl -X POST "http://localhost:8000/wallet-loans/create" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 10000.0,
    "duration": 24,
    "purpose": "Achat véhicule professionnel"
  }'
```

**Réponse :**
```json
{
  "id": "loan-xyz789",
  "user_id": "user-12345678",
  "amount": 10000.0,
  "interest_rate": 8.5,
  "duration": 24,
  "status": "approved",
  "monthly_payment": 456.78,
  "total_repayment": 10962.72,
  "remaining_balance": 10962.72,
  "next_payment_date": "2024-10-20T16:00:00Z",
  "created_at": "2024-09-20T16:00:00Z"
}
```

### 2. Consultation des Prêts Utilisateur

```bash
curl -X GET "http://localhost:8000/wallet-loans/user-loans" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### 3. Recherche de Prêts avec Filtres

```bash
curl -X GET "http://localhost:8000/wallet-loans/search?status=active&min_amount=5000&max_amount=50000" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### 4. Filtrage par Dates

```bash
curl -X GET "http://localhost:8000/wallet-loans/filter?start_date=2024-01-01T00:00:00Z&end_date=2024-12-31T23:59:59Z" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

## 🔄 Callback CinetPay

### Simulation de Callback de Paiement

```bash
curl -X POST "http://localhost:8000/wallet-paiements/callback" \
  -H "Content-Type: application/json" \
  -d '{
    "transaction_id": "reload-abc123",
    "status": "ACCEPTED",
    "amount": 1000.0,
    "reference": "CP_20240920_001",
    "signature": "demo_signature_hash"
  }'
```

**Réponse :**
```json
{
  "status": "success",
  "message": "Callback processed successfully"
}
```

## 👨‍💼 Administration

### 1. Connexion Admin

```bash
curl -X POST "http://localhost:8000/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@timcash.com",
    "password": "admin123"
  }'
```

### 2. Consultation du Compte Stock Admin

```bash
curl -X GET "http://localhost:8000/admin/stock" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

**Réponse :**
```json
{
  "id": "admin-stock-001",
  "balance": 85000.0,
  "total_credits": 14.0,
  "total_debits": 15000.0,
  "total_commissions": 14.0,
  "last_updated": "2024-09-20T16:30:00Z"
}
```

### 3. Transactions du Compte Stock Admin

```bash
curl -X GET "http://localhost:8000/wallet-admins?limit=20&offset=0" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

**Réponse :**
```json
[
  {
    "id": "admin_txn-abc123",
    "type": "loan_disbursement",
    "amount": 10000.0,
    "description": "Loan disbursement - Achat véhicule professionnel",
    "reference_id": "loan-xyz789",
    "balance_before": 95000.0,
    "balance_after": 85000.0,
    "created_at": "2024-09-20T16:00:00Z"
  },
  {
    "id": "admin_txn-def456",
    "type": "commission",
    "amount": 2.0,
    "description": "Transfer commission - 200.0",
    "reference_id": "transfer-ghi789",
    "balance_before": 85000.0,
    "balance_after": 85002.0,
    "created_at": "2024-09-20T16:05:00Z"
  }
]
```

### 4. Recherche des Transactions Admin

```bash
curl -X GET "http://localhost:8000/wallet-admins/search?transaction_type=commission&start_date=2024-09-01T00:00:00Z" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

### 5. Statistiques Détaillées

```bash
curl -X GET "http://localhost:8000/admin/stats" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

**Réponse :**
```json
{
  "users": {
    "total": 3,
    "active": 3,
    "blocked": 0
  },
  "wallets": {
    "total": 3,
    "total_balance": 15200.0,
    "active": 3
  },
  "loans": {
    "total": 2,
    "active": 2,
    "total_amount": 15000.0,
    "total_repayments": 0.0
  },
  "transactions": {
    "total": 8,
    "pending": 1,
    "completed": 7
  },
  "admin_stock": {
    "balance": 85014.0,
    "total_credits": 14.0,
    "total_debits": 15000.0,
    "total_commissions": 14.0
  }
}
```

### 6. Rapports Financiers

```bash
curl -X GET "http://localhost:8000/admin/reports" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

**Réponse :**
```json
{
  "monthly_revenue": 14.0,
  "admin_balance": 85014.0,
  "total_loans_disbursed": 15000.0,
  "total_commissions_earned": 14.0,
  "report_date": "2024-09-20T16:45:00Z"
}
```

### 7. Historique des Virements CinetPay

```bash
curl -X GET "http://localhost:8000/wallet-payouts" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

## 🧪 Exemples avec Python

### Client Python Simple

```python
import requests
import json

class TimCashAPI:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url
        self.token = None
        self.refresh_token = None
    
    def login(self, email, password):
        """Connexion et récupération des tokens"""
        response = requests.post(
            f"{self.base_url}/auth/login",
            json={"email": email, "password": password}
        )
        if response.status_code == 200:
            data = response.json()
            self.token = data["token"]
            self.refresh_token = data["refresh_token"]
            return data["user"]
        else:
            raise Exception(f"Login failed: {response.text}")
    
    def get_headers(self):
        """Headers avec authentification"""
        return {"Authorization": f"Bearer {self.token}"}
    
    def get_wallet(self):
        """Consultation du portefeuille"""
        response = requests.get(
            f"{self.base_url}/wallet",
            headers=self.get_headers()
        )
        return response.json()
    
    def create_loan(self, amount, duration, purpose):
        """Création d'un prêt"""
        response = requests.post(
            f"{self.base_url}/wallet-loans/create",
            headers=self.get_headers(),
            json={
                "amount": amount,
                "duration": duration,
                "purpose": purpose
            }
        )
        return response.json()
    
    def transfer_funds(self, recipient_email, amount, description=None):
        """Transfert de fonds"""
        response = requests.post(
            f"{self.base_url}/wallet/transfer",
            headers=self.get_headers(),
            json={
                "recipient_email": recipient_email,
                "amount": amount,
                "description": description
            }
        )
        return response.json()

# Utilisation
api = TimCashAPI()

# Connexion
user = api.login("user@timcash.com", "password")
print(f"Connecté en tant que: {user['first_name']} {user['last_name']}")

# Consultation du portefeuille
wallet = api.get_wallet()
print(f"Solde actuel: {wallet['balance']} {wallet['currency']}")

# Création d'un prêt
loan = api.create_loan(5000, 12, "Équipement informatique")
print(f"Prêt créé: {loan['id']} - Montant: {loan['amount']}")

# Transfert
transfer = api.transfer_funds("friend@example.com", 100, "Remboursement")
print(f"Transfert effectué: {transfer['transfer_id']}")
```

## 📊 Exemple avec JavaScript/Node.js

```javascript
const axios = require('axios');

class TimCashAPI {
    constructor(baseURL = 'http://localhost:8000') {
        this.baseURL = baseURL;
        this.token = null;
        this.refreshToken = null;
    }

    async login(email, password) {
        try {
            const response = await axios.post(`${this.baseURL}/auth/login`, {
                email,
                password
            });
            
            this.token = response.data.token;
            this.refreshToken = response.data.refresh_token;
            
            return response.data.user;
        } catch (error) {
            throw new Error(`Login failed: ${error.response.data.detail}`);
        }
    }

    getHeaders() {
        return {
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
        };
    }

    async getWallet() {
        const response = await axios.get(`${this.baseURL}/wallet`, {
            headers: this.getHeaders()
        });
        return response.data;
    }

    async reloadWallet(amount) {
        const response = await axios.post(
            `${this.baseURL}/wallet/reload`,
            { amount, payment_method: 'cinetpay' },
            { headers: this.getHeaders() }
        );
        return response.data;
    }

    async getAdminStats() {
        const response = await axios.get(`${this.baseURL}/admin/stats`, {
            headers: this.getHeaders()
        });
        return response.data;
    }
}

// Utilisation
(async () => {
    const api = new TimCashAPI();
    
    // Connexion admin
    const admin = await api.login('admin@timcash.com', 'password');
    console.log(`Admin connecté: ${admin.first_name}`);
    
    // Statistiques
    const stats = await api.getAdminStats();
    console.log('Statistiques:', JSON.stringify(stats, null, 2));
})();
```

## 🔧 Tests avec Postman

### Collection Postman

Importez cette collection dans Postman pour tester rapidement l'API :

```json
{
  "info": {
    "name": "TimCash API v1.0",
    "description": "Collection complète pour tester l'API TimCash"
  },
  "variable": [
    {
      "key": "base_url",
      "value": "http://localhost:8000"
    },
    {
      "key": "token",
      "value": ""
    }
  ],
  "item": [
    {
      "name": "Auth - Login",
      "request": {
        "method": "POST",
        "url": "{{base_url}}/auth/login",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"email\": \"user@timcash.com\",\n  \"password\": \"password\"\n}"
        }
      }
    },
    {
      "name": "Wallet - Get Balance",
      "request": {
        "method": "GET",
        "url": "{{base_url}}/wallet",
        "header": [
          {
            "key": "Authorization",
            "value": "Bearer {{token}}"
          }
        ]
      }
    }
  ]
}
```

---

**Version** : 0.1.0  
**Dernière Mise à Jour** : Septembre 2024  
**Statut** : ✅ Prêt pour l'Utilisation
