feat(setup): T01 create project directory structure

- Create src/openrouter_monitor/ package structure
- Create models/, routers/, services/, utils/ subpackages
- Create tests/unit/ and tests/integration/ structure
- Create alembic/, docs/, scripts/ directories
- Add test_project_structure.py with 13 unit tests
- All tests passing (13/13)

Refs: T01
This commit is contained in:
Luca Sacchi Ricciardi
2026-04-07 09:44:41 +02:00
parent 849a65d4d9
commit 75f40acb17
27 changed files with 3094 additions and 0 deletions

333
prd.md Normal file
View File

@@ -0,0 +1,333 @@
# Product Requirements Document (PRD)
## OpenRouter API Key Monitor
---
## 1. Panoramica
### 1.1 Descrizione
OpenRouter API Key Monitor e un applicazione web multi-utente che permette agli utenti di monitorare l utilizzo delle loro API key della piattaforma OpenRouter. L applicazione raccoglie statistiche d uso, le persiste in un database SQLite e fornisce sia un interfaccia web che un API programmatica per l accesso ai dati.
### 1.2 Obiettivi
- Fornire una dashboard centralizzata per il monitoraggio delle API key OpenRouter
- Permettere a piu utenti di gestire le proprie chiavi in modo indipendente
- Offrire API programmatica per integrazioni esterne
- Persistere i dati storici per analisi nel tempo
### 1.3 Target Utenti
- Sviluppatori che utilizzano API OpenRouter
- Team che gestiscono multiple API key
- Utenti che necessitano di reportistica sull utilizzo
---
## 2. Requisiti Funzionali
### 2.1 Gestione Utenti (Multi-utente)
#### 2.1.1 Registrazione
- **F-001**: Gli utenti devono potersi registrare con email e password
- **F-002**: La password deve essere salvata in modo sicuro (hash)
- **F-003**: Email deve essere univoca nel sistema
- **F-004**: Validazione formato email
#### 2.1.2 Autenticazione
- **F-005**: Login con email e password
- **F-006**: Gestione sessione utente (JWT o session-based)
- **F-007**: Logout funzionante
- **F-008**: Protezione route autenticate
#### 2.1.3 Profilo Utente
- **F-009**: Visualizzazione profilo personale
- **F-010**: Modifica password
- **F-011**: Eliminazione account con conferma
### 2.2 Gestione API Key
#### 2.2.1 CRUD API Key
- **F-012**: Aggiungere nuova API key OpenRouter
- **F-013**: Visualizzare lista API key dell utente
- **F-014**: Modificare nome/descrizione API key
- **F-015**: Eliminare API key
- **F-016**: API key devono essere cifrate nel database
#### 2.2.2 Validazione
- **F-017**: Verifica validita API key con chiamata test a OpenRouter
- **F-018**: Visualizzare stato attivo/inattivo per ogni key
### 2.3 Monitoraggio e Statistiche
#### 2.3.1 Raccolta Dati
- **F-019**: Sincronizzazione automatica statistiche da OpenRouter API
- **F-020**: Storico utilizzo (richieste, token, costi)
- **F-021**: Aggregazione dati per modello LLM utilizzato
#### 2.3.2 Dashboard
- **F-022**: Vista panoramica utilizzo totale
- **F-023**: Grafico utilizzo nel tempo (ultimi 30 giorni)
- **F-024**: Distribuzione utilizzo per modello
- **F-025**: Costi totali e medi
- **F-026**: Numero richieste totali e giornaliere medie
#### 2.3.3 Report Dettagliati
- **F-027**: Filtraggio per intervallo date
- **F-028**: Filtraggio per API key specifica
- **F-029**: Filtraggio per modello
- **F-030**: Esportazione dati (CSV/JSON)
### 2.4 API Pubblica
#### 2.4.1 Autenticazione API
- **F-031**: Generazione API token per accesso programmatico
- **F-032**: Revoca API token
- **F-033**: Autenticazione via Bearer token
#### 2.4.2 Endpoint
- **F-034**: GET /api/v1/stats - statistiche aggregate (solo lettura)
- **F-035**: GET /api/v1/usage - dati di utilizzo dettagliati (solo lettura)
- **F-036**: GET /api/v1/keys - lista API key con statistiche (solo lettura)
- **F-037**: Rate limiting su API pubblica
#### 2.4.3 Risposte
- **F-038**: Formato JSON standardizzato
- **F-039**: Gestione errori con codici HTTP appropriati
- **F-040**: Paginazione per risultati grandi
---
## 3. Requisiti Non Funzionali
### 3.1 Performance
- **NF-001**: Tempo di risposta web < 2 secondi
- **NF-002**: API response time < 500ms
- **NF-003**: Supporto per almeno 100 utenti concorrenti
### 3.2 Sicurezza
- **NF-004**: Tutte le API key cifrate in database (AES-256)
- **NF-005**: Password hash con bcrypt/Argon2
- **NF-006**: HTTPS obbligatorio in produzione
- **NF-007**: Protezione CSRF
- **NF-008**: Rate limiting su endpoint di autenticazione
- **NF-009**: SQL injection prevention (query parameterizzate)
- **NF-010**: XSS prevention
### 3.3 Affidabilita
- **NF-011**: Backup automatico database SQLite
- **NF-012**: Gestione errori graceful degradation
- **NF-013**: Logging operazioni critiche
### 3.4 Usabilita
- **NF-014**: Interfaccia responsive (mobile-friendly)
- **NF-015**: Tema chiaro/scuro
- **NF-016**: Messaggi di errore chiari
### 3.5 Manutenibilita
- **NF-017**: Codice documentato
- **NF-018**: Test coverage >= 90%
- **NF-019**: Struttura modulare
---
## 4. Architettura Tecnica
### 4.1 Stack Tecnologico
- **Backend**: Python 3.11+ con FastAPI
- **Frontend**: HTML + HTMX / React (opzionale)
- **Database**: SQLite
- **ORM**: SQLAlchemy
- **Autenticazione**: JWT
- **Task Background**: APScheduler / Celery (opzionale)
### 4.2 Struttura Database
#### Tabella: users
- id (PK, INTEGER)
- email (UNIQUE, TEXT)
- password_hash (TEXT)
- created_at (TIMESTAMP)
- updated_at (TIMESTAMP)
- is_active (BOOLEAN)
#### Tabella: api_keys
- id (PK, INTEGER)
- user_id (FK, INTEGER)
- name (TEXT)
- key_encrypted (TEXT)
- is_active (BOOLEAN)
- created_at (TIMESTAMP)
- last_used_at (TIMESTAMP)
#### Tabella: usage_stats
- id (PK, INTEGER)
- api_key_id (FK, INTEGER)
- date (DATE)
- model (TEXT)
- requests_count (INTEGER)
- tokens_input (INTEGER)
- tokens_output (INTEGER)
- cost (DECIMAL)
- created_at (TIMESTAMP)
#### Tabella: api_tokens
- id (PK, INTEGER)
- user_id (FK, INTEGER)
- token_hash (TEXT)
- name (TEXT)
- last_used_at (TIMESTAMP)
- created_at (TIMESTAMP)
- is_active (BOOLEAN)
### 4.3 Integrazione OpenRouter
- API Endpoint: https://openrouter.ai/api/v1/
- Endpoint utilizzati:
- /auth/key - per validazione key
- /credits - per controllo crediti
- (future estensioni per usage stats quando disponibili)
---
## 5. Interfaccia Utente
### 5.1 Pagine Web
#### 5.1.1 Pubbliche
- **Login** (/login) - Form di accesso
- **Registrazione** (/register) - Form di registrazione
#### 5.1.2 Autenticate
- **Dashboard** (/dashboard) - Panoramica utilizzo
- **API Keys** (/keys) - Gestione API key
- **Statistiche** (/stats) - Report dettagliati
- **Profilo** (/profile) - Gestione account
- **API Tokens** (/tokens) - Gestione token API
### 5.2 Componenti UI
#### 5.2.1 Dashboard
- Card riepilogative (richieste totali, costi, etc.)
- Grafici utilizzo temporale
- Tabella modelli piu utilizzati
#### 5.2.2 Gestione API Key
- Tabella con nome, stato, ultimo utilizzo
- Form aggiunta/modifica
- Bottone test validita
- Bottone eliminazione con conferma
#### 5.2.3 Statistiche
- Filtri per data, key, modello
- Tabella dettagliata
- Bottone esportazione
---
## 6. API Endpoints (Dettaglio)
### 6.1 Web Routes (HTML)
- GET / - redirect a /dashboard o /login
- GET/POST /login
- GET/POST /register
- GET /logout
- GET /dashboard (protetta)
- GET /keys (protetta)
- GET /stats (protetta)
- GET /profile (protetta)
- GET /tokens (protetta)
### 6.2 API Routes (JSON)
- POST /api/auth/login
- POST /api/auth/register
- POST /api/auth/logout
- GET /api/v1/stats (auth: Bearer token)
- GET /api/v1/usage (auth: Bearer token)
- GET /api/v1/keys (auth: Bearer token)
---
## 7. Cron e Background Tasks
### 7.1 Sincronizzazione Dati
- **Task**: Sync Usage Data
- **Frequenza**: Ogni ora
- **Azione**: Recupera statistiche da OpenRouter per ogni key attiva
- **Persistenza**: Salva in usage_stats
### 7.2 Validazione API Key
- **Task**: Validate Keys
- **Frequenza**: Giornaliera
- **Azione**: Verifica validita di ogni key, aggiorna stato
### 7.3 Cleanup
- **Task**: Cleanup Old Data
- **Frequenza**: Settimanale
- **Azione**: Rimuove dati piu vecchi di 1 anno (configurabile)
---
## 8. Configurazione
### 8.1 Variabili d Ambiente
- DATABASE_URL - path database SQLite
- SECRET_KEY - chiave per JWT
- ENCRYPTION_KEY - chiave per cifratura API key
- OPENROUTER_API_URL - URL base API OpenRouter
- SYNC_INTERVAL_MINUTES - intervallo sincronizzazione
- MAX_API_KEYS_PER_USER - limite key per utente
- RATE_LIMIT_REQUESTS - limite richieste API
- RATE_LIMIT_WINDOW - finestra rate limit (secondi)
### 8.2 File Configurazione
- config.yaml (opzionale) - override env vars
---
## 9. Deployment
### 9.1 Requisiti
- Python 3.11+
- SQLite
- (Opzionale) Reverse proxy (nginx/traefik)
### 9.2 Installazione
1. Clone repository
2. pip install -r requirements.txt
3. Configura variabili d ambiente
4. Esegui migrazioni: alembic upgrade head
5. Avvia: uvicorn main:app
### 9.3 Docker (Opzionale)
- Dockerfile fornito
- docker-compose.yml per stack completo
---
## 10. Roadmap
### Fase 1 (MVP)
- [ ] Autenticazione utenti
- [ ] CRUD API key
- [ ] Dashboard base
- [ ] API lettura dati
### Fase 2
- [ ] Grafici avanzati
- [ ] Esportazione dati
- [ ] Notifiche (email)
- [ ] Rate limiting avanzato
### Fase 3
- [ ] Supporto multi-team
- [ ] RBAC (Ruoli)
- [ ] Webhook
- [ ] Mobile app
---
## 11. Note
- L applicazione e progettata per essere self-hosted
- I dati rimangono locali (SQLite)
- L integrazione con OpenRouter richiede API key valide
- Le API key degli utenti sono sempre cifrate nel database