# Investor Area Architecture - ECM Platform

## Status: ✅ COMPLETE

Investor member area frontend architecture has been successfully implemented for the ECM MT5 Investment Platform.

## Overview
Production-grade investor dashboard with API-first architecture, responsive design, and finance-safe data display.

## Architecture Components

### 1. Investor Layout (`src/layouts/InvestorLayout.vue`)
**Purpose:** Main layout wrapper for all investor pages.

**Features:**
- Desktop sidebar navigation (64px width)
- Mobile hamburger menu with full-screen overlay
- User profile section with initials
- Dark mode toggle
- Notifications bell with unread indicator
- Page title auto-detection
- Logout functionality
- Responsive breakpoints (md: 768px)

**Navigation Items:**
- Dashboard
- Balance
- Profit History
- Distributions
- Trades
- Referrals
- Safety Fund
- Settings

---

### 2. Investor Pages

#### Dashboard (`src/pages/investor/Dashboard.vue`)
**Purpose:** Main investor dashboard with overview.

**Components:**
- 4 summary cards (Balance, Profit, Units, Safety Fund Share)
- 2 chart placeholders (Profit History, Balance Trend)
- Recent distributions table
- Loading/error states

**API Call:** `investorService.getDashboard()`

**Data Displayed:**
- Current balance
- Total profit
- Units count
- Safety fund share
- Recent distributions (date, profit, share, units)

---

#### Balance Overview (`src/pages/investor/Balance.vue`)
**Purpose:** Balance and transaction history.

**Components:**
- 3 summary cards (Current Balance, Available Balance, Pending Withdrawals)
- Balance history chart placeholder
- Transactions table

**API Call:** `investorService.getBalance()`

**Data Displayed:**
- Current balance
- Available balance
- Pending withdrawals
- Transaction history (date, type, amount, status)

---

#### Profit History (`src/pages/investor/ProfitHistory.vue`)
**Purpose:** Profit tracking and history.

**Components:**
- 3 summary cards (Total Profit, This Month, This Week)
- Profit trend chart placeholder
- Profit history table with pagination

**API Call:** `investorService.getProfitHistory(page)`

**Data Displayed:**
- Total profit
- Monthly profit
- Weekly profit
- Profit history (date, profit, units, share)

---

#### Daily Settlements (`src/pages/investor/Distributions.vue`)
**Purpose:** Distribution/settlement history.

**Components:**
- 3 summary cards (Total Distributed, Total Received, Count)
- Distribution trend chart placeholder
- Distributions table with pagination

**API Call:** `investorService.getDistributions(page)`

**Data Displayed:**
- Total distributed amount
- Total received amount
- Distribution count
- Distribution history (date, total profit, share, units, status)

---

#### MT5 Trade History (`src/pages/investor/Trades.vue`)
**Purpose:** MT5 trading history with filters.

**Components:**
- 4 summary cards (Total Trades, Winning, Losing, Total PnL)
- Filter section (date range, status)
- Trades table with pagination

**API Call:** `investorService.getTrades(page, filters)`

**Data Displayed:**
- Total trades count
- Winning trades count
- Losing trades count
- Total PnL
- Trade history (ticket, symbol, type, volume, prices, profit, close time)

**Filters:**
- Date from
- Date to
- Status (win/loss)

---

#### Referral Dashboard (`src/pages/investor/Referrals.vue`)
**Purpose:** Referral program management.

**Components:**
- 4 summary cards (Total Referrals, Active, Commissions, This Month)
- Referral link with copy button
- Commission trend chart placeholder
- Referrals table with pagination

**API Call:** `investorService.getReferrals(page)`

**Data Displayed:**
- Total referrals count
- Active referrals count
- Total commissions earned
- Monthly commissions
- Referral list (name, email, joined date, profit, commission, status)

---

#### Safety Fund Summary (`src/pages/investor/SafetyFund.vue`)
**Purpose:** Safety fund contribution tracking.

**Components:**
- 3 summary cards (Total Fund, Your Contribution, Allocation Rate)
- Safety fund growth chart placeholder
- Contributions table with pagination

**API Call:** `investorService.getSafetyFund(page)`

**Data Displayed:**
- Total safety fund balance
- Your contribution amount
- Allocation rate (20%)
- Contribution history (date, profit, contribution, total fund after)

---

