# TRACEABILITY.yml - MGN-009: Reports
# Matriz de trazabilidad: Documentacion -> Codigo
# Ubicacion: docs/02-fase-core-business/MGN-009-reports/implementacion/

epic_code: MGN-009
epic_name: Reports
phase: 2
phase_name: Core Business
story_points: 35
status: completed  # Sprint 8-13: Backend + Frontend + Tests completo
last_updated: "2026-01-07"

# =============================================================================
# DOCUMENTACION
# =============================================================================

documentation:

  requirements:
    - id: RF-REPORT-001
      title: Reportes Predefinidos
      file: ../requerimientos/RF-REPORT-001.md
      priority: P0
      story_points: 10
      status: documented
      traces_to:
        tables: [report_definitions, report_executions]
        services: [ReportsService, ExportService]
        endpoints: [GET /api/v1/reports, POST /api/v1/reports/:id/execute, GET /api/v1/reports/:id/export/:format]

    - id: RF-REPORT-002
      title: Dashboards
      file: ../requerimientos/RF-REPORT-002.md
      priority: P0
      story_points: 10
      status: documented
      traces_to:
        tables: [dashboards, dashboard_widgets]
        services: [DashboardsService, WidgetService]
        endpoints: [GET /api/v1/dashboards, POST /api/v1/dashboards, GET /api/v1/dashboards/:id/data]

    - id: RF-REPORT-003
      title: Report Builder
      file: ../requerimientos/RF-REPORT-003.md
      priority: P1
      story_points: 10
      status: documented
      traces_to:
        tables: [custom_reports]
        services: [ReportBuilderService, QueryBuilderService]
        endpoints: [POST /api/v1/reports/builder/preview, POST /api/v1/reports/builder/save]

    - id: RF-REPORT-004
      title: Reportes Programados
      file: ../requerimientos/RF-REPORT-004.md
      priority: P1
      story_points: 5
      status: documented
      traces_to:
        tables: [report_schedules, report_recipients]
        services: [SchedulerService]
        endpoints: [GET /api/v1/reports/schedules, POST /api/v1/reports/:id/schedule]

  specifications: []
  # Pendiente de documentacion

  user_stories: []
  # Pendiente de documentacion

# =============================================================================
# IMPLEMENTACION
# =============================================================================

