# Chain Wallet & Transaction API Flow

## Overview
This document explains how the chain wallet and transaction system works, including the complete flow from order payment to withdrawal.

---

## System Architecture

### Money Flow:
```
Customer Payment ($300)
    ↓
Stripe Payment Intent (in Superadmin's account)
    ↓
Order Payment Confirmed
    ↓
Transaction Created:
  - Gross: $300
  - Stripe Fee: ~$8.70 (2.9% + $0.30)
  - Platform Fee: $30 (10% if profit_percentage = 10)
  - Net to Chain: $261.30
    ↓
Chain Balance Updated: +$261.30
    ↓
Chain Can Withdraw via Stripe Connect
```

---

## Complete API Flow

### 1. **Order Payment Flow** (Automatic)

#### Step 1.1: Customer Creates Order
```http
POST /users/orders
Authorization: Bearer <customer_token>
Content-Type: application/json

{
  "items": [
    {"listing_id": 49, "quantity": 2}
  ],
  "voucher_code": null
}
```

**Response:**
```json
{
  "order_id": 21,
  "status": "IN_PROCESS",
  "total_amount": 300.0,
  "final_amount": 300.0,
  ...
}
```

#### Step 1.2: Customer Creates Payment Intent
```http
POST /users/orders/21/payment-intent
Authorization: Bearer <customer_token>
Content-Type: application/json

{
  "chain_code": "CHAIN001"
}
```

**Response:**
```json
{
  "payment_intent_id": "pi_1234567890",
  "client_secret": "pi_1234567890_secret_xxx",
  "amount": 30000,
  "currency": "usd",
  "status": "requires_payment_method"
}
```

#### Step 1.3: Customer Confirms Payment (Frontend uses Stripe.js)
```http
POST /users/orders/21/confirm-payment
Authorization: Bearer <customer_token>
Content-Type: application/json

{
  "payment_intent_id": "pi_1234567890"
}
```

**What Happens Automatically:**
1. ✅ Order status → `COMPLETED`
2. ✅ Payment status → `SUCCEEDED`
3. ✅ **Transaction Created** (if order has store with chain):
   - Transaction Type: `SALE`
   - Gross Amount: $300.00
   - Stripe Fee: $8.70 (calculated)
   - Platform Fee: $30.00 (10% of gross)
   - Net Amount: $261.30
   - Status: `COMPLETED`
4. ✅ **Chain Balance Updated**: +$261.30

**Response:**
```json
{
  "order_id": 21,
  "status": "COMPLETED",
  "payment_status": "SUCCEEDED",
  ...
}
```

---

### 2. **View Chain Balance** (Admin)

```http
GET /admin/transactions/balance
Authorization: Bearer <admin_token>
```

**Response:**
```json
{
  "chain_id": 1,
  "chain_name": "Walmart",
  "balance": 261.30,
  "pending_balance": 0.0,
  "available_balance": 261.30,
  "total_earned": 261.30,
  "total_withdrawn": 0.0,
  "total_refunded": 0.0
}
```

---

### 3. **View Transactions** (Admin)

```http
GET /admin/transactions/transactions?skip=0&limit=100
Authorization: Bearer <admin_token>
```

**Optional Filters:**
- `transaction_type`: `SALE`, `WITHDRAWAL`, `REFUND`, `FEE`
- `status`: `PENDING`, `COMPLETED`, `FAILED`, `CANCELLED`

**Response:**
```json
{
  "transactions": [
    {
      "transaction_id": 1,
      "chain_id": 1,
      "chain_name": "Walmart",
      "order_id": 21,
      "transaction_type": "SALE",
      "status": "COMPLETED",
      "gross_amount": 300.0,
      "stripe_fee": 8.70,
      "platform_fee": 30.0,
      "net_amount": 261.30,
      "stripe_payment_intent_id": "pi_1234567890",
      "description": "Sale from order #21",
      "created_at": "2025-01-16T10:00:00Z",
      "completed_at": "2025-01-16T10:00:01Z"
    }
  ],
  "total": 1,
  "skip": 0,
  "limit": 100
}
```