#### Account Settings (`src/pages/investor/Settings.vue`)
**Purpose:** Account management and settings.

**Components:**
- Profile settings form (name, email, phone)
- Change password form
- MT5 account connection section

**API Calls:**
- `investorService.getSettings()`
- `investorService.updateProfile(profile)`
- `investorService.changePassword(password)`

**Features:**
- Profile editing
- Password change with confirmation
- MT5 account connection/update

---

#### Notifications (`src/pages/investor/Notifications.vue`)
**Purpose:** Notification center.

**Components:**
- Notification list with read/unread states
- Mark all as read button
- Load more pagination

**API Calls:**
- `investorService.getNotifications()`
- `investorService.markNotificationAsRead(id)`
- `investorService.markAllNotificationsAsRead()`
- `investorService.loadMoreNotifications()`

**Data Displayed:**
- Notification list (icon, title, message, created at, read status)
- Unread indicator
- Timestamp formatting

---

### 3. Reusable Components

#### FinanceTable (`src/components/finance/FinanceTable.vue`)
**Purpose:** Reusable table for finance data.

**Features:**
- Column configuration
- Format support (currency, number, percentage, date)
- Loading state
- Empty state
- Pagination integration
- Responsive overflow

**Props:**
- `columns` - Array of column definitions
- `data` - Array of data rows
- `loading` - Boolean loading state
- `currentPage` - Current page number
- `totalPages` - Total pages
- `totalItems` - Total items count
- `showPagination` - Boolean to show/hide pagination

**Usage:**
```vue
<FinanceTable
  :columns="columns"
  :data="data"
  :loading="loading"
  :current-page="currentPage"
  :total-pages="totalPages"
  :total-items="totalItems"
  @page-change="onPageChange"
/>
```

---

#### ChartPlaceholder (`src/components/finance/ChartPlaceholder.vue`)
**Purpose:** Placeholder for future chart implementation.

**Features:**
- Custom message
- Icon display
- Centered layout

**Usage:**
```vue
<ChartPlaceholder message="Profit chart coming soon" />
```

---

### 4. API Consumption Architecture

**Pattern:**
All pages follow a consistent API consumption pattern:

```javascript
const loading = ref(true)
const error = ref(null)
const data = ref([])

async function loadData(page = 1) {
  loading.value = true
  error.value = null
  
  try {
    // API call
    const response = await investorService.getEndpoint(page)
    data.value = response.data
  } catch (err) {
    error.value = 'Failed to load data'
    console.error('Load error:', err)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
```

**Features:**
- Loading states
- Error handling
- Pagination support
- Empty state handling

---

### 5. Loading/Error State Architecture

**Loading State:**
- Centralized BaseLoading component
- Spinner display
- Full-height centering

**Error State:**
- Red background alert
- Error message display
- Try again capability (future)

**Empty State:**
- EmptyState component
- Icon, title, message
- Context-aware messages

---

### 6. Pagination Strategy

**Implementation:**
- Pagination component reused from UI components
- Page state managed in parent component
- Page change events emitted to parent
- Total items/pages displayed

**Usage:**
```javascript
function onPageChange(page) {
  currentPage.value = page
  loadData(page)
}
```

---

### 7. Responsive Strategy

**Breakpoints:**
- Mobile: < 768px
- Desktop: ≥ 768px

**Layout Changes:**
- Sidebar: Hidden on mobile, full-width overlay on open
- Cards: 1 column mobile, 2-4 columns desktop
- Tables: Horizontal scroll on mobile
- Header: Simplified on mobile

**Mobile Menu:**
- Full-screen overlay
- Close button
- Click-outside to close (future)
- Smooth transitions

---

### 8. Realtime-Ready Architecture

**Prepared for:**
- WebSocket integration
- Live data updates
- Push notifications
- Real-time chart updates

**Architecture:**
- Reactive state management with Pinia
- Component reactivity
- Easy integration points for WebSocket
- Notification system ready

**Future Implementation:**
```javascript
// WebSocket integration
const socket = new WebSocket('ws://api/v1/investor/updates')
socket.onmessage = (event) => {
  const data = JSON.parse(event.data)
  // Update reactive state
}
```

---

### 9. Finance-Safe Display Strategy

**CRITICAL:**
Frontend NEVER calculates finance values. All values come from backend APIs.