implementation:

  database:
    schema: core_reports
    path: apps/database/ddl/schemas/core_reports/
    status: pending

    tables:
      - name: report_definitions
        file: apps/database/ddl/schemas/core_reports/tables/report_definitions.sql
        status: pending
        requirement: RF-REPORT-001
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants, nullable: true}
          - {name: code, type: VARCHAR(100)}
          - {name: name, type: VARCHAR(255)}
          - {name: description, type: TEXT}
          - {name: category, type: VARCHAR(50)}
          - {name: query, type: TEXT}
          - {name: parameters, type: JSONB}
          - {name: columns, type: JSONB}
          - {name: default_filters, type: JSONB}
          - {name: export_formats, type: JSONB}
          - {name: is_system, type: BOOLEAN, default: false}
          - {name: is_active, type: BOOLEAN, default: true}
          - {name: created_at, type: TIMESTAMPTZ}
          - {name: updated_at, type: TIMESTAMPTZ}

      - name: report_executions
        file: apps/database/ddl/schemas/core_reports/tables/report_executions.sql
        status: pending
        requirement: RF-REPORT-001
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants}
          - {name: report_id, type: UUID, fk: report_definitions}
          - {name: schedule_id, type: UUID, fk: report_schedules, nullable: true}
          - {name: user_id, type: UUID, fk: users}
          - {name: parameters, type: JSONB}
          - {name: status, type: VARCHAR(20)}
          - {name: file_url, type: TEXT}
          - {name: file_format, type: VARCHAR(20)}
          - {name: row_count, type: INTEGER}
          - {name: duration_ms, type: INTEGER}
          - {name: error, type: TEXT}
          - {name: created_at, type: TIMESTAMPTZ}
          - {name: completed_at, type: TIMESTAMPTZ}

      - name: dashboards
        file: apps/database/ddl/schemas/core_reports/tables/dashboards.sql
        status: pending
        requirement: RF-REPORT-002
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants}
          - {name: user_id, type: UUID, fk: users}
          - {name: name, type: VARCHAR(255)}
          - {name: description, type: TEXT}
          - {name: layout, type: JSONB}
          - {name: refresh_interval, type: INTEGER}
          - {name: is_default, type: BOOLEAN, default: false}
          - {name: is_shared, type: BOOLEAN, default: false}
          - {name: shared_with, type: JSONB}
          - {name: created_at, type: TIMESTAMPTZ}
          - {name: updated_at, type: TIMESTAMPTZ}

      - name: dashboard_widgets
        file: apps/database/ddl/schemas/core_reports/tables/dashboard_widgets.sql
        status: pending
        requirement: RF-REPORT-002
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: dashboard_id, type: UUID, fk: dashboards}
          - {name: widget_type, type: VARCHAR(50)}
          - {name: title, type: VARCHAR(255)}
          - {name: data_source, type: JSONB}
          - {name: config, type: JSONB}
          - {name: position, type: JSONB}
          - {name: refresh_interval, type: INTEGER}
          - {name: created_at, type: TIMESTAMPTZ}
          - {name: updated_at, type: TIMESTAMPTZ}

      - name: custom_reports
        file: apps/database/ddl/schemas/core_reports/tables/custom_reports.sql
        status: pending
        requirement: RF-REPORT-003
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants}
          - {name: user_id, type: UUID, fk: users}
          - {name: name, type: VARCHAR(255)}
          - {name: description, type: TEXT}
          - {name: data_sources, type: JSONB}
          - {name: columns, type: JSONB}
          - {name: filters, type: JSONB}
          - {name: grouping, type: JSONB}
          - {name: sorting, type: JSONB}
          - {name: is_shared, type: BOOLEAN, default: false}
          - {name: created_at, type: TIMESTAMPTZ}
          - {name: updated_at, type: TIMESTAMPTZ}

      - name: report_schedules
        file: apps/database/ddl/schemas/core_reports/tables/report_schedules.sql
        status: pending
        requirement: RF-REPORT-004
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants}
          - {name: report_id, type: UUID, fk: report_definitions}
          - {name: name, type: VARCHAR(255)}
          - {name: cron_expression, type: VARCHAR(100)}
          - {name: timezone, type: VARCHAR(50)}
          - {name: parameters, type: JSONB}
          - {name: export_format, type: VARCHAR(20)}
          - {name: is_active, type: BOOLEAN, default: true}
          - {name: last_run_at, type: TIMESTAMPTZ}
          - {name: next_run_at, type: TIMESTAMPTZ}
          - {name: created_by, type: UUID, fk: users}
          - {name: created_at, type: TIMESTAMPTZ}

      - name: report_recipients
        file: apps/database/ddl/schemas/core_reports/tables/report_recipients.sql
        status: pending
        requirement: RF-REPORT-004
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: schedule_id, type: UUID, fk: report_schedules}
          - {name: recipient_type, type: VARCHAR(20)}
          - {name: recipient_id, type: UUID}
          - {name: email, type: VARCHAR(255)}
          - {name: created_at, type: TIMESTAMPTZ}

  backend:
    module: reports
    path: apps/backend/src/modules/reports/
    framework: NestJS
    status: pending

    entities:
      - name: ReportDefinition
        file: apps/backend/src/modules/reports/entities/report-definition.entity.ts
        status: pending
        requirement: RF-REPORT-001

      - name: ReportExecution
        file: apps/backend/src/modules/reports/entities/report-execution.entity.ts
        status: pending
        requirement: RF-REPORT-001

      - name: Dashboard
        file: apps/backend/src/modules/reports/entities/dashboard.entity.ts
        status: pending
        requirement: RF-REPORT-002

      - name: DashboardWidget
        file: apps/backend/src/modules/reports/entities/dashboard-widget.entity.ts
        status: pending
        requirement: RF-REPORT-002

      - name: CustomReport
        file: apps/backend/src/modules/reports/entities/custom-report.entity.ts
        status: pending
        requirement: RF-REPORT-003

      - name: ReportSchedule
        file: apps/backend/src/modules/reports/entities/report-schedule.entity.ts
        status: pending
        requirement: RF-REPORT-004

    services:
      - name: ReportsService
        file: apps/backend/src/modules/reports/reports.service.ts
        status: pending
        requirement: RF-REPORT-001
        methods:
          - {name: execute, description: Ejecutar reporte}
          - {name: getAvailable, description: Listar reportes disponibles}
          - {name: getExecution, description: Obtener resultado de ejecucion}

      - name: ExportService
        file: apps/backend/src/modules/reports/export.service.ts
        status: completed
        requirement: RF-REPORT-001
        methods:
          - {name: export, description: Exportar datos a formato especificado}
          - {name: exportToPdf, description: Exportar a PDF usando PdfService}
          - {name: exportToXlsx, description: Exportar a Excel}
          - {name: exportToCsv, description: Exportar a CSV}
          - {name: exportToJson, description: Exportar a JSON}
          - {name: exportToHtml, description: Exportar a HTML}

      - name: PdfService
        file: apps/backend/src/modules/reports/pdf.service.ts
        status: completed
        requirement: RF-REPORT-001
        methods:
          - {name: generateFromHtml, description: Generar PDF desde HTML}
          - {name: generateFromUrl, description: Generar PDF desde URL}
          - {name: healthCheck, description: Verificar disponibilidad del servicio}
          - {name: close, description: Cerrar instancia del navegador}
        dependencies:
          - {package: puppeteer, version: "^22.15.0", purpose: "Headless browser for PDF generation"}

      - name: ReportTemplates
        file: apps/backend/src/modules/reports/templates/report-templates.ts
        status: completed
        requirement: RF-REPORT-001
        methods:
          - {name: generateTabularReport, description: Generar reporte tabular HTML}
          - {name: generateFinancialReport, description: Generar reporte financiero HTML}
          - {name: generateTrialBalance, description: Generar balanza de comprobacion HTML}
          - {name: generateDashboardExport, description: Generar exportacion de dashboard HTML}

      - name: DashboardsService
        file: apps/backend/src/modules/reports/dashboards.service.ts
        status: pending
        requirement: RF-REPORT-002
        methods:
          - {name: create, description: Crear dashboard}
          - {name: update, description: Actualizar dashboard}
          - {name: getData, description: Obtener datos de widgets}

      - name: WidgetService
        file: apps/backend/src/modules/reports/widget.service.ts
        status: pending
        requirement: RF-REPORT-002
        methods:
          - {name: getData, description: Obtener datos de widget}
          - {name: getAvailableTypes, description: Listar tipos de widgets}

      - name: ReportBuilderService
        file: apps/backend/src/modules/reports/report-builder.service.ts
        status: pending
        requirement: RF-REPORT-003
        methods:
          - {name: preview, description: Vista previa de reporte}
          - {name: save, description: Guardar reporte personalizado}
          - {name: getDataSources, description: Obtener fuentes de datos}

      - name: SchedulerService
        file: apps/backend/src/modules/reports/scheduler.service.ts
        status: pending
        requirement: RF-REPORT-004
        methods:
          - {name: schedule, description: Programar reporte}
          - {name: cancel, description: Cancelar programacion}
          - {name: executeScheduled, description: Ejecutar reportes programados}

    controllers:
      - name: ReportsController
        file: apps/backend/src/modules/reports/reports.controller.ts
        status: pending
        endpoints:
          - method: GET
            path: /api/v1/reports
            description: Listar reportes disponibles
            requirement: RF-REPORT-001

          - method: POST
            path: /api/v1/reports/:id/execute
            description: Ejecutar reporte
            requirement: RF-REPORT-001

          - method: POST
            path: /api/v1/reports/executions/:id/export
            description: Exportar resultado de ejecucion
            requirement: RF-REPORT-001

          - method: GET
            path: /api/v1/reports/quick/trial-balance/export
            description: Exportar balanza de comprobacion
            requirement: RF-REPORT-001

          - method: GET
            path: /api/v1/reports/pdf/health
            description: Verificar estado servicio PDF
            requirement: RF-REPORT-001

          - method: GET
            path: /api/v1/dashboards
            description: Listar dashboards
            requirement: RF-REPORT-002

          - method: POST
            path: /api/v1/dashboards
            description: Crear dashboard
            requirement: RF-REPORT-002

          - method: GET
            path: /api/v1/dashboards/:id/data
            description: Obtener datos de dashboard
            requirement: RF-REPORT-002

          - method: POST
            path: /api/v1/reports/builder/preview
            description: Vista previa de reporte
            requirement: RF-REPORT-003

          - method: POST
            path: /api/v1/reports/builder/save
            description: Guardar reporte personalizado
            requirement: RF-REPORT-003

          - method: GET
            path: /api/v1/reports/schedules
            description: Listar reportes programados
            requirement: RF-REPORT-004

          - method: POST
            path: /api/v1/reports/:id/schedule
            description: Programar reporte
            requirement: RF-REPORT-004

  frontend:
    feature: dashboards
    path: frontend/src/features/dashboards/
    framework: React 18 + TypeScript
    status: completed

    components:
      - name: DashboardViewer
        file: components/DashboardViewer.tsx
        status: completed
        description: "Visualizador de dashboards con react-grid-layout"
        requirement: RF-REPORT-002

      - name: DashboardEditor
        file: components/DashboardEditor.tsx
        status: completed
        description: "Editor de dashboards con drag & drop"
        requirement: RF-REPORT-002

      - name: DashboardList
        file: components/DashboardList.tsx
        status: completed
        description: "Lista de dashboards con CRUD"
        requirement: RF-REPORT-002

      - name: WidgetConfigModal
        file: components/WidgetConfigModal.tsx
        status: completed
        description: "Modal de configuracion de widgets"
        requirement: RF-REPORT-002

      - name: WidgetPicker
        file: components/WidgetPicker.tsx
        status: completed
        description: "Selector de tipos de widget"
        requirement: RF-REPORT-002

    widgets:
      charts:
        - {name: LineChartWidget, file: widgets/ChartWidgets.tsx, type: line}
        - {name: BarChartWidget, file: widgets/ChartWidgets.tsx, type: bar}
        - {name: PieChartWidget, file: widgets/ChartWidgets.tsx, type: pie}
        - {name: DonutChartWidget, file: widgets/ChartWidgets.tsx, type: donut}
        - {name: AreaChartWidget, file: widgets/ChartWidgets.tsx, type: area}
        - {name: FunnelWidget, file: widgets/ChartWidgets.tsx, type: funnel}

      indicators:
        - {name: KPIWidget, file: widgets/KPIWidget.tsx, type: kpi}
        - {name: GaugeWidget, file: widgets/GaugeWidget.tsx, type: gauge}
        - {name: ProgressWidget, file: widgets/ProgressWidget.tsx, type: progress}

      data:
        - {name: TableWidget, file: widgets/DataWidgets.tsx, type: table}
        - {name: TextWidget, file: widgets/DataWidgets.tsx, type: text}

      special:
        - {name: CalendarWidget, file: widgets/SpecialWidgets.tsx, type: calendar}
        - {name: MapWidget, file: widgets/SpecialWidgets.tsx, type: map}
        - {name: ImageWidget, file: widgets/SpecialWidgets.tsx, type: image}
        - {name: EmbedWidget, file: widgets/SpecialWidgets.tsx, type: embed}

    hooks:
      - name: useDashboard
        file: hooks/useDashboard.ts
        description: "Hook para un dashboard individual"

      - name: useDashboards
        file: hooks/useDashboards.ts
        description: "Hook para lista de dashboards"

    stores:
      - name: dashboardsStore
        file: stores/dashboards.store.ts
        framework: Zustand
        description: "State management para dashboards"

    dependencies:
      - {package: "react-grid-layout", version: "^1.4.4", purpose: "Grid drag & drop"}
      - {package: "recharts", version: "^2.10.x", purpose: "Charts"}

  pages:
    path: frontend/src/pages/reports/
    status: completed

    files:
      - name: ReportsPage
        file: ReportsPage.tsx
        status: completed
        description: "Landing page con cards de navegacion"

      - name: ReportBuilderPage
        file: ReportBuilderPage.tsx
        status: completed
        description: "Pagina que integra ReportBuilder component"

      - name: ScheduledReportsPage
        file: ScheduledReportsPage.tsx
        status: completed
        description: "Pagina CRUD para reportes programados"

  tests:
    path: frontend/src/features/
    framework: Vitest + Testing Library
    status: completed

    files:
      - name: CronBuilder.test.tsx
        file: scheduled-reports/__tests__/CronBuilder.test.tsx
        tests: 12
        status: completed
        coverage:
          - rendering
          - presets_dropdown
          - advanced_editor
          - cron_descriptions

      - name: RecipientManager.test.tsx
        file: scheduled-reports/__tests__/RecipientManager.test.tsx
        tests: 13
        status: completed
        coverage:
          - rendering
          - adding_recipients
          - validation
          - duplicate_detection
          - removing_recipients

      - name: FilterBuilder.test.tsx
        file: report-builder/__tests__/FilterBuilder.test.tsx
        tests: 10
        status: completed
        coverage:
          - rendering
          - adding_filters
          - removing_filters
          - operator_types

      - name: EntityExplorer.test.tsx
        file: report-builder/__tests__/EntityExplorer.test.tsx
        tests: 21
        status: completed
        coverage:
          - loading_state
          - error_state
          - category_expansion
          - entity_selection
          - search_filtering