---

### 4. **Initiate Withdrawal** (Admin)

**Prerequisites:**
- Chain must have `stripe_account_id` set up (Stripe Connect account)
- Available balance must be sufficient

```http
POST /admin/transactions/withdraw
Authorization: Bearer <admin_token>
Content-Type: application/json

{
  "amount": 200.0,
  "description": "Monthly withdrawal"
}
```

**What Happens:**
1. ✅ Validates available balance
2. ✅ Creates Stripe Transfer to chain's Connect account
3. ✅ Creates withdrawal transaction:
   - Transaction Type: `WITHDRAWAL`
   - Gross Amount: $200.00
   - Net Amount: -$200.00 (negative = deduction)
   - Status: `COMPLETED`
4. ✅ **Chain Balance Updated**: -$200.00

**Response:**
```json
{
  "transaction_id": 2,
  "chain_id": 1,
  "amount": 200.0,
  "status": "COMPLETED",
  "stripe_transfer_id": "tr_1234567890",
  "message": "Withdrawal of $200.00 initiated successfully. Transfer ID: tr_1234567890"
}
```

**Updated Balance:**
```json
{
  "chain_id": 1,
  "balance": 61.30,  // 261.30 - 200.00
  "available_balance": 61.30,
  "total_withdrawn": 200.0
}
```

---

### 5. **Order Refund Flow** (Admin)

```http
POST /admin/orders/21/refund
Authorization: Bearer <admin_token>
Content-Type: application/json

{
  "reason": "Customer requested refund"
}
```

**What Happens Automatically:**
1. ✅ Stripe refund created (full amount back to customer)
2. ✅ Order status → `REFUNDED`
3. ✅ **Refund Transaction Created**:
   - Transaction Type: `REFUND`
   - Gross Amount: $300.00 (refund amount)
   - Net Amount: -$261.30 (proportional to original net)
   - Status: `COMPLETED`
4. ✅ **Chain Balance Updated**: -$261.30

**Response:**
```json
{
  "order_id": 21,
  "status": "REFUNDED",
  "refund_id": "re_1234567890",
  "refund_amount": 300.0,
  "refund_amount_cents": 30000,
  "message": "Order 21 has been successfully refunded. Amount: $300.00"
}
```

**Updated Balance:**
```json
{
  "chain_id": 1,
  "balance": 0.0,  // 261.30 - 261.30
  "total_refunded": 261.30
}
```

---

## Superadmin APIs (View All Chains)

### 6. **View All Chains Balances** (Superadmin)

```http
GET /admin/transactions/superadmin/balances
Authorization: Bearer <superadmin_token>
```

**Response:**
```json
[
  {
    "chain_id": 1,
    "chain_name": "Walmart",
    "balance": 261.30,
    "available_balance": 261.30,
    "total_earned": 261.30,
    "total_withdrawn": 0.0,
    "total_refunded": 0.0
  },
  {
    "chain_id": 2,
    "chain_name": "Target",
    "balance": 500.50,
    "available_balance": 500.50,
    "total_earned": 1000.0,
    "total_withdrawn": 499.50,
    "total_refunded": 0.0
  }
]
```

### 7. **View All Transactions** (Superadmin)

```http
GET /admin/transactions/superadmin/transactions?skip=0&limit=100&chain_id=1
Authorization: Bearer <superadmin_token>
```

**Optional Filters:**
- `chain_id`: Filter by specific chain
- `transaction_type`: `SALE`, `WITHDRAWAL`, `REFUND`, `FEE`
- `status`: `PENDING`, `COMPLETED`, `FAILED`, `CANCELLED`

**Response:**
```json
{
  "transactions": [
    {
      "transaction_id": 1,
      "chain_id": 1,
      "chain_name": "Walmart",
      "order_id": 21,
      "transaction_type": "SALE",
      "status": "COMPLETED",
      "gross_amount": 300.0,
      "stripe_fee": 8.70,
      "platform_fee": 30.0,
      "net_amount": 261.30,
      ...
    },
    {
      "transaction_id": 2,
      "chain_id": 1,
      "chain_name": "Walmart",
      "order_id": null,
      "transaction_type": "WITHDRAWAL",
      "status": "COMPLETED",
      "gross_amount": 200.0,
      "net_amount": -200.0,
      "stripe_transfer_id": "tr_1234567890",
      ...
    }
  ],
  "total": 2,
  "skip": 0,
  "limit": 100
}
```

