# Real-time Monitoring

STA Connector provides real-time monitoring capabilities through the Admin Portal and Admin API.

## Admin Portal

The React-based Admin Portal provides a real-time dashboard for monitoring file processing, system health, and metrics.

### Features

- **Health Dashboard** - Real-time system status overview
- **File Monitoring** - Live view of file processing with filters
- **Metrics Visualization** - Charts for throughput, latency, and queue depth
- **Configuration Editor** - Modify settings without restart
- **Route Management** - Enable/disable routes with toggles
- **Dark/Light Mode** - User preference support

### Accessing the Portal

```bash
# With Docker
open http://localhost:3000

# Development mode
cd admin-portal
npm run dev
open http://localhost:5173
```

## Dashboard Overview

The main dashboard displays:

```
┌─────────────────────────────────────────────────────────────┐
│  STA Connector Admin                              [Dark]    │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  System Health: ● Healthy                                   │
│                                                             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │
│  │ Inbound  │  │ Outbound │  │ Database │  │   STA    │    │
│  │    ●     │  │    ●     │  │    ●     │  │    ●     │    │
│  │  Active  │  │  Active  │  │Connected │  │   OK     │    │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘    │
│                                                             │
│  Files Processed Today                                      │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ ▂▃▅▇█▇▅▃▂▁▂▃▄▅▆▇█▇▆▅▄▃▂▁                           │   │
│  │ 00:00        06:00        12:00        18:00   24:00│   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  ┌─────────────────────┐  ┌─────────────────────────────┐  │
│  │ Recent Activity     │  │ System Metrics              │  │
│  │ • SPI file uploaded │  │ Uptime: 3d 4h 25m          │  │
│  │ • CCS file received │  │ Memory: 256 MB             │  │
│  │ • DICT file sent    │  │ Queue Depth: 5             │  │
│  └─────────────────────┘  └─────────────────────────────┘  │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

## Polling for Updates

The Admin Portal polls the Admin API at regular intervals to fetch updated data.

### Health Status

```javascript
// Polls /admin/health every 30 seconds
async function fetchHealth() {
  const response = await fetch('/api/admin/health', {
    headers: {
      'Authorization': `Basic ${btoa('admin:password')}`
    }
  });
  return response.json();
}
```

### Metrics Updates

```javascript
// Polls /admin/metrics every 5 seconds
async function fetchMetrics() {
  const response = await fetch('/api/admin/metrics', {
    headers: {
      'Authorization': `Basic ${btoa('admin:password')}`
    }
  });
  return response.json();
}
```

### File List

```javascript
// Polls /admin/files with filters
async function fetchFiles(filters) {
  const params = new URLSearchParams(filters);
  const response = await fetch(`/api/admin/files?${params}`, {
    headers: {
      'Authorization': `Basic ${btoa('admin:password')}`
    }
  });
  return response.json();
}
```

## API Integration

The Admin Portal integrates with the Admin API (port 8081) for all data.

### Base URL Configuration

```typescript
// src/config.ts
export const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8081';
```

### Authentication

The portal uses HTTP Basic authentication:

```typescript
// src/api/client.ts
const credentials = btoa(`${username}:${password}`);

const headers = {
  'Authorization': `Basic ${credentials}`,
  'Content-Type': 'application/json'
};
```

### Available Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/admin/health` | GET | System health status |
| `/admin/metrics` | GET | Operational metrics |
| `/admin/config` | GET | Current configuration |
| `/admin/config` | PATCH | Update configuration |
| `/admin/files` | GET | List files with filters |
| `/admin/retry/{id}` | POST | Retry failed file |
| `/admin/poller/trigger` | POST | Trigger poll cycle |

## Metrics Display

### File Processing Metrics

```json
{
  "timestamp": "2026-01-31T10:30:00Z",
  "inbound": {
    "files_discovered": 1234,
    "files_processed": 1200,
    "files_failed": 12,
    "files_pending": 22
  },
  "outbound": {
    "files_submitted": 5000,
    "files_uploaded": 4995,
    "files_failed": 3,
    "files_pending": 2
  }
}
```

### System Metrics

```json
{
  "uptime_seconds": 86400,
  "poller": {
    "enabled": true,
    "last_poll": "2026-01-31T10:29:00Z",
    "poll_count": 500
  },
  "sta_client": {
    "requests_total": 50000,
    "requests_failed": 45,
    "avg_latency_ms": 450
  }
}
```

## File Monitoring

### Filtering Files

