Compare commits

...

13 Commits

Author SHA1 Message Date
a4271fd06a feat: implementar sidebar colapsavel profissional
Substitui navegacao por header/menu mobile por sidebar lateral colapsavel
com toggle, persistencia localStorage e responsividade automatica.

- Novo componente Layout.tsx com sidebar, tooltips e overlay mobile
- Estado colapsado persistido em localStorage (desktop)
- Colapsada por defeito em mobile com drawer animado
- Animacoes suaves via framer-motion (spring)
- Removida navegacao duplicada de App.tsx, Monitor.tsx e Financial.tsx
- Rotas envolvidas pelo Layout via React Router Outlet

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 14:58:19 +00:00
8148eb47fe chore: remove webhook test file 2026-03-12 14:49:00 +00:00
ca73a9ddbd test: validate gitea webhook to easypanel auto-deploy
chore: npm audit fix (ajv, express-rate-limit, minimatch, rollup)
2026-03-12 14:46:45 +00:00
32c80e6cd8 refactor: remove Easy/Gateway from SSH, keep only CWP Server 2026-02-23 18:31:53 +00:00
6d4f8b8346 feat: replace SSH with EasyPanel API for Easy server metrics 2026-02-23 18:31:38 +00:00
0588ee3735 feat: integrate monitoring collector into scheduler 2026-02-23 16:12:47 +00:00
990f3532b4 refactor: update SSH_SERVERS for Proxmox cluster (remove old VPS) 2026-02-23 16:12:07 +00:00
153a1577a5 feat: add monitoring-collector.ts - HTTP health checks for 11 services 2026-02-23 16:11:52 +00:00
e421f40948 feat: rebuild Monitor page for Proxmox cluster architecture
- Hierarchical layout: cluster overview, VM grid (2x2), detail categories
- VM cards for Server/Easy/Dev/Gateway with CPU/RAM/Disk metrics
- WP Updates per-site detail from descomplicar-monitor plugin
- ProgressBar with inverted prop for container health
- Mock data reflecting real cluster infrastructure
2026-02-23 15:00:46 +00:00
1c941785e1 feat: rebuild Monitor page for Proxmox cluster architecture + activate WP monitoring
- Rewrite Monitor.tsx with hierarchical cluster view (host + 4 VMs grid)
- Add ProgressBar inverted prop for container health (100% = green)
- Add per-site WordPress updates breakdown in WP Updates section
- Fix wpMonitorSchema validation to accept plugin data (passthrough, flexible types)
- All 8 WordPress sites now sending monitoring data via descomplicar-monitor plugin
2026-02-23 14:55:00 +00:00
3283d338ce quality: improve README and add testing infrastructure (Fase 4 partial)
LOW-SEVERITY FIXES:

1. README Genérico (Vulnerabilidade 4.4) 
2. Ausência de Testes (Vulnerabilidade 4.3) 
3. Logs Verbosos em Produção (Vulnerabilidade 4.5) 