---

## Fee Calculation Examples

### Example 1: $300 Sale with 10% Platform Fee

```
Gross Amount:        $300.00
Stripe Fee:          $  8.70  (2.9% + $0.30)
Platform Fee (10%):  $ 30.00  (10% of gross)
─────────────────────────────────
Net to Chain:        $261.30
```

### Example 2: $100 Sale with 10% Platform Fee

```
Gross Amount:        $100.00
Stripe Fee:          $  3.20  (2.9% + $0.30)
Platform Fee (10%):  $ 10.00  (10% of gross)
─────────────────────────────────
Net to Chain:        $ 86.80
```

### Example 3: $1000 Sale with 10% Platform Fee

```
Gross Amount:        $1000.00
Stripe Fee:          $  29.30  (2.9% + $0.30)
Platform Fee (10%):  $ 100.00  (10% of gross)
─────────────────────────────────
Net to Chain:        $ 870.70
```

---

## Transaction Types

| Type | Description | Net Amount Sign |
|------|-------------|-----------------|
| `SALE` | Money earned from order payment | Positive (+) |
| `WITHDRAWAL` | Money withdrawn to chain's Stripe Connect | Negative (-) |
| `REFUND` | Money refunded (deducted from balance) | Negative (-) |
| `FEE` | Additional fees (future use) | Negative (-) |

---

## Transaction Statuses

| Status | Description |
|--------|-------------|
| `PENDING` | Transaction is being processed |
| `COMPLETED` | Transaction completed successfully |
| `FAILED` | Transaction failed |
| `CANCELLED` | Transaction was cancelled |

---

## Important Notes

### 1. **Automatic Transaction Creation**
- Transactions are **automatically created** when:
  - ✅ Order payment is confirmed → `SALE` transaction
  - ✅ Order is refunded → `REFUND` transaction
- No manual API calls needed for these

### 2. **Balance Updates**
- Chain balance is **automatically updated** when transactions are created
- Balance = Sum of all completed transaction net amounts

### 3. **Stripe Connect Setup**
- Chains need `stripe_account_id` configured before they can withdraw
- This is the Stripe Connect account ID for the chain
- Set via database or admin panel (future feature)

### 4. **Profit Percentage**
- Default: 10% (platform takes 10%, chain gets 90%)
- Can be customized per chain via `profit_percentage` field
- Example: If `profit_percentage = 15`, platform takes 15%, chain gets 85%

### 5. **Stripe Fees**
- Calculated automatically: 2.9% + $0.30 per transaction
- Deducted from gross amount before calculating platform fee
- Chain receives: Gross - Stripe Fee - Platform Fee

### 6. **Refund Calculation**
- Refunds are proportional to the original sale
- If order was $300 and refunded $150, chain loses 50% of original net amount
- Original net: $261.30 → Refund net: -$130.65

---

## Error Scenarios

### Insufficient Balance for Withdrawal
```json
{
  "detail": "Insufficient balance. Available: $61.30, Requested: $200.00"
}
```

### No Stripe Connect Account
```json
{
  "detail": "Chain does not have a Stripe Connect account. Please set up Stripe Connect first."
}
```

### Order Already Refunded
```json
{
  "detail": "Order has already been refunded"
}
```

---

## Database Schema

### Chains Table
- `chain_id` (PK)
- `chain_name`
- `chain_code`
- `profit_percentage` (default: 10.0)
- `stripe_account_id` (nullable, for Stripe Connect)
- `balance` (default: 0.0)