**Display Only:**
- Currency values (formatted, not calculated)
- Percentages (formatted, not calculated)
- Ratios (displayed, not calculated)
- Allocations (displayed, not calculated)

**Formatting:**
- Use `useFormat` composable
- `formatCurrency()` - Currency display
- `formatNumber()` - Number display
- `formatPercentage()` - Percentage display
- `formatDate()` - Date display

**Example:**
```javascript
// ❌ WRONG - calculating in frontend
const profit = totalRevenue - totalCost

// ✅ CORRECT - displaying backend value
const profit = data.profit // from API
```

---

### 10. Component Hierarchy

```
InvestorLayout
├── Sidebar
│   ├── Logo
│   ├── Navigation Items
│   └── User Section
├── Header
│   ├── Page Title
│   ├── Dark Mode Toggle
│   └── Notifications Bell
└── Page Content
    ├── Finance Cards (summary)
    ├── Chart Placeholders
    ├── Finance Tables
    ├── Filters
    └── Forms
```

---

### 11. UX Strategy

**Dashboard First:**
- Clear overview on login
- Key metrics visible immediately
- Quick access to detailed views

**Consistent Navigation:**
- Sidebar always visible on desktop
- Active state indication
- Logical grouping

**Progressive Disclosure:**
- Summary cards first
- Detailed tables below
- Drill-down capability

**Feedback:**
- Loading states on all async operations
- Error messages with context
- Success confirmations on actions

---

### 12. Security Considerations

**Route Protection:**
- All routes protected by `investorGuard`
- Authentication required
- Role verification

**Data Protection:**
- No sensitive data in localStorage (except auth token)
- API calls use HTTPS
- Sanctum token authentication

**Input Validation:**
- Form validation on submission
- Backend validation required
- Sanitization on display

---

## File Structure

```
src/
├── layouts/
│   └── InvestorLayout.vue
├── pages/
│   └── investor/
│       ├── Dashboard.vue
│       ├── Balance.vue
│       ├── ProfitHistory.vue
│       ├── Distributions.vue
│       ├── Trades.vue
│       ├── Referrals.vue
│       ├── SafetyFund.vue
│       ├── Settings.vue
│       └── Notifications.vue
├── components/
│   ├── finance/
│   │   ├── FinanceCard.vue
│   │   ├── FinanceTable.vue
│   │   └── ChartPlaceholder.vue
│   ├── common/
│   │   ├── BaseLoading.vue
│   │   ├── BaseCard.vue
│   │   ├── BaseInput.vue
│   │   └── BaseButton.vue
│   └── ui/
│       ├── Pagination.vue
│       └── EmptyState.vue
├── stores/
│   └── investor.js
├── services/
│   └── investor.service.js
└── router/
    └── index.js
```

---

## API Integration

**Available Endpoints (to be implemented):**
- `GET /api/v1/investor/dashboard` - Dashboard data
- `GET /api/v1/investor/balance` - Balance overview
- `GET /api/v1/investor/profit-history` - Profit history
- `GET /api/v1/investor/distributions` - Distributions
- `GET /api/v1/investor/trades` - Trade history
- `GET /api/v1/investor/referrals` - Referrals
- `GET /api/v1/investor/safety-fund` - Safety fund
- `GET /api/v1/investor/settings` - Settings
- `PUT /api/v1/investor/settings` - Update settings
- `POST /api/v1/investor/change-password` - Change password
- `GET /api/v1/investor/notifications` - Notifications
- `PUT /api/v1/investor/notifications/:id/read` - Mark as read

---

## Next Steps

Investor area architecture is complete and ready for:
1. Backend API integration (replace mock data)
2. Chart library integration (Chart.js, ECharts, etc.)
3. WebSocket integration for real-time updates
4. Form validation implementation
5. Notification system implementation
6. PDF export for statements
7. Advanced filtering and sorting
8. Data export functionality

---

## Testing Checklist

- [ ] All pages load correctly
- [ ] Loading states display properly
- [ ] Error states display properly
- [ ] Empty states display properly
- [ ] Pagination works
- [ ] Filters work (trades page)
- [ ] Mobile menu works
- [ ] Dark mode works
- [ ] Navigation works
- [ ] Forms submit correctly
- [ ] Data displays correctly
- [ ] Currency formatting works
- [ ] Date formatting works
- [ ] Responsive design tested
- [ ] Cross-browser testing