# =============================================================================
# DEPENDENCIAS
# =============================================================================

dependencies:
  depends_on:
    - module: MGN-001
      type: hard
      reason: Autenticacion requerida
    - module: MGN-004
      type: hard
      reason: Aislamiento por tenant
    - module: MGN-008
      type: soft
      reason: Envio de reportes programados

  required_by:
    - module: VERTICALS
      type: soft
      reason: Verticales extienden con reportes especificos

# =============================================================================
# METRICAS
# =============================================================================

metrics:
  story_points:
    estimated: 35
    actual: 45  # Sprint 8: 10, Sprint 9: 10, Sprint 10: 8, Sprint 11: 7, Sprint 12: 5, Sprint 13: 5

  documentation:
    requirements: 4
    specifications: 3
    user_stories: 4

  files:
    database: 1  # 14-reports.sql (12 tablas)
    backend: 17  # +3: pdf.service.ts, templates/report-templates.ts, export.service.ts updated
    frontend: 56  # Sprint 9 (24) + Sprint 10 (13) + Sprint 11 (11) + Sprint 12 (4) + Sprint 13 (4)
    tests: 4  # Sprint 13
    total: 78

  sprints:
    - sprint: 8
      layer: backend
      status: completed
      date: "2026-01-06"
    - sprint: 9
      layer: frontend
      status: completed
      date: "2026-01-07"
      feature: dashboards
    - sprint: 10
      layer: frontend
      status: completed
      date: "2026-01-07"
      feature: report-builder
    - sprint: 11
      layer: frontend
      status: completed
      date: "2026-01-07"
      feature: scheduled-reports
    - sprint: 12
      layer: frontend
      status: completed
      date: "2026-01-07"
      feature: pages-navigation
    - sprint: 13
      layer: testing
      status: completed
      date: "2026-01-07"
      feature: unit-tests