### Chain Transactions Table
- `transaction_id` (PK)
- `chain_id` (FK)
- `order_id` (FK, nullable)
- `transaction_type` (SALE, WITHDRAWAL, REFUND, FEE)
- `status` (PENDING, COMPLETED, FAILED, CANCELLED)
- `gross_amount`
- `stripe_fee`
- `platform_fee`
- `net_amount`
- `stripe_payment_intent_id` (nullable)
- `stripe_transfer_id` (nullable)
- `stripe_account_id` (nullable)
- `description` (nullable)
- `notes` (nullable)
- `created_at`
- `updated_at`
- `completed_at` (nullable)

---

## Complete Flow Diagram

```
┌─────────────┐
│   Customer  │
└──────┬──────┘
       │ 1. Create Order
       ▼
┌─────────────┐
│   Order     │ (Status: IN_PROCESS)
└──────┬──────┘
       │ 2. Create Payment Intent
       ▼
┌─────────────┐
│   Stripe    │ (Payment Intent Created)
└──────┬──────┘
       │ 3. Confirm Payment
       ▼
┌─────────────┐
│   Order     │ (Status: COMPLETED)
└──────┬──────┘
       │ 4. Auto: Create Transaction
       ▼
┌─────────────┐
│ Transaction │ (Type: SALE, Net: +$261.30)
└──────┬──────┘
       │ 5. Auto: Update Chain Balance
       ▼
┌─────────────┐
│    Chain    │ (Balance: +$261.30)
└──────┬──────┘
       │ 6. Admin: View Balance
       ▼
┌─────────────┐
│   Admin     │ (GET /admin/transactions/balance)
└──────┬──────┘
       │ 7. Admin: Initiate Withdrawal
       ▼
┌─────────────┐
│   Stripe    │ (Transfer to Chain Connect Account)
└──────┬──────┘
       │ 8. Auto: Create Withdrawal Transaction
       ▼
┌─────────────┐
│ Transaction │ (Type: WITHDRAWAL, Net: -$200.00)
└──────┬──────┘
       │ 9. Auto: Update Chain Balance
       ▼
┌─────────────┐
│    Chain    │ (Balance: $61.30)
└─────────────┘
```

---

## API Endpoints Summary

### Admin Endpoints (Chain-specific)
- `GET /admin/transactions/balance` - Get chain wallet balance
- `GET /admin/transactions/transactions` - Get chain transactions
- `POST /admin/transactions/withdraw` - Initiate withdrawal

### Superadmin Endpoints (All chains)
- `GET /admin/transactions/superadmin/balances` - Get all chains balances
- `GET /admin/transactions/superadmin/transactions` - Get all transactions

### Automatic (No API calls needed)
- Transaction creation on order payment
- Transaction creation on order refund
- Balance updates

---

## Testing the Flow

### 1. Test Order Payment
```bash
# Create order
curl -X POST 'http://127.0.0.1:8000/users/orders' \
  -H 'Authorization: Bearer <customer_token>' \
  -d '{"items": [{"listing_id": 49, "quantity": 2}]}'

# Create payment intent
curl -X POST 'http://127.0.0.1:8000/users/orders/21/payment-intent' \
  -H 'Authorization: Bearer <customer_token>' \
  -d '{"chain_code": "CHAIN001"}'

# Confirm payment (after Stripe.js payment)
curl -X POST 'http://127.0.0.1:8000/users/orders/21/confirm-payment' \
  -H 'Authorization: Bearer <customer_token>' \
  -d '{"payment_intent_id": "pi_xxx"}'
```

### 2. Test View Balance
```bash
curl -X GET 'http://127.0.0.1:8000/admin/transactions/balance' \
  -H 'Authorization: Bearer <admin_token>'
```

### 3. Test View Transactions
```bash
curl -X GET 'http://127.0.0.1:8000/admin/transactions/transactions?skip=0&limit=100' \
  -H 'Authorization: Bearer <admin_token>'
```

### 4. Test Withdrawal
```bash
curl -X POST 'http://127.0.0.1:8000/admin/transactions/withdraw' \
  -H 'Authorization: Bearer <admin_token>' \
  -d '{"amount": 100.0, "description": "Test withdrawal"}'
```

---

This system provides complete transparency and control over chain finances with automatic transaction tracking and balance management.