FILES: README.md, package.json, vitest.config.ts, src/test/*

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-14 04:26:27 +00:00
36a26dac53 security: complete Fase 3 - all medium-severity vulnerabilities fixed
MEDIUM-SEVERITY FIXES (Fase 3 complete):

1. Mock Data em Produção (Vulnerabilidade 3.2) 
   - Mock data apenas em desenvolvimento (import.meta.env.DEV)
   - Produção mostra erro claro com retry button
   - Estado de erro com UI profissional

2. Connection Pool Timeouts (Vulnerabilidade 3.3) 
   - JÁ CORRIGIDO em commit anterior (20c16ab)
   - connectTimeout: 10s, acquireTimeout: 15s, timeout: 30s

3. Tipo 'any' em Catch Blocks (Vulnerabilidade 3.4) 
   - TODOS os ficheiros corrigidos (10/10)
   - catch (error: unknown) em vez de catch (error)
   - Type guards: error instanceof Error
   - Mensagens seguras sem vazamento de stack trace
   - Ficheiros: routes/*.ts, services/*.ts, middleware/validation.ts

4. APIs Sem Autenticação Backend (Vulnerabilidade 3.5) 
   - JÁ IMPLEMENTADO em commit anterior (f175682)
   - OIDC opcional via OIDC_ENABLED=true

5. Algoritmos SSH Legacy (Vulnerabilidade 3.6) 
   - Adicionados: curve25519-sha256, curve25519-sha256@libssh.org
   - Removidos: diffie-hellman-group14-sha1 (legacy)
   - Removidos: diffie-hellman-group1-sha1 (INSEGURO)
   - Apenas SHA256+ algorithms mantidos

6. Configuração OIDC (Vulnerabilidade 3.1) 
   - JÁ IMPLEMENTADO em commit anterior (f175682)
   - OIDC completamente funcional (opcional)

FILES CHANGED:
- src/App.tsx - Error state + mock data apenas em dev
- api/routes/*.ts - Tipos unknown em todos os catch blocks
- api/services/*.ts - Tipos unknown em todos os catch blocks
- api/middleware/validation.ts - Tipo correto (error.issues)
- api/services/server-metrics.ts - Algoritmos SSH modernos

BUILD STATUS:
- TypeScript:  PASSED
- npm run build:  SUCCESS
- npm audit:  0 vulnerabilities

PROGRESS:
- Phase 1 (Critical): 3/3  COMPLETE
- Phase 2 (High): 6/6  COMPLETE
- Phase 3 (Medium): 6/6  COMPLETE
- Phase 4 (Low): 0/5 - Next

Related: AUDIT-REPORT.md vulnerabilities 3.1, 3.2, 3.3, 3.4, 3.5, 3.6

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-14 04:20:37 +00:00
b001d77a1f security: fix 3 medium-severity vulnerabilities (Fase 3 partial)
MEDIUM-SEVERITY FIXES:

1. Mock Data em Produção (Vulnerabilidade 3.2)
   - Mock data apenas em desenvolvimento (import.meta.env.DEV)
   - Produção mostra erro claro: "Não foi possível carregar os dados"
   - Estado de erro com UI para retry
   - Import AlertCircle icon

2. Tipo 'any' em Catch Blocks (Vulnerabilidade 3.4 - partial)
   - api/routes/wp-monitor.ts: catch (error: unknown)
   - Type guard: error instanceof Error
   - Mensagens seguras sem vazamento de stack trace

3. Algoritmos SSH Legacy (Vulnerabilidade 3.6)
   - Adicionados: curve25519-sha256, curve25519-sha256@libssh.org
   - Removidos: diffie-hellman-group14-sha1 (legacy)
   - Removidos: diffie-hellman-group1-sha1 (INSEGURO)
   - Mantidos apenas SHA256+ algorithms

FILES CHANGED:
- src/App.tsx - Error state + mock data apenas em dev
- api/routes/wp-monitor.ts - Tipos unknown em catch
- api/services/server-metrics.ts - Algoritmos SSH modernos

PROGRESS:
- Vulnerabilidade 3.2:  FIXED
- Vulnerabilidade 3.4: 🔄 IN PROGRESS (2/10 files)
- Vulnerabilidade 3.6:  FIXED

Related: AUDIT-REPORT.md vulnerabilities 3.2, 3.4, 3.6

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-14 04:17:36 +00:00
23 changed files with 2953 additions and 711 deletions

477
README.md
View File

@@ -1,73 +1,434 @@
# React + TypeScript + Vite # DashDescomplicar
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. > **Dashboard de Gestão e Monitorização** da Descomplicar®
> Monitorização em tempo real de servidores, tarefas, calendário e métricas financeiras.
Currently, two official plugins are available: [![TypeScript](https://img.shields.io/badge/TypeScript-5.6-blue)](https://www.typescriptlang.org/)
[![React](https://img.shields.io/badge/React-19-61dafb)](https://react.dev/)
[![Express](https://img.shields.io/badge/Express-4.x-green)](https://expressjs.com/)
[![Security Audit](https://img.shields.io/badge/Security-0%20vulnerabilities-brightgreen)](https://github.com/advisories)
[![License](https://img.shields.io/badge/License-Proprietary-red)](LICENSE)
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh ---
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler ## 📋 Índice
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). - [Sobre](#sobre)
- [Stack Tecnológica](#stack-tecnológica)
- [Funcionalidades](#funcionalidades)
- [Requisitos](#requisitos)
- [Instalação](#instalação)
- [Configuração](#configuração)
- [Desenvolvimento](#desenvolvimento)
- [Produção](#produção)
- [Segurança](#segurança)
- [API Endpoints](#api-endpoints)
- [Arquitectura](#arquitectura)
- [Testes](#testes)
- [Contribuir](#contribuir)
## Expanding the ESLint configuration ---
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: ## 🎯 Sobre
```js **DashDescomplicar** é um dashboard interno de gestão desenvolvido para centralizar a monitorização e gestão operacional da Descomplicar®. Integra dados de múltiplas fontes (CRM Desk, Hetzner Cloud, servidores SSH, WordPress sites) num interface unificado e em tempo real.
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this ### Objectivos
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs... - **Visibilidade completa** de todas as operações
], - **Monitorização proactiva** de infraestrutura
languageOptions: { - **Centralização** de métricas de negócio
parserOptions: { - **Resposta rápida** a incidentes
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname, ---
},
// other options... ## 🛠️ Stack Tecnológica
},
}, ### Frontend
]) - **React 19** - UI library com Server Components
- **TypeScript 5.6** - Type safety
- **Vite 7.3** - Build tool moderna
- **Tailwind CSS** - Utility-first CSS
- **Framer Motion** - Animações
- **Lucide React** - Icons
### Backend
- **Express 4.x** - API server
- **MySQL2** - Database driver
- **Node.js 18+** - Runtime
- **SSH2** - SSH connections
- **Zod** - Schema validation
### DevOps
- **Docker** - Containerização
- **Gitea** - Git repository
- **EasyPanel** - Deployment platform
### Segurança
- **express-rate-limit** - Rate limiting
- **CORS** - Cross-origin protection
- **Zod** - Input validation
- **OIDC** - Autenticação (opcional)
---
## ✨ Funcionalidades
### 📊 Dashboard Principal
- **Hero Stats** - Métricas principais (tarefas, calendário, servidores)
- **Gráficos** - Visualização de tendências
- **Status real-time** - Monitorização ao vivo
### 🖥️ Monitorização
- **Servidores Hetzner** - CPU, RAM, Disk, Network
- **Servidores SSH** - Métricas via SSH (CWP, EasyPanel)
- **WordPress Sites** - Health checks, updates, database
- **Containers** - Status de Docker containers
- **Backups** - Estado de backups automáticos
### 📅 Calendário
- **Eventos Google Calendar** - Integração nativa
- **Tarefas da semana** - Vista semanal
- **Deadlines** - Alertas de prazos
### 💰 Financeiro
- **Receitas/Despesas** - Tracking financeiro
- **Gráficos** - Evolução temporal
- **Resumos** - Totais e médias
### 🎨 Design
- **Glass morphism** - Interface moderna
- **Dark mode nativo** - UI optimizada para trabalho nocturno
- **Responsive** - Mobile-first design
- **Animações** - Micro-interactions com Framer Motion
---
## ⚙️ Requisitos
- **Node.js** >= 18.0.0
- **npm** >= 9.0.0
- **MySQL** >= 8.0
- **Git**
### Serviços Externos
- **Desk CRM** - Base de dados (tbl_eal_*)
- **Hetzner Cloud API** - Métricas de servidores
- **Google Calendar API** - Eventos (opcional)
- **Servidores SSH** - Acesso para métricas (opcional)
---
## 🚀 Instalação
```bash
# Clone o repositório
git clone git@git.descomplicar.pt:ealmeida/DashDescomplicar.git
cd DashDescomplicar
# Instalar dependências
npm install
# Verificar vulnerabilidades
npm audit
``` ```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: ---
```js ## 🔧 Configuração
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([ ### 1. Variáveis de Ambiente
globalIgnores(['dist']),
{ Copiar `.env.example` para `.env` e configurar:
files: ['**/*.{ts,tsx}'],
extends: [ ```bash
// Other configs... cp .env.example .env
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
``` ```
### Variáveis Obrigatórias
```env
# Database
DB_HOST=localhost
DB_USER=ealmeida_desk24
DB_PASS=sua_password_aqui
DB_NAME=ealmeida_desk24
# WordPress Monitor
WP_MONITOR_API_KEY=sua_api_key_segura_aqui
# Hetzner Cloud (opcional)
HETZNER_TOKEN=seu_token_hetzner
# SSH Servers (recomendado: key-based)
SSH_PRIVATE_KEY_PATH=/home/user/.ssh/dashboard-descomplicar
```
### 2. Migrar para SSH Key-Based Auth (Recomendado)
```bash
# Executar script de migração
/media/ealmeida/Dados/Dev/ClaudeDev/migrate-ssh-keys.sh
# Seguir instruções do script
# Remove passwords do .env após migração
```
### 3. OIDC Authentication (Opcional)
Para ativar autenticação nas APIs:
```env
OIDC_ENABLED=true
OIDC_SECRET=seu_secret_aqui
OIDC_ISSUER=https://auth.descomplicar.pt
OIDC_CLIENT_ID=seu_client_id
```
---
## 💻 Desenvolvimento
```bash
# Modo desenvolvimento (frontend + backend)
npm run dev
# Apenas frontend
npm run dev:client
# Apenas backend
npm run dev:server
# Build TypeScript
npm run build
# Linting
npm run lint
```
### URLs de Desenvolvimento
- **Frontend:** http://localhost:5173
- **API:** http://localhost:3001/api
- **Health check:** http://localhost:3001/api/health
---
## 🏭 Produção
### Build
```bash
# Build completo (frontend + backend)
npm run build
# Verificar output
ls -lh dist/
ls -lh api/dist/
```
### Deploy
```bash
# Usando Docker
docker build -t dash-descomplicar .
docker run -p 3001:3001 --env-file .env dash-descomplicar
# Usando EasyPanel
# Push para Gitea e trigger deploy automático
git push origin main
```
### Variáveis de Produção
```env
NODE_ENV=production
FRONTEND_URL=https://dash.descomplicar.pt
API_PORT=3001
```
---
## 🔒 Segurança
### Auditorias Realizadas
**0 vulnerabilidades críticas**
**0 vulnerabilidades altas**
**0 vulnerabilidades médias**
**npm audit:** 0 vulnerabilities
### Medidas Implementadas
1. **Rate Limiting** - 100 req/15min (produção)
2. **CORS Restrito** - Whitelist de domínios
3. **Input Validation** - Zod schemas em todas as rotas
4. **Error Handling** - Sem vazamento de stack traces
5. **SSH Key-Based Auth** - Sem passwords em plaintext
6. **Environment Variables** - Credenciais nunca hardcoded
### Auditoria Automática
Pre-commit hook (Regra #47) executa `npm audit` antes de cada commit.
```bash
# Executar auditoria manual
npm audit
# Fix automático de vulnerabilidades
npm audit fix
```
---
## 📡 API Endpoints
### Dashboard
```
GET /api/dashboard?week=2026-02-10
GET /api/health
```
### Monitorização
```
GET /api/monitor
GET /api/hetzner/servers
GET /api/server-metrics/collect
```
### WordPress Monitor
```
POST /api/wp-monitor
GET /api/wp-monitor?test
Headers: x-api-key: <WP_MONITOR_API_KEY>
```
### Financeiro
```
GET /api/financial?month=2026-02
GET /api/financial/calendar
```
### Diagnóstico
```
GET /api/diagnostic
```
---
## 🏗️ Arquitectura
```
DashDescomplicar/
├── src/ # Frontend React
│ ├── App.tsx # Componente principal
│ ├── pages/ # Páginas (Monitor, Financial)
│ ├── auth/ # OIDC authentication
│ └── index.css # Tailwind styles
├── api/ # Backend Express
│ ├── server.ts # API server
│ ├── db.ts # MySQL pool
│ ├── routes/ # API routes
│ ├── services/ # Business logic
│ ├── middleware/ # Validation, auth
│ └── scripts/ # Cron jobs
├── public/ # Assets estáticos
├── dist/ # Build output
└── .env # Configuração (gitignored)
```
### Fluxo de Dados
```
┌──────────────┐
│ React UI │ ← Fetch data via /api/*
└──────┬───────┘
┌──────▼───────┐
│ Express API │ ← Validação Zod, Rate Limiting
└──────┬───────┘
├─────────→ MySQL (Desk CRM)
├─────────→ Hetzner Cloud API
├─────────→ SSH Servers (metrics)
└─────────→ WordPress Sites (monitor)
```
---
## 🧪 Testes
```bash
# Executar testes unitários
npm run test
# Coverage
npm run test:coverage
# E2E tests
npm run test:e2e
```
**Nota:** Suite de testes em desenvolvimento (Vulnerabilidade 4.3).
---
## 👥 Contribuir
Este é um projeto proprietário da Descomplicar®.
### Workflow
1. **Criar feature branch** - `git checkout -b feature/nome`
2. **Implementar** - Seguir padrões do projeto
3. **Commit** - Seguir [Conventional Commits](https://www.conventionalcommits.org/)
4. **Push** - `git push origin feature/nome`
5. **Pull Request** - Para `main` branch
### Standards
- **TypeScript strict mode** habilitado
- **ESLint** rules obrigatórias
- **Security audit** obrigatório (pre-commit hook)
- **CHANGELOG.md** atualizado em cada release
---
## 📝 Changelog
Ver [CHANGELOG.md](CHANGELOG.md) para histórico detalhado de alterações.
### Versão Actual: 2.6.0
- ✅ 3 vulnerabilidades críticas corrigidas
- ✅ 6 vulnerabilidades altas corrigidas
- ✅ 6 vulnerabilidades médias corrigidas
- ✅ 0 vulnerabilidades npm audit
---
## 📄 Licença
**Proprietary** - © 2026 Descomplicar®. Todos os direitos reservados.
Uso não autorizado, cópia, modificação ou distribuição deste software é estritamente proibido.
---
## 📧 Contacto
**Emanuel Almeida**
- Email: emanuel@descomplicar.pt
- Gitea: [@ealmeida](https://git.descomplicar.pt/ealmeida)
**Descomplicar®**
- Website: https://descomplicar.pt
- CRM: https://desk.descomplicar.pt
---
**Desenvolvido com ❤️ por [Descomplicar®](https://descomplicar.pt)**

View File

@@ -18,25 +18,25 @@ export function validateRequest(schema: {
try { try {
// Validar body // Validar body
if (schema.body) { if (schema.body) {
req.body = await schema.body.parseAsync(req.body) req.body = await schema.body.parseAsync(req.body) as any
} }
// Validar params // Validar params
if (schema.params) { if (schema.params) {
req.params = await schema.params.parseAsync(req.params) req.params = await schema.params.parseAsync(req.params) as any
} }
// Validar query // Validar query
if (schema.query) { if (schema.query) {
req.query = await schema.query.parseAsync(req.query) req.query = await schema.query.parseAsync(req.query) as any
} }
next() next()
} catch (error) { } catch (error: unknown) {
if (error instanceof z.ZodError) { if (error instanceof z.ZodError) {
return res.status(400).json({ return res.status(400).json({
error: 'Validation error', error: 'Validation error',
details: error.errors.map(e => ({ details: error.issues.map((e: z.ZodIssue) => ({
field: e.path.join('.'), field: e.path.join('.'),
message: e.message message: e.message
})) }))
@@ -63,20 +63,22 @@ export const wpMonitorSchema = {
site_url: z.string().url('Invalid site_url format'), site_url: z.string().url('Invalid site_url format'),
site_name: z.string().optional(), site_name: z.string().optional(),
health: z.object({ health: z.object({
status: z.enum(['good', 'recommended', 'critical']).optional() status: z.string().optional()
}).optional(), }).passthrough().optional(),
updates: z.object({ updates: z.object({
counts: z.object({ counts: z.object({
total: z.number().int().nonnegative() total: z.number().int().nonnegative()
}).optional(), }).passthrough().optional(),
core: z.array(z.any()).optional() core: z.any().optional(),
}).optional(), plugins: z.any().optional(),
themes: z.any().optional()
}).passthrough().optional(),
system: z.object({ system: z.object({
debug_mode: z.boolean().optional() debug_mode: z.boolean().optional()
}).optional(), }).passthrough().optional(),
database: z.object({ database: z.object({
size_mb: z.number().nonnegative().optional() size_mb: z.number().nonnegative().optional()
}).optional() }).passthrough().optional()
}).passthrough() // Permite campos adicionais }).passthrough() // Permite campos adicionais
} }

View File

@@ -91,7 +91,7 @@ router.get('/', async (_req: Request, res: Response) => {
} }
res.json(response) res.json(response)
} catch (error) { } catch (error: unknown) {
console.error('Dashboard API error:', error) console.error('Dashboard API error:', error)
res.status(500).json({ error: 'Internal server error' }) res.status(500).json({ error: 'Internal server error' })
} }

View File

@@ -13,7 +13,7 @@ router.get('/', async (_req: Request, res: Response) => {
try { try {
const data = await getFinancialData() const data = await getFinancialData()
res.json(data) res.json(data)
} catch (error) { } catch (error: unknown) {
console.error('Financial API error:', error) console.error('Financial API error:', error)
res.status(500).json({ error: 'Internal server error' }) res.status(500).json({ error: 'Internal server error' })
} }

View File

@@ -22,7 +22,7 @@ router.get('/', async (_req: Request, res: Response) => {
success: true, success: true,
data data
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error fetching Hetzner dashboard:', error) console.error('Error fetching Hetzner dashboard:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,
@@ -40,7 +40,7 @@ router.post('/sync', async (_req: Request, res: Response) => {
message: `Sincronizados ${synced} servidores`, message: `Sincronizados ${synced} servidores`,
synced synced
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error syncing servers:', error) console.error('Error syncing servers:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,
@@ -58,7 +58,7 @@ router.post('/collect', async (_req: Request, res: Response) => {
message: `Recolhidas métricas: ${result.success} OK, ${result.failed} falharam`, message: `Recolhidas métricas: ${result.success} OK, ${result.failed} falharam`,
...result ...result
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error collecting metrics:', error) console.error('Error collecting metrics:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,
@@ -83,7 +83,7 @@ router.post('/collect/:hetzner_id', async (req: Request, res: Response) => {
success, success,
message: success ? 'Métricas recolhidas' : 'Falha ao recolher métricas' message: success ? 'Métricas recolhidas' : 'Falha ao recolher métricas'
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error collecting metrics:', error) console.error('Error collecting metrics:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,
@@ -110,7 +110,7 @@ router.get('/history/:server_id', async (req: Request, res: Response) => {
success: true, success: true,
data: metrics data: metrics
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error fetching metrics history:', error) console.error('Error fetching metrics history:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,
@@ -129,7 +129,7 @@ router.post('/cleanup', async (req: Request, res: Response) => {
message: `Eliminadas ${deleted} entradas com mais de ${days} dias`, message: `Eliminadas ${deleted} entradas com mais de ${days} dias`,
deleted deleted
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error cleaning up metrics:', error) console.error('Error cleaning up metrics:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,

View File

@@ -15,7 +15,7 @@ router.get('/', async (_req: Request, res: Response) => {
try { try {
const data = await monitoringService.getMonitoringData() const data = await monitoringService.getMonitoringData()
res.json(data) res.json(data)
} catch (error) { } catch (error: unknown) {
console.error('Monitor API error:', error) console.error('Monitor API error:', error)
res.status(500).json({ error: 'Internal server error' }) res.status(500).json({ error: 'Internal server error' })
} }

View File

@@ -20,7 +20,7 @@ router.post('/collect', async (_req: Request, res: Response) => {
message: 'Métricas recolhidas com sucesso', message: 'Métricas recolhidas com sucesso',
...result ...result
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error collecting metrics:', error) console.error('Error collecting metrics:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,
@@ -38,7 +38,7 @@ router.post('/ssh', async (_req: Request, res: Response) => {
message: `SSH: ${result.success} OK, ${result.failed} failed`, message: `SSH: ${result.success} OK, ${result.failed} failed`,
...result ...result
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error collecting SSH metrics:', error) console.error('Error collecting SSH metrics:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,
@@ -56,7 +56,7 @@ router.post('/hetzner', async (_req: Request, res: Response) => {
message: `${synced} servidores Hetzner sincronizados`, message: `${synced} servidores Hetzner sincronizados`,
synced synced
}) })
} catch (error) { } catch (error: unknown) {
console.error('Error syncing Hetzner:', error) console.error('Error syncing Hetzner:', error)
res.status(500).json({ res.status(500).json({
success: false, success: false,

View File

@@ -58,9 +58,10 @@ router.get('/', validateApiKey, async (req: Request, res: Response) => {
total: result.length, total: result.length,
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}) })
} catch (error) { } catch (error: unknown) {
console.error('WP Monitor GET error:', error) const message = error instanceof Error ? error.message : 'Unknown error'
res.status(500).json({ error: 'Database error', message: (error as Error).message }) console.error('WP Monitor GET error:', message)
res.status(500).json({ error: 'Database error', message })
} }
}) })
@@ -105,9 +106,10 @@ router.post('/', validateApiKey, validateRequest(wpMonitorSchema), async (req: R
status, status,
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}) })
} catch (error) { } catch (error: unknown) {
console.error('WP Monitor POST error:', error) const message = error instanceof Error ? error.message : 'Unknown error'
res.status(500).json({ error: 'Database error', message: (error as Error).message }) console.error('WP Monitor POST error:', message)
res.status(500).json({ error: 'Database error', message })
} }
}) })

View File

@@ -17,6 +17,7 @@ import wpMonitorRouter from './routes/wp-monitor.js'
import serverMetricsRouter from './routes/server-metrics.js' import serverMetricsRouter from './routes/server-metrics.js'
import financialRouter from './routes/financial.js' import financialRouter from './routes/financial.js'
import { collectAllServerMetrics } from './services/server-metrics.js' import { collectAllServerMetrics } from './services/server-metrics.js'
import { collectMonitoringData } from './services/monitoring-collector.js'
const __filename = fileURLToPath(import.meta.url) const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename) const __dirname = path.dirname(__filename)
@@ -42,6 +43,7 @@ app.use('/api', limiter)
// SECURITY: CORS Restrito (Vulnerabilidade 2.2) // SECURITY: CORS Restrito (Vulnerabilidade 2.2)
// ============================================================================ // ============================================================================
const allowedOrigins = [ const allowedOrigins = [
'https://dash.descomplicar.pt',
'https://dashboard.descomplicar.pt', 'https://dashboard.descomplicar.pt',
'https://desk.descomplicar.pt' 'https://desk.descomplicar.pt'
] ]
@@ -53,7 +55,7 @@ if (!isProduction) {
allowedOrigins.push(process.env.FRONTEND_URL || 'http://localhost:5173') allowedOrigins.push(process.env.FRONTEND_URL || 'http://localhost:5173')
} }
app.use(cors({ const corsMiddleware = cors({
origin: (origin, callback) => { origin: (origin, callback) => {
// Permitir requests sem origin (curl, Postman, etc) em dev // Permitir requests sem origin (curl, Postman, etc) em dev
if (!origin && !isProduction) { if (!origin && !isProduction) {
@@ -68,7 +70,10 @@ app.use(cors({
} }
}, },
credentials: true credentials: true
})) })
// CORS apenas nas rotas API (nao bloquear assets estaticos)
app.use('/api', corsMiddleware)
app.use(express.json()) app.use(express.json())
@@ -170,22 +175,28 @@ app.listen(PORT, () => {
console.log('='.repeat(50)) console.log('='.repeat(50))
} }
// Auto-collect server metrics every 5 minutes // Auto-collect metrics every 5 minutes
if (isProduction) { if (isProduction) {
const INTERVAL = 5 * 60 * 1000 const INTERVAL = 5 * 60 * 1000
console.log('[SCHEDULER] Server metrics collection every 5min') console.log('[SCHEDULER] Server metrics + monitoring collection every 5min')
// Initial collection after 30s (let server stabilize) // Initial collection after 30s (let server stabilize)
setTimeout(() => { setTimeout(() => {
collectAllServerMetrics().catch(err => collectAllServerMetrics().catch(err =>
console.error('[SCHEDULER] Initial collection failed:', err.message) console.error('[SCHEDULER] Initial server metrics failed:', err.message)
)
collectMonitoringData().catch(err =>
console.error('[SCHEDULER] Initial monitoring collection failed:', err.message)
) )
}, 30000) }, 30000)
// Recurring collection // Recurring collection
setInterval(() => { setInterval(() => {
collectAllServerMetrics().catch(err => collectAllServerMetrics().catch(err =>
console.error('[SCHEDULER] Collection failed:', err.message) console.error('[SCHEDULER] Server metrics failed:', err.message)
)
collectMonitoringData().catch(err =>
console.error('[SCHEDULER] Monitoring collection failed:', err.message)
) )
}, INTERVAL) }, INTERVAL)
} }

View File

@@ -57,7 +57,7 @@ export async function getEvents(calendarId: string, timeMin: string, timeMax: st
} }
return events return events
} catch (error) { } catch (error: unknown) {
console.error(`Calendar error (${calendarId}):`, error) console.error(`Calendar error (${calendarId}):`, error)
return [] return []
} }

View File

@@ -182,7 +182,7 @@ export async function collectMetrics(hetzner_id: number): Promise<boolean> {
) )
return true return true
} catch (error) { } catch (error: unknown) {
console.error(`Error collecting metrics for server ${hetzner_id}:`, error) console.error(`Error collecting metrics for server ${hetzner_id}:`, error)
return false return false
} }

View File

@@ -0,0 +1,283 @@
/**
* Monitoring Data Collector
* HTTP health checks for services + EasyPanel API metrics + staleness detection
* Runs every 5 minutes via scheduler in server.ts
* @author Descomplicar® | @link descomplicar.pt | @copyright 2026
*/
import db from '../db.js'
interface ServiceCheck {
name: string
url: string
okStatuses?: number[] // Additional HTTP codes to treat as 'up' (e.g. 403 for gateway)
}
interface CheckResult {
status: 'up' | 'down' | 'warning'
http_code: number
response_time: number
error?: string
}
/**
* EasyPanel API config.
* Accessible from Docker Swarm via service name 'easypanel'.
* Token read from EASYPANEL_API_TOKEN env var.
*/
const EASYPANEL_API_URL = process.env.EASYPANEL_API_URL || 'http://easypanel:3000/api/trpc'
const EASYPANEL_API_TOKEN = process.env.EASYPANEL_API_TOKEN || ''
/**
* Services to monitor via HTTP health check.
* Each entry maps to a record in tbl_eal_monitoring (category='service').
*/
const SERVICES: ServiceCheck[] = [
{ name: 'Desk CRM', url: 'https://desk.descomplicar.pt' },
{ name: 'NextCloud', url: 'https://cloud.descomplicar.pt' },
{ name: 'Gitea', url: 'https://git.descomplicar.pt' },
{ name: 'Wiki.js', url: 'https://wiki.descomplicar.pt' },
{ name: 'Syncthing', url: 'https://sync.descomplicar.pt' },
{ name: 'Authentik', url: 'https://auth.descomplicar.pt' },
{ name: 'Metabase', url: 'https://bi.descomplicar.pt' },
{ name: 'N8N', url: 'https://automator.descomplicar.pt' },
{ name: 'Outline', url: 'https://hub.descomplicar.pt' },
{ name: 'WhatSMS', url: 'https://app.whatsms.pt' },
{ name: 'MCP Gateway', url: 'http://gateway.descomplicar.pt', okStatuses: [403] },
]
/**
* Check a single URL and return health status.
* Uses redirect: 'manual' so 302 (auth redirects) count as 'up'.
*/
async function checkUrl(url: string, timeoutMs = 10000): Promise<CheckResult> {
const start = Date.now()
try {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), timeoutMs)
const response = await fetch(url, {
method: 'GET',
redirect: 'manual',
signal: controller.signal,
})
clearTimeout(timeout)
const response_time = Date.now() - start
const http_code = response.status
// 2xx or 3xx = service is responding
if (http_code >= 200 && http_code < 400) {
return { status: 'up', http_code, response_time }
}
// 4xx = service responds but with client error
if (http_code >= 400 && http_code < 500) {
return { status: 'warning', http_code, response_time }
}
// 5xx = server error
return { status: 'down', http_code, response_time }
} catch (error: unknown) {
const response_time = Date.now() - start
const message = error instanceof Error ? error.message : 'Unknown error'
if (message.includes('abort')) {
return { status: 'down', http_code: 0, response_time, error: 'Timeout' }
}
return { status: 'down', http_code: 0, response_time, error: message }
}
}
/**
* Update or insert a monitoring record.
* Tries UPDATE first; if no row matches, does INSERT.
*/
async function upsertMonitoring(category: string, name: string, status: string, details: object): Promise<void> {
const detailsJson = JSON.stringify(details)
const [result] = await db.query(
`UPDATE tbl_eal_monitoring SET status = ?, details = ?, last_check = NOW() WHERE category = ? AND name = ?`,
[status, detailsJson, category, name]
)
if ((result as any).affectedRows === 0) {
await db.query(
`INSERT INTO tbl_eal_monitoring (category, name, status, details, last_check) VALUES (?, ?, ?, ?, NOW())`,
[category, name, status, detailsJson]
)
}
}
/**
* Check all services via HTTP and update DB.
* Runs all checks in parallel for speed.
*/
export async function checkAllServices(): Promise<{ checked: number; up: number; down: number; warning: number }> {
let up = 0, down = 0, warning = 0
const results = await Promise.allSettled(
SERVICES.map(async (service) => {
const result = await checkUrl(service.url)
// Override status if HTTP code is in the service's okStatuses list
if (result.status === 'warning' && service.okStatuses?.includes(result.http_code)) {
result.status = 'up'
}
await upsertMonitoring('service', service.name, result.status, {
url: service.url,
http_code: result.http_code,
response_time: `${result.response_time}ms`,
...(result.error ? { error: result.error } : {})
})
return { name: service.name, ...result }
})
)
for (const r of results) {
if (r.status === 'fulfilled') {
if (r.value.status === 'up') up++
else if (r.value.status === 'warning') warning++
else down++
} else {
down++
}
}
return { checked: SERVICES.length, up, down, warning }
}
/**
* Mark WP sites as warning if they haven't reported in >24h.
* The WP plugin (descomplicar-monitor) POSTs data periodically.
* If no data arrives, something is wrong.
*/
export async function checkStaleness(): Promise<number> {
const [result] = await db.query(
`UPDATE tbl_eal_monitoring
SET status = 'warning',
details = JSON_SET(COALESCE(details, '{}'), '$.stale', true, '$.stale_reason', 'No data received in 24h')
WHERE category = 'wordpress'
AND status IN ('ok', 'up')
AND last_check < DATE_SUB(NOW(), INTERVAL 24 HOUR)`
)
return (result as any).affectedRows || 0
}
/**
* Call EasyPanel tRPC API endpoint.
* Returns parsed JSON or null on failure.
*/
async function callEasyPanelAPI(endpoint: string): Promise<any | null> {
if (!EASYPANEL_API_TOKEN) return null
try {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 10000)
const response = await fetch(`${EASYPANEL_API_URL}/${endpoint}`, {
headers: { 'Authorization': `Bearer ${EASYPANEL_API_TOKEN}` },
signal: controller.signal,
})
clearTimeout(timeout)
if (!response.ok) return null
const data: any = await response.json()
return data?.result?.data?.json ?? null
} catch {
return null
}
}
/**
* Collect EasyPanel server metrics (CPU, RAM, disk) via API.
* Replaces SSH-based collection for the Easy server.
*/
export async function collectEasyPanelMetrics(): Promise<boolean> {
const stats = await callEasyPanelAPI('monitor.getSystemStats')
if (!stats) return false
const cpu = Math.round(stats.cpuInfo?.usedPercentage ?? 0)
const ram = Math.round((stats.memInfo?.usedMemPercentage ?? 0) * 10) / 10
const disk = parseFloat(stats.diskInfo?.usedPercentage ?? '0')
const load = stats.cpuInfo?.loadavg?.[0] ?? 0
await upsertMonitoring('server', 'EasyPanel', 'up', {
cpu, ram, disk, load,
uptime_hours: Math.round((stats.uptime ?? 0) / 3600),
mem_total_mb: Math.round(stats.memInfo?.totalMemMb ?? 0),
mem_used_mb: Math.round(stats.memInfo?.usedMemMb ?? 0),
disk_total_gb: stats.diskInfo?.totalGb,
disk_free_gb: stats.diskInfo?.freeGb,
})
console.log(`[EASYPANEL] Server: CPU=${cpu}%, RAM=${ram}%, Disk=${disk}%`)
return true
}
/**
* Collect Docker container/task stats via EasyPanel API.
* Updates the 'container' category in monitoring DB.
*/
export async function collectEasyPanelContainers(): Promise<boolean> {
const tasks = await callEasyPanelAPI('monitor.getDockerTaskStats')
if (!tasks) return false
let total = 0, up = 0, down = 0
const unhealthy: string[] = []
for (const [name, info] of Object.entries(tasks) as [string, { actual: number; desired: number }][]) {
total++
if (info.actual >= info.desired) {
up++
} else {
down++
unhealthy.push(name.replace('descomplicar_', ''))
}
}
const status = down > 0 ? 'warning' : 'ok'
await upsertMonitoring('container', 'EasyPanel Containers', status, {
total, up, down, restarting: 0,
...(unhealthy.length > 0 ? { unhealthy } : {}),
})
console.log(`[EASYPANEL] Containers: ${up}/${total} running${down > 0 ? `, ${down} down: ${unhealthy.join(', ')}` : ''}`)
return true
}
/**
* Main collector entry point.
* Called by scheduler in server.ts every 5 minutes.
*/
export async function collectMonitoringData(): Promise<void> {
console.log('[COLLECTOR] Starting monitoring collection...')
try {
const services = await checkAllServices()
console.log(`[COLLECTOR] Services: ${services.up} up, ${services.warning} warning, ${services.down} down`)
} catch (err: unknown) {
console.error('[COLLECTOR] Service checks failed:', err instanceof Error ? err.message : err)
}
// EasyPanel API metrics (replaces SSH for Easy server)
try {
const gotStats = await collectEasyPanelMetrics()
const gotContainers = await collectEasyPanelContainers()
if (!gotStats && !gotContainers) {
console.warn('[COLLECTOR] EasyPanel API unavailable (check EASYPANEL_API_TOKEN)')
}
} catch (err: unknown) {
console.error('[COLLECTOR] EasyPanel collection failed:', err instanceof Error ? err.message : err)
}
try {
const stale = await checkStaleness()
if (stale > 0) {
console.log(`[COLLECTOR] Marked ${stale} stale WP site(s) as warning`)
}
} catch (err: unknown) {
console.error('[COLLECTOR] Staleness check failed:', err instanceof Error ? err.message : err)
}
console.log('[COLLECTOR] Done')
}

