# Realtime Architecture - ECM Platform

## Status: ✅ ARCHITECTURE COMPLETE

Production-grade realtime infrastructure for the ECM MT5 Investment Platform.

---

## Architecture Overview

### Design Philosophy
- **Display Only** - Realtime is for visualization and notifications only
- **No Finance Logic** - Never calculate or modify finance values in realtime layer
- **Backend Authority** - Backend remains settlement, finance, and reconciliation authority
- **Queue-Safe** - Broadcasting respects queue idempotency and retry safety
- **Secure Channels** - Role-protected private channels with authorization

### Tech Stack

**Backend:**
- Laravel Broadcasting
- Laravel Echo
- Pusher / Soketi / Laravel WebSockets
- Redis
- Queue broadcasting

**Frontend:**
- Vue 3 Composition API
- Pinia (State Management)
- Laravel Echo (WebSocket client)
- Pusher.js

---

## Backend Architecture

### 1. Broadcasting Configuration

**File:** `config/broadcasting.php`

**Features:**
- Default broadcaster: Pusher (configurable)
- Soketi support for self-hosted WebSockets
- Redis support for scalable pub/sub
- Cluster configuration for Pusher
- TLS/SSL support

**Environment Variables:**
```bash
BROADCAST_DRIVER=pusher
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_ID=
PUSHER_APP_CLUSTER=mt1
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https

# Soketi (alternative)
SOKETI_APP_KEY=
SOKETI_APP_SECRET=
SOKETI_APP_ID=
SOKETI_HOST=127.0.0.1
SOKETI_PORT=6001
SOKETI_SCHEME=http
```

---

### 2. Event Architecture

**Events Created:**

#### 1. SettlementCompleted
- **Channels:** `private-investor.{id}`, `admin.settlements`
- **Event Name:** `settlement.completed`
- **Data:** Distribution object
- **Purpose:** Notify investor and admin of completed settlement

#### 2. ProfitCredited
- **Channels:** `private-investor.{id}`
- **Event Name:** `profit.credited`
- **Data:** ProfitLog object
- **Purpose:** Notify investor of profit credit

#### 3. Mt5SyncCompleted
- **Channels:** `admin.mt5`
- **Event Name:** `mt5.sync.completed`
- **Data:** Sync data
- **Purpose:** Notify admin of successful MT5 sync

#### 4. Mt5SyncFailed
- **Channels:** `admin.mt5`, `admin.system`
- **Event Name:** `mt5.sync.failed`
- **Data:** Sync data + error
- **Purpose:** Alert admin of MT5 sync failure

#### 5. ReconciliationFailed
- **Channels:** `admin.reconciliation`, `admin.system`
- **Event Name:** `reconciliation.failed`
- **Data:** Distribution ID + mismatch
- **Purpose:** Alert admin of reconciliation mismatch

#### 6. SettlementFailed
- **Channels:** `admin.settlements`, `admin.system`
- **Event Name:** `settlement.failed`
- **Data:** Distribution ID + error
- **Purpose:** Alert admin of settlement failure

#### 7. QueueHealthChanged
- **Channels:** `admin.queue`, `admin.system`
- **Event Name:** `queue.health.changed`
- **Data:** Queue status
- **Purpose:** Notify admin of queue health changes

#### 8. InvestorBalanceUpdated
- **Channels:** `private-investor.{id}`
- **Event Name:** `investor.balance.updated`
- **Data:** Investor ID + balance
- **Purpose:** Notify investor of balance update

#### 9. SafetyFundUpdated
- **Channels:** `admin.safety-fund`
- **Event Name:** `safety-fund.updated`
- **Data:** Safety fund object
- **Purpose:** Notify admin of safety fund changes

#### 10. ReferralCommissionCreated
- **Channels:** `private-investor.{id}`
- **Event Name:** `referral.commission.created`
- **Data:** Commission object
- **Purpose:** Notify referrer of commission earned

#### 11. AdminAlertCreated
- **Channels:** `admin.system`
- **Event Name:** `admin.alert.created`
- **Data:** Alert object
- **Purpose:** Broadcast admin alerts

---

### 3. Channel Authorization

**File:** `routes/channels.php`

**Channels:**

#### Investor Channels (Private)
```php
Broadcast::channel('investor.{id}', function ($user, $id) {
    $investor = Investor::where('user_id', $user->id)->first();
    return $investor && $investor->id === (int) $id;
});
```

#### Admin Channels (Public, Role-Protected)
```php
Broadcast::channel('admin.system', function ($user) {
    return $user->role === 'admin';
});
```

---

## Frontend Architecture

### 1. Echo Integration

**File:** `frontend/src/plugins/echo.js`

### 2. Realtime Composable

**File:** `frontend/src/composables/useRealtime.js`

### 3. Realtime Store

**File:** `frontend/src/stores/realtime.js`

### 4. Notification Components

- `frontend/src/components/realtime/NotificationCenter.vue`
- `frontend/src/components/realtime/AlertBanner.vue`

---

## Files Created

### Backend:
- `config/broadcasting.php` - Updated
- `routes/channels.php` - Updated
- `app/Events/SettlementCompleted.php`
- `app/Events/ProfitCredited.php`
- `app/Events/Mt5SyncCompleted.php`
- `app/Events/Mt5SyncFailed.php`
- `app/Events/ReconciliationFailed.php`
- `app/Events/SettlementFailed.php`
- `app/Events/QueueHealthChanged.php`
- `app/Events/InvestorBalanceUpdated.php`
- `app/Events/SafetyFundUpdated.php`
- `app/Events/ReferralCommissionCreated.php`
- `app/Events/AdminAlertCreated.php`

### Frontend:
- `src/plugins/echo.js`
- `src/composables/useRealtime.js`
- `src/stores/realtime.js`
- `src/composables/useRealtimeNotifications.js`
- `src/components/realtime/NotificationCenter.vue`
- `src/components/realtime/AlertBanner.vue`

---

**Architecture Complete:** Realtime infrastructure is ready for live updates and notifications.