The file list supports multiple filters:

```
/admin/files?status=failed&system=SPI&limit=50&offset=0
```

| Filter | Description |
|--------|-------------|
| `status` | Filter by status: `pending`, `completed`, `failed` |
| `system` | Filter by BCB system: `CCS`, `SPI`, `DICT`, etc. |
| `limit` | Maximum files to return (default: 100, max: 1000) |
| `offset` | Pagination offset |
| `start_date` | Start date (ISO 8601 or YYYY-MM-DD) |
| `end_date` | End date (ISO 8601 or YYYY-MM-DD) |

### File Status Colors

| Status | Color | Description |
|--------|-------|-------------|
| `pending` | Yellow | Awaiting processing |
| `uploading` | Blue | Upload in progress |
| `completed` | Green | Successfully processed |
| `failed` | Red | Processing failed |
| `retrying` | Orange | Scheduled for retry |

## Configuration Management

### Viewing Configuration

The configuration page displays all settings with sensitive values redacted:

```json
{
  "service": {
    "name": "sta-connector",
    "log_level": "info"
  },
  "sta": {
    "environment": "homologation",
    "username": "user123",
    "password": "[REDACTED]",
    "timeout_seconds": 30
  },
  "poller": {
    "enabled": true,
    "interval_seconds": 30
  }
}
```

### Updating Configuration

Hot-reloadable settings can be changed via the portal:

```javascript
// Update poller interval
await fetch('/api/admin/config', {
  method: 'PATCH',
  headers: {
    'Authorization': `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    poller: {
      interval_seconds: 60
    }
  })
});
```

## Route Management

### Listing Routes

Routes are displayed with their current status:

```
┌──────────┬────────────┬─────────────────────────────────┬─────────┐
│ System   │ Status     │ URL                             │ Actions │
├──────────┼────────────┼─────────────────────────────────┼─────────┤
│ CCS      │ ● Enabled  │ https://fluxiq.com.br/api/ccs   │ [Toggle]│
│ SPI      │ ● Enabled  │ https://fluxiq.com.br/api/spi   │ [Toggle]│
│ DICT     │ ○ Disabled │ https://fluxiq.com.br/api/dict  │ [Toggle]│
└──────────┴────────────┴─────────────────────────────────┴─────────┘
```

### Toggling Routes

Enable or disable routes without restart:

```javascript
// Disable a route
await fetch('/api/admin/config', {
  method: 'PATCH',
  headers: { /* ... */ },
  body: JSON.stringify({
    routes: {
      DICT: {
        enabled: false
      }
    }
  })
});
```

## Manual Operations

### Retry Failed File

```javascript
async function retryFile(fileId) {
  const response = await fetch(`/api/admin/retry/${fileId}`, {
    method: 'POST',
    headers: {
      'Authorization': `Basic ${credentials}`
    }
  });
  return response.json();
}
```

### Trigger Poll Cycle

```javascript
async function triggerPoll() {
  const response = await fetch('/api/admin/poller/trigger', {
    method: 'POST',
    headers: {
      'Authorization': `Basic ${credentials}`
    }
  });
  return response.json();
}
```

## Dark Mode

The Admin Portal supports dark mode:

```typescript
// Toggle theme
const toggleTheme = () => {
  const current = localStorage.getItem('theme') || 'light';
  const next = current === 'light' ? 'dark' : 'light';
  localStorage.setItem('theme', next);
  document.documentElement.classList.toggle('dark');
};
```

## Building the Portal

### Development

```bash
cd admin-portal
npm install
npm run dev
```

### Production Build

```bash
cd admin-portal
npm run build
```

The build output is in `admin-portal/dist/` and can be served by any static file server.

### Docker

The portal is included in the Docker Compose setup:

```yaml
services:
  admin-portal:
    build:
      context: ../admin-portal
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    depends_on:
      - sta-connector
```

## Customization

### Environment Variables

```bash
# API URL for the admin portal
VITE_API_URL=http://localhost:8081

# Polling intervals (milliseconds)
VITE_HEALTH_POLL_INTERVAL=30000
VITE_METRICS_POLL_INTERVAL=5000
VITE_FILES_POLL_INTERVAL=10000
```

### Proxy Configuration

For development, configure the Vite proxy:

```typescript
// vite.config.ts
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8081',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
});
```

## Next Steps

- [Admin API](/api/admin) - Full API reference
- [Configuration](/guide/configuration) - Configuration options
- [Troubleshooting](/troubleshooting) - Common issues