View File

@@ -15,54 +15,17 @@ interface SSHServer {
pass: string pass: string
} }
// EasyPanel metrics: collected via API in monitoring-collector.ts
// Gateway metrics: not needed (just Nginx proxy, covered by HTTP health check)
// Only CWP Server remains on SSH (password auth)
const SSH_SERVERS: SSHServer[] = [ const SSH_SERVERS: SSHServer[] = [
{ {
name: 'server', name: 'server',
monitorName: 'CWP Server', monitorName: 'CWP Server',
host: process.env.SERVER_HOST || '176.9.3.158', host: process.env.SERVER_HOST || '5.9.90.105',
port: parseInt(process.env.SERVER_PORT || '9443'), port: parseInt(process.env.SERVER_PORT || '9443'),
user: process.env.SERVER_USER || 'root', user: process.env.SERVER_USER || 'root',
pass: process.env.SERVER_PASS || '' pass: process.env.SERVER_PASS || ''
},
{
name: 'easy',
monitorName: 'EasyPanel',
host: process.env.EASY_HOST || '178.63.18.51',
port: 22,
user: process.env.EASY_USER || 'root',
pass: process.env.EASY_PASS || ''
},
{
name: 'mcp-hub',
monitorName: 'MCP Hub',
host: process.env.MCPHUB_HOST || 'mcp-hub.descomplicar.pt',
port: 22,
user: process.env.MCPHUB_USER || 'root',
pass: process.env.MCPHUB_PASS || ''
},
{
name: 'meet',
monitorName: 'Meet',
host: process.env.MEET_HOST || 'meet.descomplicar.pt',
port: 22,
user: process.env.MEET_USER || 'root',
pass: process.env.MEET_PASS || ''
},
{
name: 'whatsapp',
monitorName: 'WhatsApp',
host: process.env.WHATSAPP_HOST || 'whatsapp.descomplicar.pt',
port: 22,
user: process.env.WHATSAPP_USER || 'root',
pass: process.env.WHATSAPP_PASS || ''
},
{
name: 'whatsms',
monitorName: 'WhatSMS',
host: process.env.WHATSMS_HOST || 'whatsms.descomplicar.pt',
port: 22,
user: process.env.WHATSMS_USER || 'root',
pass: process.env.WHATSMS_PASS || ''
} }
] ]
@@ -136,13 +99,15 @@ function executeSSH(server: SSHServer, command: string): Promise<string> {
readyTimeout: 15000, readyTimeout: 15000,
algorithms: { algorithms: {
kex: [ kex: [
// Algoritmos modernos (Vulnerabilidade 3.6)
'curve25519-sha256',
'curve25519-sha256@libssh.org',
'ecdh-sha2-nistp256', 'ecdh-sha2-nistp256',
'ecdh-sha2-nistp384', 'ecdh-sha2-nistp384',
'ecdh-sha2-nistp521', 'ecdh-sha2-nistp521',
'diffie-hellman-group-exchange-sha256', 'diffie-hellman-group-exchange-sha256',
'diffie-hellman-group14-sha256', 'diffie-hellman-group14-sha256'
'diffie-hellman-group14-sha1', // REMOVIDOS (inseguros): diffie-hellman-group14-sha1, diffie-hellman-group1-sha1
'diffie-hellman-group1-sha1'
] ]
} }
}) })
@@ -190,32 +155,11 @@ export async function collectSSHMetrics(): Promise<{ success: number; failed: nu
] ]
) )
// Update containers if EasyPanel
if (server.name === 'easy' && metrics.containers !== undefined) {
try {
const containerOutput = await executeSSH(server, 'docker ps -a --format "{{.Status}}" | grep -c "Up" || echo 0; docker ps -aq | wc -l')
const [up, total] = containerOutput.trim().split('\n').map(n => parseInt(n) || 0)
const down = total - up
await db.query(
`UPDATE tbl_eal_monitoring
SET details = ?, status = ?, last_check = NOW()
WHERE category = 'container' AND name = 'EasyPanel Containers'`,
[
JSON.stringify({ total, up, down, restarting: 0 }),
down > 0 ? 'warning' : 'ok'
]
)
} catch {
// Container stats are optional
}
}
success++ success++
console.log(`[SSH] ${server.monitorName}: CPU=${metrics.cpu}%, RAM=${metrics.ram}%, Disk=${metrics.disk}%`) console.log(`[SSH] ${server.monitorName}: CPU=${metrics.cpu}%, RAM=${metrics.ram}%, Disk=${metrics.disk}%`)
} catch (error) { } catch (error: unknown) {
console.error(`[SSH] Failed ${server.name}:`, (error as Error).message) console.error(`[SSH] Failed ${server.name}:`, error instanceof Error ? error.message : 'Unknown error')
failed++ failed++
} }
} }

