# Indice de Especificaciones Tecnicas - MGN-009 Reports

## Identificacion

| Campo | Valor |
|-------|-------|
| **Modulo** | MGN-009 |
| **Epic** | Reports & Dashboards |
| **Total ET** | 3 |
| **Story Points** | 36 |
| **Fecha** | 2025-12-05 |

---

## Especificaciones Tecnicas

| ID | Titulo | RF Cubiertos | Estado |
|----|--------|--------------|--------|
| [ET-REPORT-database](./ET-REPORT-database.md) | Schema core_reports | RF-001 a RF-004 | Documentado |
| [ET-REPORT-backend](./ET-REPORT-backend.md) | Servicios y API REST | RF-001 a RF-004 | Documentado |
| [ET-REPORT-frontend](./ET-REPORT-frontend.md) | Componentes React + Chart.js | RF-001 a RF-004 | Documentado |

---

## Resumen de Componentes

### Database (ET-REPORT-database)

| Tabla | RF | Descripcion |
|-------|-----|-------------|
| report_definitions | RF-001 | Definiciones de reportes predefinidos |
| report_executions | RF-001 | Historial de ejecuciones |
| dashboards | RF-002 | Dashboards personalizables |
| widgets | RF-002 | Widgets dentro de dashboards |
| custom_reports | RF-003 | Reportes creados via Builder |
| report_fields | RF-003 | Catalogo de campos disponibles |
| scheduled_reports | RF-004 | Programacion de reportes automaticos |

**Total:** 7 tablas

**Funciones:**
- `execute_report()` - Ejecucion de reportes predefinidos
- `build_query()` - Construccion de query dinamico
- `cleanup_old_executions()` - Limpieza de ejecuciones antiguas

### Backend (ET-REPORT-backend)

| Servicio | Responsabilidad | RF |
|----------|-----------------|-----|
| ReportsService | CRUD reportes predefinidos | RF-001 |
| ReportExecutorService | Ejecucion sync/async | RF-001 |
| ReportExporterService | Exportacion multi-formato | RF-001 |
| DashboardsService | CRUD dashboards | RF-002 |
| WidgetsService | CRUD widgets + data | RF-002 |
| CustomReportsService | CRUD reportes custom | RF-003 |
| ReportBuilderService | Builder engine | RF-003 |
| ScheduledReportsService | Programacion | RF-004 |

**Total:** 24 endpoints

---

## Matriz de Trazabilidad RF -> ET

| RF | Database | Backend |
|----|----------|---------|
| RF-REPORT-001 | report_definitions, report_executions | ReportsService, ReportExecutorService, ReportExporterService |
| RF-REPORT-002 | dashboards, widgets | DashboardsService, WidgetsService |
| RF-REPORT-003 | custom_reports, report_fields | CustomReportsService, ReportBuilderService |
| RF-REPORT-004 | scheduled_reports | ScheduledReportsService |

---

## Arquitectura de Reportes

```
+------------------+     +------------------+
|   Predefined     |     |     Custom       |
|    Reports       |     |    (Builder)     |
+--------+---------+     +--------+---------+
         |                        |
         v                        v
+--------+---------+     +--------+---------+
| ReportExecutor   |<--->| ReportBuilder    |
| (Query Engine)   |     | (Query Builder)  |
+--------+---------+     +--------+---------+
         |
         v
+--------+---------+
|  ReportExporter  |
|  (PDF/XLSX/CSV)  |
+------------------+
         |
         v
+--------+---------+
|   Scheduled      |
|   (Cron Jobs)    |
+------------------+
```

### Flujo de Ejecucion

1. **Reporte Predefinido:**
   - Query template + parametros
   - Ejecucion directa o via Queue (async)
   - Cache opcional por TTL
   - Exportacion multi-formato

2. **Reporte Custom (Builder):**
   - Seleccion entidad base
   - Seleccion campos + joins
   - Definicion filtros dinamicos
   - Agrupaciones y agregaciones
   - Preview antes de guardar

3. **Dashboard:**
   - Layout configurable (grid)
   - Widgets con data sources independientes
   - Refresh automatico opcional
   - Visibilidad: private/team/tenant

---

## Tipos de Widget

| Tipo | Uso | Data Format |
|------|-----|-------------|
| metric | KPI numerico | `{ value, previousValue }` |
| chart_line | Tendencias | `{ labels, datasets }` |
| chart_bar | Comparativas | `{ labels, datasets }` |
| chart_pie | Proporciones | `{ labels, data }` |
| chart_area | Areas | `{ labels, datasets }` |
| table | Datos tabulares | `{ rows }` |
| list | Listas simples | `{ rows }` |
| progress | Progreso | `{ current, total }` |
| gauge | Medidores | `{ value, min, max }` |
| map | Geografico | `{ points }` |
| calendar | Calendario | `{ events }` |

---

## Formatos de Exportacion

| Formato | Libreria | Content-Type |
|---------|----------|--------------|
| PDF | Puppeteer/PDFKit | application/pdf |
| XLSX | ExcelJS | application/vnd.openxmlformats... |
| CSV | Native | text/csv |
| JSON | Native | application/json |

---

## Dependencias Tecnicas

### Externas
- PostgreSQL 15+ (JSONB)
- Redis (Cache)
- TypeORM 0.3+
- NestJS 10+
- Bull/BullMQ (Async jobs)
- ExcelJS (Excel export)
- Puppeteer/PDFKit (PDF export)
- cron-parser (Scheduling)

### Internas
- core_tenants.tenants (RLS)
- core_users.users (Owner)
- MGN-001 Auth (Autenticacion)
- MGN-003 RBAC (Permisos)
- MGN-008 Notifications (Envio reportes)

---

## Permisos Requeridos

| Permiso | Descripcion |
|---------|-------------|
| reports.read | Ver catalogo de reportes |
| reports.execute | Ejecutar reportes |
| reports.export | Exportar reportes |
| reports.builder.read | Acceso a Report Builder |
| reports.builder.create | Crear reportes custom |
| reports.builder.execute | Ejecutar reportes custom |
| reports.schedules.read | Ver programaciones |
| reports.schedules.manage | Crear/editar programaciones |
| reports.admin | Administrar definiciones |

---

## Consideraciones de Performance

| Aspecto | Estrategia |
|---------|------------|
| Cache | Redis con TTL configurable por reporte |
| Async | Reportes grandes via Bull queue |
| Limit | max_rows por definicion (default 10k) |
| Timeout | Query timeout configurable |
| Indices | Usar indices en campos frecuentes |

---

## Historial

| Version | Fecha | Autor | Cambios |
|---------|-------|-------|---------|
| 1.0 | 2025-12-05 | Requirements-Analyst | Creacion inicial con 2 ET |
| 1.1 | 2025-12-05 | Requirements-Analyst | Agregado ET Frontend |
