feat: update frontend path to '/badge' and adjust related documentation

This commit is contained in:
EmanueleAlfano
2026-02-04 13:12:15 +01:00
parent 77bea025fa
commit 458b074f45
10 changed files with 471 additions and 37 deletions

292
CHANGE_BASE_PATH.md Normal file
View File

@@ -0,0 +1,292 @@
# 🔧 Guida: Come Cambiare il Path Base dell'Applicazione
## Contesto
Il sistema Focolari Voting è composto da:
- **Backend** (FastAPI) che serve sia le API REST che il frontend statico
- **Frontend** (React SPA) che viene buildato e servito dal backend
Attualmente il frontend è servito su: **`/badge`**
---
## 📍 Configurazione Attuale
### Backend serve su:
- **API**: `http://localhost:8000/api/info-room`, `/api/login-validate`, `/api/anagrafica/{badge}`, `/api/entry-request`
- **Frontend**: `http://localhost:8000/badge`
- **Debug page**: `http://localhost:8000/badge/debug`
### Frontend in sviluppo:
- Vite dev server su `http://localhost:5173` (qualsiasi base path)
- Proxy `/api/*` verso `http://127.0.0.1:8000`
---
## 🔄 Come Cambiare il Path Base
Se in futuro vuoi servire il frontend su un path diverso (es. `/votazioni`, `/app`, `/` per la root), segui questi passaggi:
### 1⃣ Backend - `backend-mock/main.py`
**File**: `/backend-mock/main.py`
**Cerca le route del frontend** (circa linea 94-114):
```python
# Serve index.html su /badge e sue sub-route
@app.get("/badge")
async def serve_badge_index():
return FileResponse(STATIC_DIR / "index.html")
@app.get("/badge/debug")
async def serve_badge_debug():
return FileResponse(STATIC_DIR / "index.html")
# Monta i file statici (JS, CSS, assets) sotto /badge
app.mount("/badge/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")
# Fallback per altri file statici sotto /badge
@app.get("/badge/{filename:path}")
async def serve_static(filename: str):
# ...
```
**Modifica necessaria:**
- Sostituisci `/badge` con il nuovo path desiderato in TUTTE le occorrenze
- Esempio per `/votazioni`:
```python
@app.get("/votazioni")
@app.get("/votazioni/debug")
app.mount("/votazioni/assets", ...)
@app.get("/votazioni/{filename:path}")
```
**Cerca anche il messaggio di avvio** (circa linea 177):
```python
print(f"🌐 Frontend disponibile su http://{args.host}:{args.port}/badge")
```
Cambia in:
```python
print(f"🌐 Frontend disponibile su http://{args.host}:{args.port}/NUOVO_PATH")
```
---
### 2⃣ Frontend - `frontend/src/main.tsx`
**File**: `/frontend/src/main.tsx`
**Cerca il BrowserRouter** (circa linea 12):
```tsx
<BrowserRouter basename="/badge">
```
**Modifica necessaria:**
- Cambia `basename="/badge"` con il nuovo path
- Esempio: `basename="/votazioni"` oppure `basename="/"` per la root
**Cerca anche il callback onBack** (circa linea 8):
```tsx
return <DebugScreen onBack={() => window.location.href = '/badge'}/>
```
Cambia in:
```tsx
return <DebugScreen onBack={() => window.location.href = '/NUOVO_PATH'}/>
```
---
### 3⃣ Frontend - `frontend/vite.config.ts`
**File**: `/frontend/vite.config.ts`
**Cerca la configurazione proxy** (circa linea 32):
```typescript
// Proxy API in sviluppo verso il backend (porta 8000)
// In produzione il backend serve il frontend su /badge e le API su /api/*
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
},
},
```
**Modifica necessaria (solo se cambi il path delle API):**
- Se le API cambiano da `/api/*` a un altro path, aggiorna qui
- Normalmente **NON è necessario** cambiare questo
**Aggiorna anche il commento** per riflettere il nuovo path frontend (solo documentazione).
---
### 4⃣ Come Cambiare il Path delle API (Opzionale)
⚠️ **Attenzione**: Questo è separato dal path del frontend!
Attualmente le API sono su `/api/*`. Se vuoi cambiarle (es. `/v1/*` o `/rest/*`):
**Backend - `backend-mock/api/routes.py`:**
```python
# Cerca tutte le route decorator (4 endpoint)
@router.get("/api/info-room", ...) # → @router.get("/v1/info-room", ...)
@router.post("/api/login-validate", ...) # → @router.post("/v1/login-validate", ...)
@router.get("/api/anagrafica/{badge_code}", ...) # → @router.get("/v1/anagrafica/{badge_code}", ...)
@router.post("/api/entry-request", ...) # → @router.post("/v1/entry-request", ...)
```
**Frontend - `frontend/src/services/api.ts`:**
```typescript
// Cerca tutte le chiamate API (4 endpoint)
return apiFetch<RoomInfo>('/api/info-room'); // → '/v1/info-room'
return apiFetch<LoginResponse>('/api/login-validate', ...); // → '/v1/login-validate'
return apiFetch<User>(`/api/anagrafica/${...}`); // → `/v1/anagrafica/${...}`
return apiFetch<EntryResponse>('/api/entry-request', ...); // → '/v1/entry-request'
```
**Frontend - `frontend/vite.config.ts`:**
```typescript
proxy: {
'/api': { // → '/v1': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
},
```
---
## 📝 Caso Speciale: Root Path `/`
Se vuoi servire il frontend direttamente sulla root (`http://localhost:8000/`):
### Backend:
```python
@app.get("/")
async def serve_index():
return FileResponse(STATIC_DIR / "index.html")
@app.get("/debug")
async def serve_debug():
return FileResponse(STATIC_DIR / "index.html")
app.mount("/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")
@app.get("/{filename:path}")
async def serve_static(filename: str):
# ... fallback logic
```
### Frontend:
```tsx
<BrowserRouter basename="/">
// oppure semplicemente:
<BrowserRouter>
```
⚠️ **Attenzione**: Se usi la root, le API REST devono essere montate PRIMA del catch-all `/{filename:path}`, altrimenti verranno intercettate dal frontend.
---
## ✅ Checklist Completa
### Per Cambiare il Path del Frontend (es. `/badge` → `/votazioni`):
- [ ] **Backend**: Modifica tutte le route `@app.get("/badge...")` → `@app.get("/NUOVO_PATH...")`
- [ ] **Backend**: Modifica `app.mount("/badge/assets", ...)` → `app.mount("/NUOVO_PATH/assets", ...)`
- [ ] **Backend**: Aggiorna il messaggio di avvio con il nuovo URL
- [ ] **Frontend**: Aggiorna `basename="/badge"` in `main.tsx`
- [ ] **Frontend**: Aggiorna il link di ritorno in `DebugWrapper`
- [ ] **Frontend**: (Opzionale) Aggiorna i commenti in `vite.config.ts`
- [ ] **Test**: Rebuild del frontend con `./dev.sh build`
- [ ] **Test**: Avvio del server con `./dev.sh server`
- [ ] **Test**: Verifica che `http://localhost:8000/NUOVO_PATH` funzioni
- [ ] **Test**: Verifica che `http://localhost:8000/NUOVO_PATH/debug` funzioni
- [ ] **Test**: Verifica che le API continuino a funzionare (servite su `/api/*`)
### Per Cambiare il Path delle API (es. `/api/*` → `/v1/*`):
- [ ] **Backend**: Modifica tutti i `@router.get("/api/...")` in `api/routes.py`
- [ ] **Frontend**: Modifica tutte le chiamate `apiFetch('/api/...')` in `services/api.ts`
- [ ] **Frontend**: Aggiorna il proxy in `vite.config.ts`
- [ ] **Frontend**: Aggiorna `baseURL` in `playwright.config.ts` se usi test E2E
- [ ] **Test**: Verifica che tutte le API rispondano sul nuovo path
- [ ] **Test**: Test E2E (`./dev.sh test:e2e`) per verificare integrazione completa
---
## 🔬 Test dopo il Cambio
```bash
# 1. Pulisci e rebuilda
./dev.sh clean
./dev.sh build
# 2. Avvia il server completo
./dev.sh server
# 3. Testa nel browser
# - http://localhost:8000/NUOVO_PATH
# - http://localhost:8000/NUOVO_PATH/debug
# - http://localhost:8000/docs (API docs, deve rimanere fuori dal path frontend)
# 4. Test API dirette (servite su /api/*)
curl http://localhost:8000/api/info-room
curl http://localhost:8000/api/anagrafica/0008988288
```
---
## 🎯 Files da Modificare - Riepilogo
### Cambio Path Frontend (`/badge` → altro):
| File | Cosa Modificare | Linee Circa |
|------|----------------|-------------|
| `backend-mock/main.py` | Route `@app.get("/badge")` e varianti | ~94-114 |
| `backend-mock/main.py` | Messaggio avvio `print(...)` | ~177 |
| `frontend/src/main.tsx` | `basename="/badge"` in BrowserRouter | ~12 |
| `frontend/src/main.tsx` | `window.location.href = '/badge'` | ~8 |
| `frontend/vite.config.ts` | Commento documentazione (opzionale) | ~32 |
### Cambio Path API (`/api/*` → altro):
| File | Cosa Modificare | Linee Circa |
|------|----------------|-------------|
| `backend-mock/api/routes.py` | Tutti i `@router.get("/api/...")` (4 route) | ~58, 67, 96, 118 |
| `frontend/src/services/api.ts` | Tutte le chiamate `apiFetch('/api/...')` (4 chiamate) | ~95, 108, 120, 135 |
| `frontend/vite.config.ts` | Proxy `'/api'` | ~35 |
---
## 💡 Nota Importante
Il sistema usa **due path separati**:
1. **Frontend SPA** (React): servito su `/badge`
- `http://localhost:8000/badge` → App principale
- `http://localhost:8000/badge/debug` → Pagina debug
- `http://localhost:8000/badge/assets/*` → File statici (JS, CSS, immagini)
2. **API REST** (FastAPI): servite su `/api/*`
- `http://localhost:8000/api/info-room`
- `http://localhost:8000/api/login-validate`
- `http://localhost:8000/api/anagrafica/{badge}`
- `http://localhost:8000/api/entry-request`
Questi due path sono **indipendenti** e possono essere cambiati separatamente.
**Vantaggio**: Le API sono sempre accessibili su un path fisso, anche se il frontend cambia posizione.
---
Documento creato: 2026-02-04