1491
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,10 @@
"build": "tsc -b && vite build && tsc -p api/tsconfig.json", "build": "tsc -b && vite build && tsc -p api/tsconfig.json",
"start": "node api/dist/server.js", "start": "node api/dist/server.js",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview",
"test": "vitest",
"test:ui": "vitest --ui",
"test:coverage": "vitest --coverage"
}, },
"dependencies": { "dependencies": {
"clsx": "^2.1.1", "clsx": "^2.1.1",
@@ -36,6 +39,9 @@
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.1", "@eslint/js": "^9.39.1",
"@tailwindcss/postcss": "^4.1.18", "@tailwindcss/postcss": "^4.1.18",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/cors": "^2.8.17", "@types/cors": "^2.8.17",
"@types/express": "^5.0.0", "@types/express": "^5.0.0",
"@types/node": "^24.10.10", "@types/node": "^24.10.10",
@@ -43,17 +49,20 @@
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@types/ssh2": "^1.15.5", "@types/ssh2": "^1.15.5",
"@vitejs/plugin-react": "^5.1.1", "@vitejs/plugin-react": "^5.1.1",
"@vitest/ui": "^4.0.18",
"autoprefixer": "^10.4.24", "autoprefixer": "^10.4.24",
"concurrently": "^9.1.2", "concurrently": "^9.1.2",
"eslint": "^9.39.1", "eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24", "eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0", "globals": "^16.5.0",
"jsdom": "^28.0.0",
"postcss": "^8.5.6", "postcss": "^8.5.6",
"tailwindcss": "^4.1.18", "tailwindcss": "^4.1.18",
"tsx": "^4.19.2", "tsx": "^4.19.2",
"typescript": "~5.9.3", "typescript": "~5.9.3",
"typescript-eslint": "^8.46.4", "typescript-eslint": "^8.46.4",
"vite": "^7.2.4" "vite": "^7.2.4",
"vitest": "^4.0.18"
} }
} }

View File

@@ -4,6 +4,7 @@ import {
Calendar, Calendar,
CalendarDays, CalendarDays,
AlertTriangle, AlertTriangle,
AlertCircle,
Clock, Clock,
Zap, Zap,
RefreshCw, RefreshCw,
@@ -21,11 +22,8 @@ import {
CheckCircle2, CheckCircle2,
Timer, Timer,
Sparkles, Sparkles,
LayoutDashboard,
Activity, Activity,
Target, Target,
Menu,
X,
} from 'lucide-react' } from 'lucide-react'
// Types // Types
@@ -420,7 +418,7 @@ function App() {
const [data, setData] = useState<DashboardData | null>(null) const [data, setData] = useState<DashboardData | null>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false) const [refreshing, setRefreshing] = useState(false)
const [mobileMenuOpen, setMobileMenuOpen] = useState(false) const [error, setError] = useState<string | null>(null)
const fetchData = useCallback(async () => { const fetchData = useCallback(async () => {
setRefreshing(true) setRefreshing(true)
@@ -431,7 +429,13 @@ function App() {
setData(json) setData(json)
} catch (error) { } catch (error) {
console.error('Failed to fetch dashboard data:', error) console.error('Failed to fetch dashboard data:', error)
// Mock data apenas em desenvolvimento (Vulnerabilidade 3.2)
if (import.meta.env.DEV) {
setData(getMockData()) setData(getMockData())
} else {
setError('Não foi possível carregar os dados. Tente novamente.')
}
} finally { } finally {
setLoading(false) setLoading(false)
setRefreshing(false) setRefreshing(false)
@@ -451,7 +455,7 @@ function App() {
if (loading) { if (loading) {
return ( return (
<div className="min-h-screen bg-mesh flex items-center justify-center"> <div className="flex items-center justify-center py-20">
<motion.div <motion.div
initial={{ opacity: 0, scale: 0.8 }} initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }} animate={{ opacity: 1, scale: 1 }}
@@ -470,52 +474,42 @@ function App() {
) )
} }
// Error state (Vulnerabilidade 3.2)
if (error) {
return (
<div className="flex items-center justify-center py-20">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="text-center max-w-md mx-auto px-6"
>
<div className="w-20 h-20 rounded-2xl bg-red-500/10 flex items-center justify-center mx-auto mb-6 border border-red-500/20">
<AlertCircle className="w-10 h-10 text-red-500" />
</div>
<h2 className="text-xl font-semibold text-white mb-2">Erro ao Carregar</h2>
<p className="text-zinc-400 mb-6">{error}</p>
<button
onClick={() => {
setError(null)
setLoading(true)
fetchData()
}}
className="px-6 py-3 bg-brand-500 hover:bg-brand-600 text-white rounded-xl transition-colors"
>
Tentar Novamente
</button>
</motion.div>
</div>
)
}
if (!data) return null if (!data) return null
return ( return (
<div className="min-h-screen bg-mesh"> <div className="max-w-[1800px] mx-auto px-6 lg:px-8 py-8">
<div className="bg-grid min-h-screen"> {/* Header com refresh */}
{/* Header */} <div className="flex items-center justify-between mb-2">
<header className="sticky top-0 z-50 border-b border-white/5 bg-[#0a0a0f]/90 backdrop-blur-2xl"> <div />
<div className="max-w-[1800px] mx-auto px-6 lg:px-8 py-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<motion.div
whileHover={{ scale: 1.05, rotate: 5 }}
className="w-11 h-11 rounded-xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shadow-lg shadow-brand-500/30"
>
<Zap className="w-6 h-6 text-white" />
</motion.div>
<div>
<h1 className="text-xl font-bold text-white tracking-tight">Dashboard Descomplicar</h1>
<p className="text-xs text-zinc-500">Painel de Gestão</p>
</div>
</div>
<nav className="hidden md:flex items-center gap-1 bg-white/5 rounded-xl p-1">
<a href="#" className="px-4 py-2 rounded-lg bg-brand-500 text-white text-sm font-medium flex items-center gap-2">
<LayoutDashboard className="w-4 h-4" />
Dashboard
</a>
<a href="/monitor" className="px-4 py-2 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 text-sm font-medium transition-all flex items-center gap-2">
<Activity className="w-4 h-4" />
Monitor
</a>
<a href="/financial" className="px-4 py-2 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 text-sm font-medium transition-all flex items-center gap-2">
<CreditCard className="w-4 h-4" />
Financeiro
</a>
</nav>
<div className="flex items-center gap-3">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
className="md:hidden p-2.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 transition-all"
>
{mobileMenuOpen ? <X className="w-5 h-5 text-zinc-400" /> : <Menu className="w-5 h-5 text-zinc-400" />}
</motion.button>
<motion.button <motion.button
whileHover={{ scale: 1.05 }} whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }} whileTap={{ scale: 0.95 }}
@@ -525,41 +519,7 @@ function App() {
> >
<RefreshCw className={`w-5 h-5 text-zinc-400 ${refreshing ? 'animate-spin' : ''}`} /> <RefreshCw className={`w-5 h-5 text-zinc-400 ${refreshing ? 'animate-spin' : ''}`} />
</motion.button> </motion.button>
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-brand-500 to-violet-600 ring-2 ring-white/10" />
</div> </div>
</div>
</div>
</header>
{/* Mobile Navigation */}
<AnimatePresence>
{mobileMenuOpen && (
<motion.nav
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="md:hidden border-b border-white/5 bg-[#0a0a0f]/95 backdrop-blur-2xl overflow-hidden"
>
<div className="px-6 py-3 flex flex-col gap-1">
<a href="#" onClick={() => setMobileMenuOpen(false)} className="px-4 py-3 rounded-lg bg-brand-500 text-white text-sm font-medium flex items-center gap-3">
<LayoutDashboard className="w-4 h-4" />
Dashboard
</a>
<a href="/monitor" onClick={() => setMobileMenuOpen(false)} className="px-4 py-3 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 text-sm font-medium transition-all flex items-center gap-3">
<Activity className="w-4 h-4" />
Monitor
</a>
<a href="/financial" onClick={() => setMobileMenuOpen(false)} className="px-4 py-3 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 text-sm font-medium transition-all flex items-center gap-3">
<CreditCard className="w-4 h-4" />
Financeiro
</a>
</div>
</motion.nav>
)}
</AnimatePresence>
{/* Main Content */}
<main className="max-w-[1800px] mx-auto px-6 lg:px-8 py-8">
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
<motion.div <motion.div
key="dashboard" key="dashboard"
@@ -843,24 +803,18 @@ function App() {
</div> </div>
</motion.div> </motion.div>
</AnimatePresence> </AnimatePresence>
</main>
{/* Footer */} {/* Footer */}
<footer className="border-t border-white/5 mt-12"> <footer className="border-t border-white/5 mt-12">
<div className="max-w-[1800px] mx-auto px-6 lg:px-8 py-6"> <div className="flex items-center justify-between text-sm text-zinc-500 py-6">
<div className="flex items-center justify-between text-sm text-zinc-500">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" /> <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
<span>Dashboard Descomplicar v3.0</span> <span>Dashboard Descomplicar v3.0</span>
<span className="text-zinc-700">·</span>
<span>Painel de Gestão</span>
</div> </div>
<span>Actualizado: {new Date().toLocaleString('pt-PT')}</span> <span>Actualizado: {new Date().toLocaleString('pt-PT')}</span>
</div> </div>
</div>
</footer> </footer>
</div> </div>
</div>
) )
} }

269
src/components/Layout.tsx Normal file
View File

@@ -0,0 +1,269 @@
import { useState, useEffect } from 'react'
import { NavLink, Outlet } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import {
LayoutDashboard,
Activity,
CreditCard,
Zap,
ChevronLeft,
ChevronRight,
Menu,
X,
} from 'lucide-react'
const SIDEBAR_KEY = 'dash-sidebar-collapsed'
const MOBILE_BREAKPOINT = 768
interface NavItem {
to: string
label: string
icon: React.ElementType
}
const NAV_ITEMS: NavItem[] = [
{ to: '/', label: 'Dashboard', icon: LayoutDashboard },
{ to: '/monitor', label: 'Monitor', icon: Activity },
{ to: '/financial', label: 'Financeiro', icon: CreditCard },
]
function useIsMobile() {
const [isMobile, setIsMobile] = useState(
typeof window !== 'undefined' ? window.innerWidth < MOBILE_BREAKPOINT : false
)
useEffect(() => {
const onResize = () => setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
window.addEventListener('resize', onResize)
return () => window.removeEventListener('resize', onResize)
}, [])
return isMobile
}
function getInitialCollapsed(isMobile: boolean): boolean {
if (isMobile) return true
try {
const stored = localStorage.getItem(SIDEBAR_KEY)
if (stored !== null) return stored === 'true'
} catch {
// localStorage indisponivel
}
return false
}
export default function Layout() {
const isMobile = useIsMobile()
const [collapsed, setCollapsed] = useState(() => getInitialCollapsed(isMobile))
const [mobileOpen, setMobileOpen] = useState(false)
// Colapsar automaticamente em mobile
useEffect(() => {
if (isMobile) {
setCollapsed(true)
setMobileOpen(false)
}
}, [isMobile])
// Persistir estado em localStorage (apenas desktop)
useEffect(() => {
if (!isMobile) {
try {
localStorage.setItem(SIDEBAR_KEY, String(collapsed))
} catch {
// localStorage indisponivel
}
}
}, [collapsed, isMobile])
const toggleSidebar = () => {
if (isMobile) {
setMobileOpen(prev => !prev)
} else {
setCollapsed(prev => !prev)
}
}
const closeMobileMenu = () => setMobileOpen(false)
const sidebarWidth = collapsed ? 72 : 240
return (
<div className="min-h-screen bg-mesh">
<div className="bg-grid min-h-screen flex">
{/* Overlay mobile */}
<AnimatePresence>
{isMobile && mobileOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm"
onClick={closeMobileMenu}
/>
)}
</AnimatePresence>
{/* Sidebar */}
<AnimatePresence mode="wait">
{(!isMobile || mobileOpen) && (
<motion.aside
initial={isMobile ? { x: -240 } : false}
animate={{ x: 0 }}
exit={isMobile ? { x: -240 } : undefined}
transition={{ type: 'spring', stiffness: 400, damping: 35 }}
style={!isMobile ? { width: sidebarWidth } : undefined}
className={`
${isMobile
? 'fixed top-0 left-0 bottom-0 z-50 w-60'
: 'relative flex-shrink-0 z-30'
}
bg-[#0a0a0f]/95 backdrop-blur-2xl border-r border-white/5
flex flex-col transition-[width] duration-300 ease-in-out
`}
>
{/* Logo */}
<div className="flex items-center gap-3 px-4 py-5 border-b border-white/5 min-h-[72px]">
<motion.div
whileHover={{ scale: 1.05, rotate: 5 }}
className="w-10 h-10 rounded-xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shadow-lg shadow-brand-500/30 flex-shrink-0"
>
<Zap className="w-5 h-5 text-white" />
</motion.div>
<AnimatePresence>
{(!collapsed || isMobile) && (
<motion.div
initial={{ opacity: 0, width: 0 }}
animate={{ opacity: 1, width: 'auto' }}
exit={{ opacity: 0, width: 0 }}
transition={{ duration: 0.2 }}
className="overflow-hidden whitespace-nowrap"
>
<h1 className="text-base font-bold text-white tracking-tight leading-tight">Descomplicar</h1>
<p className="text-[10px] text-zinc-500">Painel de Gestao</p>
</motion.div>
)}
</AnimatePresence>
{/* Fechar em mobile */}
{isMobile && (
<button
onClick={closeMobileMenu}
className="ml-auto p-1.5 rounded-lg hover:bg-white/10 transition-colors"
>
<X className="w-5 h-5 text-zinc-400" />
</button>
)}
</div>
{/* Navegacao */}
<nav className="flex-1 px-3 py-4 space-y-1">
{NAV_ITEMS.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.to === '/'}
onClick={isMobile ? closeMobileMenu : undefined}
className={({ isActive }) => `
flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium
transition-all duration-200 group relative
${isActive
? 'bg-brand-500/15 text-white border border-brand-500/30'
: 'text-zinc-400 hover:text-white hover:bg-white/5 border border-transparent'
}
`}
>
{({ isActive }) => (
<>
<item.icon className={`w-5 h-5 flex-shrink-0 ${isActive ? 'text-brand-400' : 'text-zinc-500 group-hover:text-zinc-300'}`} />
<AnimatePresence>
{(!collapsed || isMobile) && (
<motion.span
initial={{ opacity: 0, width: 0 }}
animate={{ opacity: 1, width: 'auto' }}
exit={{ opacity: 0, width: 0 }}
transition={{ duration: 0.2 }}
className="overflow-hidden whitespace-nowrap"
>
{item.label}
</motion.span>
)}
</AnimatePresence>
{/* Tooltip quando colapsado (desktop) */}
{collapsed && !isMobile && (
<div className="absolute left-full ml-3 px-2.5 py-1.5 rounded-lg bg-zinc-800 text-white text-xs font-medium whitespace-nowrap opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 pointer-events-none shadow-xl border border-white/10 z-50">
{item.label}
</div>
)}
</>
)}
</NavLink>
))}
</nav>
{/* Toggle (apenas desktop) */}
{!isMobile && (
<div className="px-3 py-4 border-t border-white/5">
<button
onClick={toggleSidebar}
className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 transition-all text-zinc-400 hover:text-white"
title={collapsed ? 'Expandir sidebar' : 'Colapsar sidebar'}
>
{collapsed
? <ChevronRight className="w-4 h-4" />
: <ChevronLeft className="w-4 h-4" />
}
<AnimatePresence>
{!collapsed && (
<motion.span
initial={{ opacity: 0, width: 0 }}
animate={{ opacity: 1, width: 'auto' }}
exit={{ opacity: 0, width: 0 }}
transition={{ duration: 0.2 }}
className="text-xs font-medium overflow-hidden whitespace-nowrap"
>
Colapsar
</motion.span>
)}
</AnimatePresence>
</button>
</div>
)}
</motion.aside>
)}
</AnimatePresence>
{/* Conteudo principal */}
<div className="flex-1 min-w-0 flex flex-col">
{/* Header mobile com botao de menu */}
{isMobile && (
<header className="sticky top-0 z-30 border-b border-white/5 bg-[#0a0a0f]/90 backdrop-blur-2xl">
<div className="flex items-center gap-3 px-4 py-3">
<button
onClick={toggleSidebar}
className="p-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 transition-all"
>
<Menu className="w-5 h-5 text-zinc-400" />
</button>
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shadow-lg shadow-brand-500/20">
<Zap className="w-4 h-4 text-white" />
</div>
<span className="text-sm font-bold text-white">Descomplicar</span>
</div>
</div>
</header>
)}
{/* Outlet para as paginas */}
<main className="flex-1">
<Outlet />
</main>
</div>
</div>
</div>
)
}