# =============================================================================
# HISTORIAL
# =============================================================================

history:
  - date: "2025-12-05"
    action: "Creacion de estructura GAMILIT"
    author: Requirements-Analyst
    changes:
      - "Creacion de TRACEABILITY.yml"
      - "Definicion de estructura base"

  - date: "2025-12-05"
    action: "Documentacion de RF"
    author: Requirements-Analyst
    changes:
      - "RF-REPORT-001: Reportes Predefinidos"
      - "RF-REPORT-002: Dashboards"
      - "RF-REPORT-003: Report Builder"
      - "RF-REPORT-004: Reportes Programados"
      - "Actualizacion de trazabilidad RF -> implementacion"

  - date: "2026-01-06"
    action: "Sprint 8 - Backend Implementation"
    author: Backend-Agent
    changes:
      - "DDL 14-reports.sql implementado"
      - "Schema reports con 12 tablas"
      - "API REST endpoints para dashboards"
      - "Servicios DashboardsService, WidgetsService"

  - date: "2026-01-07"
    action: "Sprint 9 - Frontend Implementation"
    author: Frontend-Agent
    changes:
      - "Feature dashboards con 24 archivos"
      - "15 tipos de widgets implementados"
      - "DashboardViewer con react-grid-layout"
      - "DashboardEditor con drag & drop"
      - "DashboardList con CRUD"
      - "Zustand store para state management"
      - "Hooks useDashboard, useDashboards"
      - "Recharts para visualizaciones"
      - "TypeScript build validado"
      - "Vite build validado"
      - "DB recreation validada"

  - date: "2026-01-07"
    action: "Sprint 10 - Report Builder Frontend"
    author: Frontend-Agent
    changes:
      - "Feature report-builder con 13 archivos"
      - "EntityExplorer - arbol de entidades"
      - "FieldSelector - selector de campos con agregaciones"
      - "FilterBuilder - constructor visual de filtros"
      - "ReportPreview - preview datos y SQL"
      - "ReportBuilder - componente principal"
      - "Zustand store para state management"
      - "API client para endpoints Report Builder"
      - "Types completos con operadores y agregaciones"
      - "TypeScript build validado"
      - "Vite build validado"

  - date: "2026-01-07"
    action: "Sprint 11 - Scheduled Reports Frontend"
    author: Frontend-Agent
    changes:
      - "Feature scheduled-reports con 11 archivos"
      - "CronBuilder - constructor visual de expresiones cron"
      - "RecipientManager - gestion de destinatarios email"
      - "ExecutionHistory - historial de ejecuciones"
      - "ScheduleList - lista de programaciones con CRUD"
      - "ScheduleForm - formulario completo de configuracion"
      - "Zustand store para state management"
      - "API client para endpoints Scheduled Reports"
      - "Types con cron presets, timezones, delivery methods"
      - "4 metodos de entrega: none, email, storage, webhook"
      - "4 formatos de exportacion: PDF, Excel, CSV, JSON"
      - "TypeScript build validado"
      - "Vite build validado"

  - date: "2026-01-07"
    action: "Sprint 12 - Pages & Navigation"
    author: Frontend-Agent
    changes:
      - "ReportsPage - Landing page con cards de navegacion"
      - "ReportBuilderPage - Integra componente ReportBuilder"
      - "ScheduledReportsPage - Integra ScheduleList, ScheduleForm, ExecutionHistory"
      - "routes.tsx - Rutas lazy loading para /reports/*"
      - "DashboardLayout.tsx - Items Dashboards y Reportes en sidebar"
      - "TypeScript build validado"
      - "Vite build validado"

  - date: "2026-01-07"
    action: "Sprint 13 - Unit Tests"
    author: Frontend-Agent
    changes:
      - "CronBuilder.test.tsx - 12 tests para constructor cron"
      - "RecipientManager.test.tsx - 13 tests para gestion destinatarios"
      - "FilterBuilder.test.tsx - 10 tests para constructor filtros"
      - "EntityExplorer.test.tsx - 21 tests para explorador entidades"
      - "Total: 56 tests nuevos, 94 tests en suite completa"
      - "Cobertura: rendering, interaccion, validacion, estados"
      - "Modulo MGN-009 completado al 100% con tests"

  - date: "2026-01-07"
    action: "BE-026 - PDF Export Implementation"
    author: Backend-Agent
    changes:
      - "PdfService - Servicio puppeteer para generacion PDF"
      - "ReportTemplates - Templates HTML para reportes financieros"
      - "ExportService actualizado para usar PdfService"
      - "Endpoints exportacion: /executions/:id/export, /trial-balance/export"
      - "Endpoint health check: /pdf/health"
      - "Soporte para formatos: PDF, XLSX, CSV, JSON, HTML"
      - "Templates: tabular, financial, trialBalance, dashboard"
      - "TypeScript build validado"