View File

@@ -33,9 +33,10 @@ L'output sarà qualcosa come: `192.168.1.230` (o simile, dipende dalla tua rete)
Sul tablet o altro dispositivo connesso alla **stessa rete WiFi**:
1. Apri il browser (Chrome, Firefox, ecc.)
2. Vai all'indirizzo: `http://192.168.1.230:8000`
2. Vai all'indirizzo: `http://192.168.1.230:8000/badge`
- Sostituisci `192.168.1.230` con l'IP che hai trovato nel passo 2
- Mantieni la porta `:8000` (o quella che hai specificato con `-p`)
- Il frontend è servito su `/badge`
### 4. Verifica della connettività
@@ -95,7 +96,7 @@ Se la porta 8000 è già in uso o vuoi usarne un'altra:
./dev.sh server -p 9000
```
Poi accedi da: `http://192.168.1.230:9000`
Poi accedi da: `http://192.168.1.230:9000/badge`
### 6. Ambiente di produzione

147
PATH_STRUCTURE.md Normal file
View File

@@ -0,0 +1,147 @@
# 🗺️ Struttura Path del Sistema
## Riepilogo Configurazione Attuale
Il sistema Focolari Voting System utilizza una **struttura path separata** per frontend e API:
```
http://localhost:8000/
├── /badge ← Frontend React SPA
│ ├── / ← Pagina principale
│ ├── /debug ← Pagina diagnostica
│ └── /assets/* ← File statici (JS, CSS, immagini)
├── /api/* ← API REST
│ ├── /info-room ← Informazioni sala
│ ├── /login-validate ← Login validatore
│ ├── /anagrafica/{badge} ← Ricerca utente
│ └── /entry-request ← Registrazione ingresso
├── /docs ← Documentazione API (Swagger)
└── / ← Health check (solo se frontend non buildato)
```
---
## 🎯 Vantaggi di questa Struttura
1. **Separazione chiara**: Frontend e API sono completamente isolati
2. **Flessibilità**: Puoi cambiare il path del frontend senza toccare le API
3. **Sicurezza**: Le API sono su un path fisso, facile da proteggere con firewall/proxy
4. **Debugging**: È chiaro se un errore viene dal frontend o dalle API
5. **Deployment**: Puoi servire frontend e API da server diversi in futuro
---
## 📁 Files Coinvolti
### Backend
**File: `backend-mock/main.py`**
- Gestisce le route del frontend su `/badge`
- Include il router API che gestisce `/api/*`
**File: `backend-mock/api/routes.py`**
- Definisce tutte le route API con prefisso `/api/*`
### Frontend
**File: `frontend/src/main.tsx`**
- Configura il router React con `basename="/badge"`
**File: `frontend/src/services/api.ts`**
- Tutte le chiamate API usano il prefisso `/api/*`
**File: `frontend/vite.config.ts`**
- Proxy per development: `/api``http://127.0.0.1:8000`
**File: `frontend/playwright.config.ts`**
- Test E2E configurati per `baseURL: http://localhost:8000/badge`
**File: `frontend/e2e/app.spec.ts`**
- Intercept delle chiamate API su `**/api/entry-request`
---
## 🔄 Flusso Richieste
### In Sviluppo (Vite Dev Server)
```
Browser → http://localhost:5173/
Frontend React (Vite)
API call to /api/info-room
Vite Proxy: /api/* → http://127.0.0.1:8000/api/*
Backend FastAPI
```
### In Produzione (Server Integrato)
```
Browser → http://localhost:8000/badge
Backend FastAPI
├─→ /badge → Serve frontend statico
└─→ /api/* → Gestisce API REST
```
---
## 📋 Checklist Verifica
Per verificare che tutto funzioni correttamente:
```bash
# 1. Avvia il server
./dev.sh server
# 2. Testa il frontend
open http://localhost:8000/badge
# 3. Testa le API
curl http://localhost:8000/api/info-room
curl http://localhost:8000/api/anagrafica/0008988288
# 4. Verifica documentazione API
open http://localhost:8000/docs
# 5. Esegui i test E2E
./dev.sh test:e2e
```
---
## 🔧 Come Modificare
Per modificare i path, consulta **`CHANGE_BASE_PATH.md`** che spiega:
- Come cambiare il path del frontend (es. `/badge``/votazioni`)
- Come cambiare il path delle API (es. `/api/*``/v1/*`)
- Quali file modificare per ogni cambiamento
- Checklist completa di test
---
## 📊 Tabella Riassuntiva
| Componente | Path | Gestito da | File Config |
|------------|------|------------|-------------|
| **Frontend principale** | `/badge` | Backend (serve static) | `backend-mock/main.py` |
| **Frontend debug** | `/badge/debug` | Backend (serve static) | `backend-mock/main.py` |
| **Frontend assets** | `/badge/assets/*` | Backend (StaticFiles) | `backend-mock/main.py` |
| **Frontend router** | `/badge` (basename) | React Router | `frontend/src/main.tsx` |
| **API info sala** | `/api/info-room` | Backend API | `backend-mock/api/routes.py` |
| **API login** | `/api/login-validate` | Backend API | `backend-mock/api/routes.py` |
| **API anagrafica** | `/api/anagrafica/{badge}` | Backend API | `backend-mock/api/routes.py` |
| **API ingresso** | `/api/entry-request` | Backend API | `backend-mock/api/routes.py` |
| **Proxy dev** | `/api``:8000` | Vite | `frontend/vite.config.ts` |
| **Test E2E** | `baseURL: /badge` | Playwright | `frontend/playwright.config.ts` |
---
Documento creato: 2025-02-04
Ultima modifica: 2025-02-04

