Files
trenes/RESUMEN-IMPLEMENTACION.md
Millaguie 34c0cb50c7
Some checks failed
Auto Tag on Merge to Main / auto-tag (push) Successful in 27s
CI - Lint and Build / lint-backend (push) Failing after 30s
CI - Lint and Build / lint-frontend (push) Failing after 2s
CI - Lint and Build / build-frontend (push) Has been skipped
CI - Lint and Build / docker-build-test (push) Has been skipped
feat: Initial commit - Train tracking system
Complete real-time train tracking system for Spanish railways (Renfe/Cercanías):

- Backend API (Node.js/Express) with GTFS-RT polling workers
- Frontend dashboard (React/Vite) with Leaflet maps
- Real-time updates via Socket.io WebSocket
- PostgreSQL/PostGIS database with Flyway migrations
- Redis caching layer
- Docker Compose configuration for development and production
- Gitea CI/CD workflows (lint, auto-tag, release)
- Production deployment with nginx + Let's Encrypt SSL

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 00:21:15 +01:00

241 lines
6.5 KiB
Markdown

# Sistema de Tracking de Trenes - Referencia Operativa
## Estado del Proyecto (27 Nov 2025)
| Fase | Backend | Frontend |
|------|---------|----------|
| 1. MVP | ✅ 100% | ✅ 100% |
| 2. Enriquecimiento | ✅ 100% | ⏳ 0% |
| 3. Analytics | ✅ 100% | ⏳ 0% |
---
## Quick Start
```bash
# 1. Configurar
cp .env.example .env
# Editar .env con contraseñas seguras
# 2. Ejecutar migraciones
make migrate
# 3. Iniciar
make start
# 4. Acceder
# App: http://localhost
# API: http://localhost/api
```
---
## Servicios Docker
| Servicio | Puerto | Descripción |
|----------|--------|-------------|
| nginx | 80 | Reverse proxy |
| api | 3000 | API REST + WebSocket |
| frontend | 5173 | React app |
| postgres | 5432 | PostgreSQL + PostGIS |
| redis | 6379 | Cache |
| worker | - | GTFS-RT Vehicle Positions |
| gtfs-static-syncer | - | Sync GTFS Static (3 AM) |
| trip-updates-poller | - | Trip Updates (30s) |
| alerts-poller | - | Service Alerts (30s) |
| analytics-refresher | - | Refresh vistas (15 min) |
---
## API Endpoints
### Fase 1 - Core
```
GET /health - Health check
GET /trains/current - Posiciones actuales
GET /trains/:id - Info de un tren
GET /trains/:id/history - Histórico de posiciones
GET /trains/:id/path - Trayectoria
GET /trains/area - Trenes en área geográfica
GET /routes - Todas las rutas
GET /routes/:id - Ruta específica
GET /stations - Todas las estaciones
GET /stations/:id - Estación específica
GET /stats - Estadísticas sistema
WS /ws - WebSocket (Socket.io)
```
### Fase 2 - Alertas y Delays
```
GET /alerts - Alertas activas
GET /alerts/:id - Alerta específica
GET /alerts/route/:routeId - Alertas por ruta
GET /trips - Viajes activos hoy
GET /trips/:id - Detalles de viaje
GET /trips/:id/delays - Retrasos de viaje
GET /trips/delayed/all - Todos los retrasados
```
### Fase 3 - Analytics
```
GET /analytics/traffic/heatmap - Heatmap de tráfico
GET /analytics/traffic/hourly - Tráfico por hora
GET /analytics/statistics/daily - Estadísticas diarias
GET /analytics/delays/top-routes - Rutas más retrasadas
GET /analytics/export - Exportar datos (CSV/JSON/GeoJSON)
GET /explorer/routes/:routeId - Explorar ruta completa
GET /explorer/planner - Planificador de viajes
GET /explorer/search - Búsqueda de estaciones
```
---
## WebSocket Events
```javascript
// Cliente
socket.emit('subscribe:train', trainId);
socket.emit('unsubscribe:train', trainId);
// Servidor
socket.on('trains:update', (positions) => {});
socket.on('train:update', (position) => {});
```
---
## Comandos Make
```bash
make start # Iniciar servicios
make stop # Detener servicios
make logs # Ver todos los logs
make migrate # Ejecutar migraciones
make psql # Conectar a PostgreSQL
make redis-cli # Conectar a Redis
make debug-start # Iniciar con Adminer + Redis Commander
make test-start # Entorno de testing
make backup-db # Backup de BD
```
---
## Base de Datos
### Tablas Principales
- `trains` - Catálogo de trenes
- `train_positions` - Histórico (particionada por mes)
- `routes` - Rutas y líneas
- `stations` - Estaciones
- `alerts` - Alertas e incidencias
- `trips` - Viajes programados (GTFS Static)
- `trip_updates` - Actualizaciones tiempo real
### Funciones Útiles
```sql
-- Limpiar posiciones antiguas (>90 días)
SELECT cleanup_old_positions(90);
-- Crear siguiente partición mensual
SELECT create_next_partition();
-- Trayectoria de un tren
SELECT * FROM get_train_path('TRAIN_ID', '2025-01-01', '2025-01-02');
-- Trenes en área geográfica
SELECT * FROM get_trains_in_area(40.0, -4.0, 41.0, -3.0);
-- Próximas salidas desde estación
SELECT * FROM get_next_departures('STATION_ID', 10);
```
---
## Fuentes de Datos GTFS-RT
| Feed | URL | Frecuencia |
|------|-----|------------|
| Vehicle Positions | https://gtfsrt.renfe.com/vehicle_positions.pb | 30s |
| Trip Updates | https://gtfsrt.renfe.com/trip_updates_cercanias.pb | 30s |
| Service Alerts | https://gtfsrt.renfe.com/alerts.pb | 30s |
| GTFS Static | https://data.renfe.com/dataset | Diario |
---
## Estructura del Proyecto
```
trenes/
├── backend/src/
│ ├── api/
│ │ ├── server.js # API + WebSocket
│ │ └── routes/ # Endpoints (8 archivos)
│ ├── worker/ # 5 workers
│ ├── lib/ # db, redis, logger
│ └── config/
├── frontend/src/
│ ├── components/ # TrainMap, TrainInfo, Timeline
│ ├── hooks/useTrains.js # WebSocket hook
│ └── App.jsx
├── database/migrations/ # V1-V6
├── nginx/ # Reverse proxy config
├── docker-compose.yml
├── Makefile
└── .env.example
```
---
## Troubleshooting
### No se ven trenes
```bash
docker compose logs worker # Verificar worker
make psql
> SELECT COUNT(*) FROM train_positions WHERE recorded_at > NOW() - INTERVAL '1 hour';
```
### Error conexión WebSocket
- Verificar `CORS_ORIGIN` en `.env`
- Verificar `VITE_WS_URL` en frontend
### BD sin datos
```bash
make migrate # Ejecutar migraciones
make migrate-info # Verificar estado
```
---
## Siguiente Fase: Frontend Fase 2/3
### Pendiente implementar:
1. **Componente AlertsPanel** - Mostrar alertas activas
2. **Componente PunctualityMonitor** - Dashboard de puntualidad
3. **Timeline funcional** - Reproducción de histórico
4. **Heatmap de tráfico** - Visualización en mapa
5. **Dashboard Analytics** - Gráficos y estadísticas
6. **Planificador UI** - Interfaz de búsqueda de viajes
### APIs disponibles para frontend:
- `GET /alerts` - Lista de alertas
- `GET /trips/delayed/all` - Viajes retrasados
- `GET /analytics/traffic/heatmap` - Datos para heatmap
- `GET /analytics/statistics/daily` - Estadísticas
- `GET /explorer/planner?from=X&to=Y&time=Z` - Planificador
---
## Documentación Adicional
- `README.md` - Introducción y setup
- `arquitectura-sistema-tracking-trenes.md` - Arquitectura detallada
- `FUENTES_DATOS.md` - Fuentes de datos disponibles
- `FASE1-MVP.md` - Detalles Fase 1
- `FASE2-ENRIQUECIMIENTO.md` - Detalles Fase 2
- `FASE3-ANALYTICS.md` - Detalles Fase 3
---
**Última actualización**: 27 noviembre 2025