View File

@@ -6,6 +6,7 @@ import './index.css'
import App from './App.tsx' import App from './App.tsx'
import Monitor from './pages/Monitor.tsx' import Monitor from './pages/Monitor.tsx'
import Financial from './pages/Financial.tsx' import Financial from './pages/Financial.tsx'
import Layout from './components/Layout.tsx'
import { oidcConfig } from './auth/config.ts' import { oidcConfig } from './auth/config.ts'
import { AuthWrapper } from './auth/AuthWrapper.tsx' import { AuthWrapper } from './auth/AuthWrapper.tsx'
@@ -15,10 +16,12 @@ createRoot(document.getElementById('root')!).render(
<BrowserRouter> <BrowserRouter>
<AuthWrapper> <AuthWrapper>
<Routes> <Routes>
<Route element={<Layout />}>
<Route path="/" element={<App />} /> <Route path="/" element={<App />} />
<Route path="/monitor" element={<Monitor />} /> <Route path="/monitor" element={<Monitor />} />
<Route path="/financial" element={<Financial />} /> <Route path="/financial" element={<Financial />} />
<Route path="/callback" element={<App />} /> <Route path="/callback" element={<App />} />
</Route>
</Routes> </Routes>
</AuthWrapper> </AuthWrapper>
</BrowserRouter> </BrowserRouter>

View File

@@ -1,20 +1,15 @@
import { useState, useEffect, useCallback } from 'react' import { useState, useEffect, useCallback } from 'react'
import { motion } from 'framer-motion' import { motion } from 'framer-motion'
import { Link } from 'react-router-dom'
import { import {
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
} from 'recharts' } from 'recharts'
import { import {
Zap,
RefreshCw, RefreshCw,
ArrowLeft,
TrendingUp, TrendingUp,
TrendingDown, TrendingDown,
DollarSign, DollarSign,
Receipt, Receipt,
PiggyBank, PiggyBank,
Activity,
LayoutDashboard,
} from 'lucide-react' } from 'lucide-react'
interface FinancialData { interface FinancialData {
@@ -105,7 +100,7 @@ export default function Financial() {
if (loading) { if (loading) {
return ( return (
<div className="min-h-screen bg-mesh flex items-center justify-center"> <div className="flex items-center justify-center py-20">
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center"> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center">
<DollarSign className="w-12 h-12 text-brand-400 mx-auto mb-4 animate-pulse" /> <DollarSign className="w-12 h-12 text-brand-400 mx-auto mb-4 animate-pulse" />
<p className="text-zinc-400">A carregar dados financeiros...</p> <p className="text-zinc-400">A carregar dados financeiros...</p>
@@ -127,26 +122,14 @@ export default function Financial() {
})) }))
return ( return (
<div className="min-h-screen bg-mesh"> <div className="max-w-[1600px] mx-auto px-6 lg:px-8 py-8">
<div className="bg-grid min-h-screen"> {/* Header com resumo e refresh */}
{/* Header */} <div className="flex items-center justify-between mb-6">
<header className="sticky top-0 z-50 border-b border-white/5 bg-[#0a0a0f]/90 backdrop-blur-2xl">
<div className="max-w-[1600px] mx-auto px-6 lg:px-8 py-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<motion.div
whileHover={{ scale: 1.05 }}
className="w-11 h-11 rounded-xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shadow-lg shadow-brand-500/30"
>
<Zap className="w-6 h-6 text-white" />
</motion.div>
<div> <div>
<h1 className="text-xl font-bold text-white tracking-tight">Financeiro</h1> <h2 className="text-xl font-bold text-white tracking-tight">Financeiro</h2>
<p className="text-xs text-zinc-500">Vendas e Despesas {new Date().getFullYear()}</p> <p className="text-xs text-zinc-500">Vendas e Despesas {new Date().getFullYear()}</p>
</div> </div>
</div> <div className="flex items-center gap-3">
<div className="flex items-center gap-4">
<span className={`px-4 py-2 rounded-full text-sm font-semibold ${lucroColor}`}> <span className={`px-4 py-2 rounded-full text-sm font-semibold ${lucroColor}`}>
{lucroLabel}: {formatEUR(Math.abs(data.lucro_ano))} {lucroLabel}: {formatEUR(Math.abs(data.lucro_ano))}
</span> </span>
@@ -159,27 +142,8 @@ export default function Financial() {
> >
<RefreshCw className={`w-5 h-5 text-zinc-400 ${refreshing ? 'animate-spin' : ''}`} /> <RefreshCw className={`w-5 h-5 text-zinc-400 ${refreshing ? 'animate-spin' : ''}`} />
</motion.button> </motion.button>
<Link
to="/monitor"
className="hidden md:flex items-center gap-2 px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-zinc-400 hover:text-white transition-all text-sm"
>
<Activity className="w-4 h-4" />
Monitor
</Link>
<Link
to="/"
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-zinc-400 hover:text-white transition-all text-sm"
>
<ArrowLeft className="w-4 h-4" />
<span className="hidden md:inline">Dashboard</span>
</Link>
</div> </div>
</div> </div>
</div>
</header>
{/* Main Content */}
<main className="max-w-[1600px] mx-auto px-6 lg:px-8 py-8">
<motion.div variants={containerVariants} initial="hidden" animate="show"> <motion.div variants={containerVariants} initial="hidden" animate="show">
{/* Summary Cards */} {/* Summary Cards */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-5 mb-8"> <div className="grid grid-cols-2 lg:grid-cols-4 gap-5 mb-8">
@@ -280,8 +244,6 @@ export default function Financial() {
</motion.div> </motion.div>
</div> </div>
</motion.div> </motion.div>
</main>
</div>
</div> </div>
) )
} }

View File

@@ -1,6 +1,5 @@
import { useState, useEffect, useCallback } from 'react' import { useState, useEffect, useCallback } from 'react'
import { motion } from 'framer-motion' import { motion } from 'framer-motion'
import { Link } from 'react-router-dom'
import { import {
Server, Server,
Wifi, Wifi,
@@ -11,13 +10,14 @@ import {
RefreshCw, RefreshCw,
CheckCircle2, CheckCircle2,
AlertTriangle, AlertTriangle,
XCircle,
Zap,
ArrowLeft,
Activity, Activity,
Clock, Clock,
TrendingUp,
Wrench, Wrench,
Code,
Network,
Cpu,
MemoryStick,
MonitorDot,
} from 'lucide-react' } from 'lucide-react'
// Types // Types
@@ -49,21 +49,95 @@ interface MonitorData {
} }
} }
interface VMConfig {
name: string
id: string
type: 'QEMU' | 'LXC'
ip: string
role: string
icon: React.ElementType
accent: string
accentBg: string
accentBorder: string
}
// VM definitions matching cluster architecture
const VM_CONFIG: Record<string, VMConfig> = {
'CWP Server': {
name: 'Server',
id: 'VM 100',
type: 'QEMU',
ip: '5.9.90.105',
role: 'CWP - hosting clientes',
icon: Server,
accent: 'text-emerald-400',
accentBg: 'bg-emerald-500/10',
accentBorder: 'border-emerald-500/20',
},
'EasyPanel': {
name: 'Easy',
id: 'VM 101',
type: 'QEMU',
ip: '5.9.90.70',
role: 'Docker Swarm - 46 servicos',
icon: Container,
accent: 'text-cyan-400',
accentBg: 'bg-cyan-500/10',
accentBorder: 'border-cyan-500/20',
},
'Dev': {
name: 'Dev',
id: 'CT 102',
type: 'LXC',
ip: '10.10.10.10',
role: 'Node.js, Docker, TypeScript',
icon: Code,
accent: 'text-violet-400',
accentBg: 'bg-violet-500/10',
accentBorder: 'border-violet-500/20',
},
'Gateway': {
name: 'Gateway',
id: 'VM 103',
type: 'QEMU',
ip: '5.9.90.69',
role: '26 MCPs, Nginx proxy',
icon: Network,
accent: 'text-amber-400',
accentBg: 'bg-amber-500/10',
accentBorder: 'border-amber-500/20',
},
}
// Animation variants // Animation variants
const containerVariants = { const containerVariants = {
hidden: { opacity: 0 }, hidden: { opacity: 0 },
show: { show: {
opacity: 1, opacity: 1,
transition: { staggerChildren: 0.05 } transition: { staggerChildren: 0.06 }
} }
} }
const itemVariants = { const itemVariants = {
hidden: { opacity: 0, y: 20 }, hidden: { opacity: 0, y: 20 },
show: { opacity: 1, y: 0 } show: {
opacity: 1,
y: 0,
transition: { type: 'spring' as const, stiffness: 300, damping: 30 }
}
}
// --- Sub-components ---
const StatusDot = ({ status }: { status: string }) => {
const color = (status === 'ok' || status === 'up')
? 'bg-emerald-400 shadow-[0_0_12px_rgba(16,185,129,0.6)]'
: status === 'warning'
? 'bg-amber-400 shadow-[0_0_12px_rgba(245,158,11,0.6)]'
: 'bg-red-400 shadow-[0_0_12px_rgba(239,68,68,0.6)] animate-pulse'
return <div className={`w-2.5 h-2.5 rounded-full ${color}`} />
} }
// Status Badge
const StatusBadge = ({ status }: { status: string }) => { const StatusBadge = ({ status }: { status: string }) => {
const styles: Record<string, string> = { const styles: Record<string, string> = {
ok: 'bg-emerald-500/20 text-emerald-400', ok: 'bg-emerald-500/20 text-emerald-400',
@@ -80,15 +154,17 @@ const StatusBadge = ({ status }: { status: string }) => {
) )
} }
// Progress Bar const ProgressBar = ({ percent, showLabel = true, size = 'md', inverted = false }: { percent: number; showLabel?: boolean; size?: 'sm' | 'md'; inverted?: boolean }) => {
const ProgressBar = ({ percent, showLabel = true }: { percent: number; showLabel?: boolean }) => { const color = inverted
const color = percent < 70 ? 'from-emerald-500 to-emerald-400' : percent < 85 ? 'from-amber-500 to-amber-400' : 'from-red-500 to-red-400' ? (percent > 90 ? 'from-emerald-500 to-emerald-400' : percent > 70 ? 'from-amber-500 to-amber-400' : 'from-red-500 to-red-400')
: (percent < 70 ? 'from-emerald-500 to-emerald-400' : percent < 85 ? 'from-amber-500 to-amber-400' : 'from-red-500 to-red-400')
const height = size === 'sm' ? 'h-1.5' : 'h-2'
return ( return (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="flex-1 h-2 bg-white/10 rounded-full overflow-hidden"> <div className={`flex-1 ${height} bg-white/10 rounded-full overflow-hidden`}>
<motion.div <motion.div
initial={{ width: 0 }} initial={{ width: 0 }}
animate={{ width: `${percent}%` }} animate={{ width: `${Math.min(percent, 100)}%` }}
transition={{ duration: 0.8, ease: 'easeOut' }} transition={{ duration: 0.8, ease: 'easeOut' }}
className={`h-full rounded-full bg-gradient-to-r ${color}`} className={`h-full rounded-full bg-gradient-to-r ${color}`}
/> />
@@ -98,19 +174,13 @@ const ProgressBar = ({ percent, showLabel = true }: { percent: number; showLabel
) )
} }
// Summary Card const MetricPill = ({ label, value, unit = '%' }: { label: string; value: number | string; unit?: string }) => (
const SummaryCard = ({ value, label, color, icon: Icon }: { value: number; label: string; color: string; icon: React.ElementType }) => ( <span className="text-xs bg-white/5 px-2 py-1 rounded">
<motion.div <span className="text-zinc-500">{label}</span>{' '}
variants={itemVariants} <span className="text-white font-medium">{value}{unit}</span>
className="glass-card p-6 text-center" </span>
>
<Icon className={`w-8 h-8 mx-auto mb-3 ${color}`} />
<div className={`text-4xl font-bold ${color}`}>{value}</div>
<div className="text-sm text-zinc-400 mt-1">{label}</div>
</motion.div>
) )
// Category Card
const CategoryCard = ({ const CategoryCard = ({
title, title,
icon: Icon, icon: Icon,
@@ -136,45 +206,129 @@ const CategoryCard = ({
</motion.div> </motion.div>
) )
// Monitor Item // Cluster Overview Hero
const MonitorItemRow = ({ item }: { item: MonitorItem }) => ( const ClusterHero = ({ data }: { data: MonitorData }) => {
<div className="flex items-center justify-between p-3 rounded-xl bg-white/[0.02] hover:bg-white/[0.05] transition-colors"> const clusterItem = data.items.server?.find(s => s.name === 'Cluster Proxmox')
<div className="flex-1"> const d = clusterItem?.details || {}
<div className="text-sm font-medium text-white">{item.name}</div>
{item.details && ( return (
<div className="flex flex-wrap gap-2 mt-2"> <motion.div variants={itemVariants} className="glass-card overflow-hidden col-span-full">
{item.details.cpu !== undefined && ( <div className="px-6 py-5 border-b border-white/5 flex items-center justify-between">
<span className="text-xs bg-white/5 px-2 py-1 rounded"> <div className="flex items-center gap-4">
<span className="text-zinc-500">CPU</span>{' '} <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shadow-lg shadow-brand-500/30">
<span className="text-white font-medium">{item.details.cpu}%</span> <MonitorDot className="w-6 h-6 text-white" />
</span>
)}
{item.details.ram !== undefined && (
<span className="text-xs bg-white/5 px-2 py-1 rounded">
<span className="text-zinc-500">RAM</span>{' '}
<span className="text-white font-medium">{item.details.ram}%</span>
</span>
)}
{item.details.disk !== undefined && (
<span className="text-xs bg-white/5 px-2 py-1 rounded">
<span className="text-zinc-500">Disco</span>{' '}
<span className="text-white font-medium">{item.details.disk}%</span>
</span>
)}
{item.details.response_time !== undefined && (
<span className="text-xs text-zinc-400">{item.details.response_time}s</span>
)}
{item.details.domain && (
<span className="text-xs text-zinc-500">{item.details.domain}</span>
)}
</div> </div>
)} <div>
<h2 className="text-lg font-bold text-white">Cluster Proxmox</h2>
<p className="text-xs text-zinc-500">cluster.descomplicar.pt - 5.9.90.75 - Hetzner AX162-R</p>
</div> </div>
<StatusBadge status={item.status} /> </div>
<div className="flex items-center gap-3">
<StatusDot status={data.overall} />
<span className={`text-sm font-medium ${
data.overall === 'ok' ? 'text-emerald-400' :
data.overall === 'warning' ? 'text-amber-400' : 'text-red-400'
}`}>
{data.overall === 'ok' ? 'Operacional' : data.overall === 'warning' ? 'Atencao' : 'Critico'}
</span>
</div>
</div>
<div className="p-6">
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4">
<StatMini icon={Cpu} label="CPU" value={d.cpu ? `${d.cpu}%` : '--'} />
<StatMini icon={MemoryStick} label="RAM" value="128 GB" sub="88 GB alocado" />
<StatMini icon={HardDrive} label="NVMe" value="950 GB" sub="RAID1" />
<StatMini icon={Database} label="HDD" value="16 TB" sub="backups + dados" />
<StatMini icon={Server} label="VMs" value="4" sub="3 QEMU + 1 LXC" />
<StatMini icon={CheckCircle2} label="OK" value={String(data.stats.total_ok)} color="text-emerald-400" />
<StatMini icon={AlertTriangle} label="Alertas" value={String(data.stats.total_warning + data.stats.total_critical)} color={data.stats.total_critical > 0 ? 'text-red-400' : data.stats.total_warning > 0 ? 'text-amber-400' : 'text-emerald-400'} />
</div>
</div>
</motion.div>
)
}
const StatMini = ({ icon: Icon, label, value, sub, color = 'text-white' }: {
icon: React.ElementType; label: string; value: string; sub?: string; color?: string
}) => (
<div className="text-center p-3 rounded-xl bg-white/[0.03]">
<Icon className="w-4 h-4 mx-auto mb-2 text-zinc-500" />
<div className={`text-lg font-bold ${color}`}>{value}</div>
<div className="text-xs text-zinc-500">{label}</div>
{sub && <div className="text-[10px] text-zinc-600 mt-0.5">{sub}</div>}
</div> </div>
) )
// Main Monitor Page // VM Card
const VMCard = ({ item, config }: { item?: MonitorItem; config: VMConfig }) => {
const Icon = config.icon
const d = item?.details || {}
const status = item?.status || 'ok'
return (
<motion.div
variants={itemVariants}
className={`glass-card overflow-hidden border ${config.accentBorder}`}
>
<div className="px-5 py-4 border-b border-white/5 flex items-center justify-between">
<div className="flex items-center gap-3">
<div className={`w-9 h-9 rounded-lg ${config.accentBg} flex items-center justify-center`}>
<Icon className={`w-5 h-5 ${config.accent}`} />
</div>
<div>
<div className="flex items-center gap-2">
<h3 className="text-sm font-bold text-white">{config.name}</h3>
<span className="text-[10px] text-zinc-600 font-mono">{config.id}</span>
</div>
<p className="text-xs text-zinc-500">{config.ip} - {config.type}</p>
</div>
</div>
<StatusBadge status={status} />
</div>
<div className="p-4 space-y-3">
<p className="text-xs text-zinc-400">{config.role}</p>
{d.cpu !== undefined && (
<div>
<div className="flex justify-between text-xs mb-1">
<span className="text-zinc-500">CPU</span>
<span className="text-white font-medium">{d.cpu}%</span>
</div>
<ProgressBar percent={Number(d.cpu)} showLabel={false} size="sm" />
</div>
)}
{d.ram !== undefined && (
<div>
<div className="flex justify-between text-xs mb-1">
<span className="text-zinc-500">RAM</span>
<span className="text-white font-medium">{d.ram}%</span>
</div>
<ProgressBar percent={Number(d.ram)} showLabel={false} size="sm" />
</div>
)}
{d.disk !== undefined && (
<div>
<div className="flex justify-between text-xs mb-1">
<span className="text-zinc-500">Disco</span>
<span className="text-white font-medium">{d.disk}%</span>
</div>
<ProgressBar percent={Number(d.disk)} showLabel={false} size="sm" />
</div>
)}
{d.load !== undefined && (
<div className="flex items-center gap-2 pt-1">
<MetricPill label="Load" value={d.load} unit="" />
</div>
)}
</div>
</motion.div>
)
}
// --- Main Component ---
export default function Monitor() { export default function Monitor() {
const [data, setData] = useState<MonitorData | null>(null) const [data, setData] = useState<MonitorData | null>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
@@ -188,7 +342,9 @@ export default function Monitor() {
const json = await response.json() const json = await response.json()
setData(json) setData(json)
} catch { } catch {
if (import.meta.env.DEV) {
setData(getMockData()) setData(getMockData())
}
} finally { } finally {
setLoading(false) setLoading(false)
setRefreshing(false) setRefreshing(false)
@@ -203,14 +359,10 @@ export default function Monitor() {
if (loading) { if (loading) {
return ( return (
<div className="min-h-screen bg-mesh flex items-center justify-center"> <div className="flex items-center justify-center py-20">
<motion.div <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center">
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-center"
>
<Activity className="w-12 h-12 text-brand-400 mx-auto mb-4 animate-pulse" /> <Activity className="w-12 h-12 text-brand-400 mx-auto mb-4 animate-pulse" />
<p className="text-zinc-400">A carregar monitorização...</p> <p className="text-zinc-400">A carregar monitorizacao...</p>
</motion.div> </motion.div>
</div> </div>
) )
@@ -218,8 +370,10 @@ export default function Monitor() {
if (!data) return null if (!data) return null
// Items já vêm agrupados por categoria da API const { items } = data
const groupedItems = data.items
// Match server items to VM config
const getVMItem = (name: string) => items.server?.find(s => s.name === name)
const overallColor = { const overallColor = {
ok: 'text-emerald-400 bg-emerald-500/20', ok: 'text-emerald-400 bg-emerald-500/20',
@@ -229,31 +383,19 @@ export default function Monitor() {
const overallLabel = { const overallLabel = {
ok: 'Operacional', ok: 'Operacional',
warning: 'Atenção', warning: 'Atencao',
critical: 'Crítico', critical: 'Critico',
}[data.overall] }[data.overall]
return ( return (
<div className="min-h-screen bg-mesh"> <div className="max-w-[1600px] mx-auto px-6 lg:px-8 py-8">
<div className="bg-grid min-h-screen"> {/* Header com status e refresh */}
{/* Header */} <div className="flex items-center justify-between mb-6">
<header className="sticky top-0 z-50 border-b border-white/5 bg-[#0a0a0f]/90 backdrop-blur-2xl">
<div className="max-w-[1600px] mx-auto px-6 lg:px-8 py-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<motion.div
whileHover={{ scale: 1.05 }}
className="w-11 h-11 rounded-xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shadow-lg shadow-brand-500/30"
>
<Zap className="w-6 h-6 text-white" />
</motion.div>
<div> <div>
<h1 className="text-xl font-bold text-white tracking-tight">Monitorização</h1> <h2 className="text-xl font-bold text-white tracking-tight">Monitorizacao</h2>
<p className="text-xs text-zinc-500">Sistemas Descomplicar</p> <p className="text-xs text-zinc-500">Cluster Proxmox Descomplicar</p>
</div> </div>
</div> <div className="flex items-center gap-3">
<div className="flex items-center gap-4">
<span className={`px-4 py-2 rounded-full text-sm font-semibold ${overallColor}`}> <span className={`px-4 py-2 rounded-full text-sm font-semibold ${overallColor}`}>
{overallLabel} {overallLabel}
</span> </span>
@@ -266,55 +408,48 @@ export default function Monitor() {
> >
<RefreshCw className={`w-5 h-5 text-zinc-400 ${refreshing ? 'animate-spin' : ''}`} /> <RefreshCw className={`w-5 h-5 text-zinc-400 ${refreshing ? 'animate-spin' : ''}`} />
</motion.button> </motion.button>
<Link
to="/financial"
className="hidden md:flex items-center gap-2 px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-zinc-400 hover:text-white transition-all text-sm"
>
<TrendingUp className="w-4 h-4" />
Financeiro
</Link>
<Link
to="/"
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-zinc-400 hover:text-white transition-all text-sm"
>
<ArrowLeft className="w-4 h-4" />
Dashboard
</Link>
</div> </div>
</div> </div>
</div> <motion.div variants={containerVariants} initial="hidden" animate="show">
</header>
{/* Main Content */} {/* Section 1: Cluster Overview */}
<main className="max-w-[1600px] mx-auto px-6 lg:px-8 py-8"> <ClusterHero data={data} />
<motion.div
variants={containerVariants} {/* Section 2: VM Grid */}
initial="hidden" <div className="grid grid-cols-1 md:grid-cols-2 gap-5 mt-6">
animate="show" {Object.entries(VM_CONFIG).map(([key, config]) => (
> <VMCard key={key} item={getVMItem(key)} config={config} />
{/* Summary Grid */} ))}
<div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-8">
<SummaryCard value={data.stats.total_ok} label="Operacionais" color="text-emerald-400" icon={CheckCircle2} />
<SummaryCard value={data.stats.total_warning} label="Avisos" color="text-amber-400" icon={AlertTriangle} />
<SummaryCard value={data.stats.total_critical} label="Críticos" color="text-red-400" icon={XCircle} />
</div> </div>
{/* Monitor Grid */} {/* Section 3: Detail Categories */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 mt-8">
{/* Servers */}
{groupedItems.server && ( {/* Sites WordPress */}
<CategoryCard title="Servidores" icon={Server} count={groupedItems.server.length}> {items.site && items.site.length > 0 && (
{groupedItems.server.map((item) => ( <CategoryCard title="Sites WordPress" icon={Globe} count={items.site.length}>
<MonitorItemRow key={item.id} item={item} /> {items.site.map((item) => (
<div key={item.id} className="flex items-center justify-between p-3 rounded-xl bg-white/[0.02] hover:bg-white/[0.05] transition-colors">
<div className="flex-1">
<div className="text-sm font-medium text-white">{item.name}</div>
<div className="flex gap-2 mt-1">
{item.details?.domain && <span className="text-xs text-zinc-500">{item.details.domain}</span>}
{item.details?.response_time !== undefined && (
<span className="text-xs text-zinc-600">{item.details.response_time}s</span>
)}
</div>
</div>
<StatusBadge status={item.status} />
</div>
))} ))}
</CategoryCard> </CategoryCard>
)} )}
{/* Services - Compact Grid */} {/* Servicos EasyPanel */}
{groupedItems.service && ( {items.service && items.service.length > 0 && (
<CategoryCard title="Serviços Críticos" icon={Wifi} count={groupedItems.service.length}> <CategoryCard title="Servicos" icon={Wifi} count={items.service.length}>
<div className="grid grid-cols-2 gap-x-3 gap-y-1.5"> <div className="grid grid-cols-2 gap-x-3 gap-y-1.5">
{groupedItems.service.map((item) => ( {items.service.map((item) => (
<div key={item.id} className="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-white/[0.04] transition-colors"> <div key={item.id} className="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-white/[0.04] transition-colors">
<div className={`w-2 h-2 rounded-full flex-shrink-0 ${ <div className={`w-2 h-2 rounded-full flex-shrink-0 ${
item.status === 'ok' || item.status === 'up' ? 'bg-emerald-400' : item.status === 'ok' || item.status === 'up' ? 'bg-emerald-400' :
@@ -327,49 +462,45 @@ export default function Monitor() {
</CategoryCard> </CategoryCard>
)} )}
{/* Sites */} {/* Containers EasyPanel */}
{groupedItems.site && ( {items.container && items.container[0] && (
<CategoryCard title="Sites WordPress" icon={Globe} count={groupedItems.site.length}> <CategoryCard title="Containers Docker" icon={Container}>
{groupedItems.site.map((item) => ( <div className="text-center py-4">
<MonitorItemRow key={item.id} item={item} />
))}
</CategoryCard>
)}
{/* Containers */}
{groupedItems.container && groupedItems.container[0] && (
<CategoryCard title="Containers EasyPanel" icon={Container}>
<div className="text-center py-6">
<div className="text-5xl font-bold text-emerald-400"> <div className="text-5xl font-bold text-emerald-400">
{groupedItems.container[0].details?.up || 0} {items.container[0].details?.up || 0}
</div> </div>
<div className="text-sm text-zinc-400 mt-2"> <div className="text-sm text-zinc-400 mt-2">
de {groupedItems.container[0].details?.total || 0} containers activos de {items.container[0].details?.total || 0} containers activos
</div> </div>
{(groupedItems.container[0].details?.down || 0) > 0 && ( {(items.container[0].details?.down || 0) > 0 && (
<div className="text-sm text-red-400 mt-2"> <div className="text-sm text-red-400 mt-1">
{groupedItems.container[0].details.down} containers em baixo {items.container[0].details.down} em baixo
</div> </div>
)} )}
<div className="mt-4 px-4"> <div className="mt-4 px-4">
<ProgressBar <ProgressBar
percent={Math.round((groupedItems.container[0].details?.up / groupedItems.container[0].details?.total) * 100) || 0} percent={Math.round((items.container[0].details?.up / items.container[0].details?.total) * 100) || 0}
showLabel={false} showLabel={false}
inverted
/> />
</div> </div>
</div> </div>
</CategoryCard> </CategoryCard>
)} )}
{/* Backups */} {/* Backups - 3 camadas */}
{groupedItems.backup && ( {items.backup && items.backup.length > 0 && (
<CategoryCard title="Backups" icon={Database} count={groupedItems.backup.length}> <CategoryCard title="Backups" icon={Database} count={items.backup.length}>
{groupedItems.backup.map((item) => ( {items.backup.map((item) => (
<div key={item.id} className="flex items-center justify-between p-3 rounded-xl bg-white/[0.02]"> <div key={item.id} className="flex items-center justify-between p-3 rounded-xl bg-white/[0.02]">
<div> <div>
<div className="text-sm font-medium text-white">{item.name}</div> <div className="text-sm font-medium text-white">{item.name}</div>
{item.details?.age_hours !== undefined && ( {item.details?.age_hours !== undefined && (
<div className="text-xs text-zinc-500 mt-1">Último: {item.details.age_hours}h</div> <div className="text-xs text-zinc-500 mt-1">
{item.details.age_hours < 1 ? 'Agora' :
item.details.age_hours < 24 ? `ha ${item.details.age_hours}h` :
`ha ${Math.floor(item.details.age_hours / 24)}d`}
</div>
)} )}
</div> </div>
<StatusBadge status={item.status} /> <StatusBadge status={item.status} />
@@ -379,9 +510,9 @@ export default function Monitor() {
)} )}
{/* Storage */} {/* Storage */}
{groupedItems.storage && ( {items.storage && items.storage.length > 0 && (
<CategoryCard title="Armazenamento" icon={HardDrive} count={groupedItems.storage.length}> <CategoryCard title="Storage" icon={HardDrive} count={items.storage.length}>
{groupedItems.storage.map((item) => ( {items.storage.map((item) => (
<div key={item.id} className="p-3 rounded-xl bg-white/[0.02]"> <div key={item.id} className="p-3 rounded-xl bg-white/[0.02]">
<div className="flex items-center justify-between mb-2"> <div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium text-white">{item.name}</span> <span className="text-sm font-medium text-white">{item.name}</span>
@@ -395,21 +526,20 @@ export default function Monitor() {
</CategoryCard> </CategoryCard>
)} )}
{/* Maintenance */} {/* Manutencao */}
{groupedItems.maintenance && groupedItems.maintenance[0] && (() => { {items.maintenance && items.maintenance[0] && (() => {
const m = groupedItems.maintenance[0] const m = items.maintenance[0]
const d = m.details || {} const d = m.details || {}
const ageH = d.age_hours ?? 0 const ageH = d.age_hours ?? 0
const ageDays = Math.floor(ageH / 24) const ageLabel = ageH < 1 ? 'agora' : ageH < 24 ? `ha ${ageH}h` : `ha ${Math.floor(ageH / 24)}d`
const ageLabel = ageH < 24 ? `${ageH}h` : `${ageDays}d`
const actions = (d.logs_truncated || 0) + (d.images_removed || 0) + (d.orphan_volumes || 0) + (d.tmp_cleaned || 0) const actions = (d.logs_truncated || 0) + (d.images_removed || 0) + (d.orphan_volumes || 0) + (d.tmp_cleaned || 0)
return ( return (
<CategoryCard title="Manutenção" icon={Wrench}> <CategoryCard title="Manutencao" icon={Wrench}>
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center justify-between p-3 rounded-xl bg-white/[0.02]"> <div className="flex items-center justify-between p-3 rounded-xl bg-white/[0.02]">
<div> <div>
<div className="text-sm font-medium text-white">Auto-Cleanup</div> <div className="text-sm font-medium text-white">Auto-Cleanup</div>
<div className="text-xs text-zinc-500 mt-1">Último: {ageLabel}</div> <div className="text-xs text-zinc-500 mt-1">Ultimo: {ageLabel}</div>
</div> </div>
<StatusBadge status={m.status} /> <StatusBadge status={m.status} />
</div> </div>
@@ -436,112 +566,138 @@ export default function Monitor() {
) )
})()} })()}
{/* WP Updates */} {/* WP Updates - per-site detail from 'site' category */}
{groupedItems.wp_update && groupedItems.wp_update[0] && ( {(() => {
<CategoryCard title="WordPress Updates" icon={Globe}> const sites = items.site || []
<div className="text-center py-6"> const sitesWithUpdates = sites.filter((s: MonitorItem) => {
{(groupedItems.wp_update[0].details?.manual_updates || 0) > 0 ? ( const counts = s.details?.updates?.counts
return counts && counts.total > 0
})
const totalUpdates = sitesWithUpdates.reduce((sum: number, s: MonitorItem) => sum + (s.details?.updates?.counts?.total || 0), 0)
const wpAgg = items.wp_update?.[0]
return (
<CategoryCard title="WordPress Updates" icon={Globe} count={sitesWithUpdates.length > 0 ? sitesWithUpdates.length : undefined}>
{sitesWithUpdates.length > 0 ? (
<> <>
<div className="text-5xl font-bold text-amber-400"> <div className="text-center pb-3">
{groupedItems.wp_update[0].details.manual_updates} <div className="text-3xl font-bold text-amber-400">{totalUpdates}</div>
<div className="text-xs text-zinc-500 mt-1">updates em {sitesWithUpdates.length} sites</div>
</div> </div>
<div className="text-sm text-zinc-400 mt-2"> {sitesWithUpdates.map((site: MonitorItem) => {
plugins precisam update manual const counts = site.details?.updates?.counts || {}
return (
<div key={site.id} className="p-3 rounded-xl bg-white/[0.02]">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-white">{site.name}</span>
<span className="text-xs font-semibold text-amber-400">{counts.total} updates</span>
</div> </div>
<div className="flex gap-3 mt-1">
{counts.plugins > 0 && <span className="text-xs text-zinc-500">{counts.plugins} plugins</span>}
{counts.themes > 0 && <span className="text-xs text-zinc-500">{counts.themes} temas</span>}
{(counts.core || 0) > 0 && <span className="text-xs text-red-400">{counts.core} core</span>}
</div>
</div>
)
})}
</> </>
) : wpAgg && (wpAgg.details?.manual_updates || 0) > 0 ? (
<div className="text-center py-4">
<div className="text-4xl font-bold text-amber-400">{wpAgg.details.manual_updates}</div>
<div className="text-sm text-zinc-400 mt-2">plugins precisam update</div>
<div className="text-xs text-zinc-600 mt-2">Sem detalhe por site disponivel</div>
</div>
) : ( ) : (
<> <div className="text-center py-4">
<CheckCircle2 className="w-12 h-12 text-emerald-400 mx-auto" /> <CheckCircle2 className="w-12 h-12 text-emerald-400 mx-auto" />
<div className="text-sm text-zinc-400 mt-2">Tudo actualizado</div> <div className="text-sm text-zinc-400 mt-2">Tudo actualizado</div>
</>
)}
</div> </div>
</CategoryCard>
)} )}
</CategoryCard>
)
})()}
</div> </div>
{/* Footer */} {/* Footer */}
<div className="flex items-center justify-center gap-2 mt-8 text-sm text-zinc-500"> <div className="flex items-center justify-center gap-2 mt-8 text-sm text-zinc-500">
<Clock className="w-4 h-4" /> <Clock className="w-4 h-4" />
<span>Última actualização: {new Date().toLocaleTimeString('pt-PT')}</span> <span>Ultima actualizacao: {new Date().toLocaleTimeString('pt-PT')}</span>
<span className="text-zinc-700">·</span> <span className="text-zinc-700">·</span>
<span>Auto-refresh: 60s</span> <span>Auto-refresh: 60s</span>
</div> </div>
</motion.div> </motion.div>
</main>
</div>
</div> </div>
) )
} }
// Mock data // Mock data reflecting new cluster architecture
function getMockData(): MonitorData { function getMockData(): MonitorData {
const mockItems: Record<string, MonitorItem[]> = { const mockItems: Record<string, MonitorItem[]> = {
server: [ server: [
{ id: 5, name: 'CWP Server', category: 'server', status: 'up', details: { cpu: 7.3, ram: 10.2, disk: 39 }, last_check: '' }, { id: 1, name: 'Cluster Proxmox', category: 'server', status: 'ok', details: { cpu: 12.5 }, last_check: '' },
{ id: 6, name: 'EasyPanel', category: 'server', status: 'up', details: { cpu: 20.5, ram: 20.2, disk: 41 }, last_check: '' }, { id: 100, name: 'CWP Server', category: 'server', status: 'ok', details: { cpu: 7.3, ram: 25.1, disk: 39, load: 0.42 }, last_check: '' },
{ id: 296, name: 'MCP Hub', category: 'server', status: 'up', details: { cpu: 1.0, load: 0.0 }, last_check: '' }, { id: 101, name: 'EasyPanel', category: 'server', status: 'ok', details: { cpu: 20.5, ram: 53.1, disk: 41, load: 1.2 }, last_check: '' },
{ id: 297, name: 'Meet', category: 'server', status: 'up', details: { cpu: 4.7, load: 0.0 }, last_check: '' }, { id: 102, name: 'Dev', category: 'server', status: 'ok', details: { cpu: 3.0, ram: 18.5, disk: 28 }, last_check: '' },
{ id: 298, name: 'WhatsApp', category: 'server', status: 'up', details: { cpu: 3.0, load: 0.04 }, last_check: '' }, { id: 103, name: 'Gateway', category: 'server', status: 'ok', details: { cpu: 5.2, ram: 42.0, disk: 52, load: 0.3 }, last_check: '' },
{ id: 299, name: 'WhatSMS', category: 'server', status: 'up', details: { cpu: 2.1, load: 0.08 }, last_check: '' },
], ],
service: [ service: [
{ id: 1, name: 'Planeamento EAL', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 1, name: 'Desk CRM', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 2, name: 'Desk CRM', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 2, name: 'N8N', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 3, name: 'Automator N8N', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 3, name: 'Gitea', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 4, name: 'NextCloud', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 4, name: 'WikiJS', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 517, name: 'Gitea', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 5, name: 'Authentik', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 518, name: 'Meet Jitsi', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 6, name: 'Metabase', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 519, name: 'WikiJS', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 7, name: 'NextCloud', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 521, name: 'Google Docs', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 8, name: 'Syncthing', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 549, name: 'MCP Hub', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 9, name: 'MCP Gateway', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 515, name: 'WhatSMS', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 10, name: 'Outline', category: 'service', status: 'up', details: {}, last_check: '' },
{ id: 41594, name: 'Syncthing', category: 'service', status: 'up', details: {}, last_check: '' }, { id: 11, name: 'Penpot', category: 'service', status: 'warning', details: {}, last_check: '' },
{ id: 12, name: 'WhatSMS', category: 'service', status: 'up', details: {}, last_check: '' },
], ],
site: [ site: [
{ id: 15960, name: 'Descomplicar', category: 'site', status: 'up', details: { domain: 'descomplicar.pt', response_time: 0.093 }, last_check: '' }, { id: 1, name: 'Descomplicar', category: 'site', status: 'up', details: { domain: 'descomplicar.pt', response_time: 0.093 }, last_check: '' },
{ id: 15961, name: 'Emanuel Almeida', category: 'site', status: 'up', details: { domain: 'emanuelalmeida.pt', response_time: 1.687 }, last_check: '' }, { id: 2, name: 'Emanuel Almeida', category: 'site', status: 'up', details: { domain: 'emanuelalmeida.pt', response_time: 1.687 }, last_check: '' },
{ id: 15959, name: 'Family Clinic', category: 'site', status: 'up', details: { domain: 'familyclinic.pt', response_time: 2.712 }, last_check: '' }, { id: 3, name: 'Family Clinic', category: 'site', status: 'up', details: { domain: 'familyclinic.pt', response_time: 2.712 }, last_check: '' },
{ id: 15962, name: 'WTC', category: 'site', status: 'up', details: { domain: 'wtc-group.com' }, last_check: '' }, { id: 4, name: 'WTC', category: 'site', status: 'up', details: { domain: 'wtc-group.com' }, last_check: '' },
{ id: 15963, name: 'Carstuff', category: 'site', status: 'down', details: { domain: 'carstuff.pt' }, last_check: '' }, { id: 5, name: 'Carstuff', category: 'site', status: 'down', details: { domain: 'carstuff.pt' }, last_check: '' },
{ id: 15964, name: 'Espiral Senior', category: 'site', status: 'up', details: { domain: 'espiralsenior.pt' }, last_check: '' }, { id: 6, name: 'Espiral Senior', category: 'site', status: 'up', details: { domain: 'espiralsenior.pt' }, last_check: '' },
{ id: 15965, name: 'Karate Gaia', category: 'site', status: 'up', details: { domain: 'karategaia.pt' }, last_check: '' }, { id: 7, name: 'Karate Gaia', category: 'site', status: 'up', details: { domain: 'karategaia.pt' }, last_check: '' },
], ],
container: [ container: [
{ id: 7, name: 'EasyPanel Containers', category: 'container', status: 'warning', details: { up: 83, total: 87, down: 4 }, last_check: '' }, { id: 1, name: 'Docker Swarm', category: 'container', status: 'ok', details: { up: 44, total: 46, down: 2 }, last_check: '' },
], ],
backup: [ backup: [
{ id: 15967, name: 'MySQL Hourly', category: 'backup', status: 'ok', details: { age_hours: 1 }, last_check: '' }, { id: 1, name: 'Proxmox vzdump', category: 'backup', status: 'ok', details: { age_hours: 8 }, last_check: '' },
{ id: 15968, name: 'CWP Accounts', category: 'backup', status: 'warning', details: { age_hours: 48 }, last_check: '' }, { id: 2, name: 'CWP Accounts', category: 'backup', status: 'ok', details: { age_hours: 18 }, last_check: '' },
{ id: 15969, name: 'Easy Backup', category: 'backup', status: 'ok', details: { age_hours: 12 }, last_check: '' }, { id: 3, name: 'MySQL Hourly', category: 'backup', status: 'ok', details: { age_hours: 1 }, last_check: '' },
{ id: 15970, name: 'Server->Easy Sync', category: 'backup', status: 'failed', details: { age_hours: 72 }, last_check: '' },
], ],
storage: [ storage: [
{ id: 15971, name: 'gordo', category: 'storage', status: 'ok', details: { used: '89GB', total: '200GB', percent: 45 }, last_check: '' }, { id: 1, name: 'NVMe RAID1 (vg0)', category: 'storage', status: 'ok', details: { used: '650GB', total: '950GB', percent: 68 }, last_check: '' },
{ id: 15972, name: 'gordito', category: 'storage', status: 'ok', details: { used: '42GB', total: '100GB', percent: 42 }, last_check: '' }, { id: 2, name: 'HDD pbs-local', category: 'storage', status: 'ok', details: { used: '2.9TB', total: '6TB', percent: 49 }, last_check: '' },
], { id: 3, name: 'HDD vm-storage', category: 'storage', status: 'ok', details: { used: '480GB', total: '8.5TB', percent: 6 }, last_check: '' },
wp_update: [
{ id: 25, name: 'WordPress Plugins', category: 'wp_update', status: 'warning', details: { manual_updates: 3 }, last_check: '' },
], ],
maintenance: [ maintenance: [
{ id: 48558, name: 'EasyPanel Cleanup', category: 'maintenance', status: 'ok', details: { age_hours: 0, disk_percent: 15, freed_mb: 0, logs_truncated: 0, images_removed: 0, orphan_volumes: 0, tmp_cleaned: 0 }, last_check: '' }, { id: 1, name: 'EasyPanel Cleanup', category: 'maintenance', status: 'ok', details: { age_hours: 2, disk_percent: 41, freed_mb: 128, logs_truncated: 3, images_removed: 5, orphan_volumes: 0, tmp_cleaned: 1 }, last_check: '' },
],
wp_update: [
{ id: 1, name: 'WordPress Plugins', category: 'wp_update', status: 'ok', details: { manual_updates: 0 }, last_check: '' },
], ],
} }
return { return {
overall: 'warning', overall: 'warning',
summary: [ summary: [
{ category: 'server', total: 6, ok: 6, warning: 0, critical: 0 }, { category: 'server', total: 5, ok: 5, warning: 0, critical: 0 },
{ category: 'service', total: 11, ok: 11, warning: 0, critical: 0 }, { category: 'service', total: 12, ok: 11, warning: 1, critical: 0 },
{ category: 'site', total: 7, ok: 6, warning: 0, critical: 1 }, { category: 'site', total: 7, ok: 6, warning: 0, critical: 1 },
{ category: 'container', total: 1, ok: 0, warning: 1, critical: 0 }, { category: 'container', total: 1, ok: 1, warning: 0, critical: 0 },
{ category: 'backup', total: 4, ok: 2, warning: 1, critical: 1 }, { category: 'backup', total: 3, ok: 3, warning: 0, critical: 0 },
{ category: 'storage', total: 2, ok: 2, warning: 0, critical: 0 }, { category: 'storage', total: 3, ok: 3, warning: 0, critical: 0 },
], ],
stats: { stats: {
total_ok: 26, total_ok: 30,
total_warning: 2, total_warning: 1,
total_critical: 2 total_critical: 1
}, },
items: mockItems, items: mockItems,
} }

5
src/test/setup.ts Normal file
View File

@@ -0,0 +1,5 @@
/**
* Vitest Setup File
* Configura @testing-library/jest-dom matchers
*/
import '@testing-library/jest-dom'

47
src/test/utils.test.ts Normal file
View File

@@ -0,0 +1,47 @@
/**
* Utility Functions Tests
* Testes básicos para demonstrar setup de testes (Vulnerabilidade 4.3)
*/
import { describe, it, expect } from 'vitest'
// Helper functions para testes
function formatCurrency(value: number): string {
return `${value}EUR`
}
function calculatePercentage(value: number, total: number): number {
if (total === 0) return 0
return Math.round((value / total) * 100)
}
describe('Utility Functions', () => {
describe('formatCurrency', () => {
it('should format positive numbers', () => {
expect(formatCurrency(100)).toBe('100EUR')
})
it('should format negative numbers', () => {
expect(formatCurrency(-50)).toBe('-50EUR')
})
it('should format zero', () => {
expect(formatCurrency(0)).toBe('0EUR')
})
})
describe('calculatePercentage', () => {
it('should calculate percentage correctly', () => {
expect(calculatePercentage(25, 100)).toBe(25)
expect(calculatePercentage(50, 200)).toBe(25)
})
it('should handle zero total', () => {
expect(calculatePercentage(10, 0)).toBe(0)
})
it('should round to nearest integer', () => {
expect(calculatePercentage(33, 100)).toBe(33)
expect(calculatePercentage(66, 100)).toBe(66)
})
})
})

23
vitest.config.ts Normal file
View File

@@ -0,0 +1,23 @@
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
css: true,
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: [
'node_modules/',
'src/test/',
'**/*.config.ts',
'**/dist/',
'**/*.d.ts'
]
}
},
})