View File

@@ -38,7 +38,7 @@ VotoFocolari/
```bash
./dev.sh server
# App completa: http://localhost:8000
# App completa: http://localhost:8000/badge
```
### Altri Comandi
@@ -97,7 +97,7 @@ Il watch mode è utile durante lo sviluppo:
```bash
./dev.sh test:dev
```
Questo avvia sia il server (http://localhost:8000) che i test in watch mode, così puoi:
Questo avvia sia il server (http://localhost:8000/badge) che i test in watch mode, così puoi:
- Testare manualmente nel browser
- Vedere i test automatici aggiornarsi in tempo reale
@@ -183,8 +183,14 @@ Questo garantisce che anche se il frontend ha bug, il backend fa da ultimo balua
## 📚 Documentazione
Per dettagli tecnici, consulta la cartella `ai-prompts/`:
Per dettagli tecnici, consulta:
### Guide:
- **`PATH_STRUCTURE.md`** - Struttura path del sistema (`/badge` per frontend, `/api/*` per API)
- **`CHANGE_BASE_PATH.md`** - Come cambiare il path base del frontend o delle API
- **`NETWORK_ACCESS.md`** - Come accedere al server da altri dispositivi (tablet)
### Piani di sviluppo (`ai-prompts/`):
- `00-welcome-agent.md` - Panoramica progetto
- `01-backend-plan.md` - Piano sviluppo backend
- `02-frontend-plan.md` - Piano sviluppo frontend

View File

@@ -138,7 +138,7 @@ backend-mock/
### Via Script (consigliato)
```bash
./dev.sh server # Avvia server con frontend
./dev.sh server # Avvia server con frontend su /badge
./dev.sh server -p 9000 # Porta custom
./dev.sh backend # Solo API, no frontend
```

View File

@@ -85,20 +85,20 @@ def create_app(data: dict, serve_frontend: bool = True) -> FastAPI:
if serve_frontend and STATIC_DIR.exists():
print(f"🌐 Frontend statico servito da: {STATIC_DIR}")
# Serve index.html per la root e tutte le route SPA
@app.get("/")
async def serve_index():
# Serve index.html su /badge e sue sub-route
@app.get("/badge")
async def serve_badge_index():
return FileResponse(STATIC_DIR / "index.html")
@app.get("/debug")
async def serve_debug():
@app.get("/badge/debug")
async def serve_badge_debug():
return FileResponse(STATIC_DIR / "index.html")
# Monta i file statici (JS, CSS, assets) - DEVE essere dopo le route
app.mount("/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")
# Monta i file statici (JS, CSS, assets) sotto /badge
app.mount("/badge/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")
# Fallback per altri file statici nella root (favicon, ecc.)
@app.get("/{filename:path}")
# Fallback per altri file statici sotto /badge (favicon, ecc.)
@app.get("/badge/{filename:path}")
async def serve_static(filename: str):
file_path = STATIC_DIR / filename
if file_path.exists() and file_path.is_file():
@@ -179,7 +179,7 @@ def main():
print(f"📍 Server in ascolto su http://{args.host}:{args.port}")
print(f"📚 Documentazione API su http://{args.host}:{args.port}/docs")
if not args.api_only and STATIC_DIR.exists():
print(f"🌐 Frontend disponibile su http://{args.host}:{args.port}/")
print(f"🌐 Frontend disponibile su http://{args.host}:{args.port}/badge")
print("=" * 50)
# Crea e avvia l'app

View File

@@ -345,7 +345,7 @@ test.describe('Sicurezza Backend', () => {
let requestIntercepted = false;
let backendResponse: { success: boolean; message: string } | null = null;
await page.route('**/entry-request', async (route, request) => {
await page.route('**/api/entry-request', async (route, request) => {
requestIntercepted = true;
console.log('[E2E] ⚠️ Richiesta entry-request INTERCETTATA');
console.log('[E2E] Body:', request.postData());

View File

@@ -19,8 +19,8 @@ export default defineConfig({
},
use: {
// URL base del server
baseURL: 'http://localhost:8000',
// URL base del server (frontend servito su /badge)
baseURL: 'http://localhost:8000/badge',
// Rallenta le azioni per vedere cosa succede
launchOptions: {

View File

@@ -6,12 +6,12 @@ import App from './App.tsx'
import {DebugScreen} from './screens'
function DebugWrapper() {
return <DebugScreen onBack={() => window.location.href = '/'}/>
return <DebugScreen onBack={() => window.location.href = '/badge'}/>
}
createRoot(document.getElementById('root')!).render(
<StrictMode>
<BrowserRouter>
<BrowserRouter basename="/badge">
<Routes>
<Route path="/" element={<App/>}/>
<Route path="/debug" element={<DebugWrapper/>}/>

View File

@@ -7,8 +7,8 @@ import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
// Path relativi per funzionare su qualsiasi IP/porta
base: './',
// Base path per il frontend servito su /badge
base: '/badge/',
// Build nella cartella dist del frontend
build: {
@@ -30,22 +30,10 @@ export default defineConfig({
},
// Proxy API in sviluppo verso il backend (porta 8000)
// In produzione il backend serve direttamente il frontend
// In produzione il backend serve il frontend su /badge e le API su /api/*
server: {
proxy: {
'/info-room': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
'/login-validate': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
'/anagrafica': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
'/entry-request': {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},