# TRACEABILITY.yml - MGN-007: Audit
# Matriz de trazabilidad: Documentacion -> Codigo
# Ubicacion: docs/02-fase-core-business/MGN-007-audit/implementacion/

epic_code: MGN-007
epic_name: Audit
phase: 2
phase_name: Core Business
story_points: 30
status: rf_documented

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

documentation:

  requirements:
    - id: RF-AUDIT-001
      title: Audit Trail
      file: ../requerimientos/RF-AUDIT-001.md
      priority: P0
      story_points: 10
      status: documented
      traces_to:
        tables: [audit_logs]
        services: [AuditTrailService]
        endpoints: [GET /api/v1/audit/logs, GET /api/v1/audit/entity/:type/:id/history]

    - id: RF-AUDIT-002
      title: Access Logs
      file: ../requerimientos/RF-AUDIT-002.md
      priority: P0
      story_points: 8
      status: documented
      traces_to:
        tables: [access_logs]
        services: [AccessLogService]
        interceptors: [AccessLogInterceptor]
        endpoints: [GET /api/v1/audit/access, GET /api/v1/audit/access/stats]

    - id: RF-AUDIT-003
      title: Security Events
      file: ../requerimientos/RF-AUDIT-003.md
      priority: P0
      story_points: 8
      status: documented
      traces_to:
        tables: [security_events]
        services: [SecurityEventService]
        endpoints: [GET /api/v1/audit/security, GET /api/v1/audit/security/alerts]

    - id: RF-AUDIT-004
      title: Consultas y Reportes de Auditoria
      file: ../requerimientos/RF-AUDIT-004.md
      priority: P1
      story_points: 5
      status: documented
      traces_to:
        tables: [audit_reports]
        services: [AuditQueryService]
        endpoints: [GET /api/v1/audit/search, GET /api/v1/audit/export, POST /api/v1/audit/reports]

  specifications: []
  # Pendiente de documentacion

  user_stories: []
  # Pendiente de documentacion

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

implementation:

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

    tables:
      - name: audit_logs
        file: apps/database/ddl/schemas/core_audit/tables/audit_logs.sql
        status: pending
        requirement: RF-AUDIT-001
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants}
          - {name: user_id, type: UUID, fk: users}
          - {name: action, type: VARCHAR(50)}
          - {name: entity_type, type: VARCHAR(100)}
          - {name: entity_id, type: UUID}
          - {name: old_values, type: JSONB}
          - {name: new_values, type: JSONB}
          - {name: changed_fields, type: JSONB}
          - {name: ip_address, type: INET}
          - {name: user_agent, type: TEXT}
          - {name: correlation_id, type: UUID}
          - {name: created_at, type: TIMESTAMPTZ}

      - name: access_logs
        file: apps/database/ddl/schemas/core_audit/tables/access_logs.sql
        status: pending
        requirement: RF-AUDIT-002
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants}
          - {name: user_id, type: UUID, fk: users}
          - {name: method, type: VARCHAR(10)}
          - {name: path, type: VARCHAR(500)}
          - {name: query_params, type: JSONB}
          - {name: status_code, type: INTEGER}
          - {name: response_time_ms, type: INTEGER}
          - {name: request_size, type: INTEGER}
          - {name: response_size, type: INTEGER}
          - {name: ip_address, type: INET}
          - {name: user_agent, type: TEXT}
          - {name: correlation_id, type: UUID}
          - {name: created_at, type: TIMESTAMPTZ}

      - name: security_events
        file: apps/database/ddl/schemas/core_audit/tables/security_events.sql
        status: pending
        requirement: RF-AUDIT-003
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants, nullable: true}
          - {name: user_id, type: UUID, fk: users, nullable: true}
          - {name: event_type, type: VARCHAR(50)}
          - {name: severity, type: VARCHAR(20)}
          - {name: description, type: TEXT}
          - {name: metadata, type: JSONB}
          - {name: ip_address, type: INET}
          - {name: geo_location, type: JSONB}
          - {name: is_alert, type: BOOLEAN, default: false}
          - {name: acknowledged_at, type: TIMESTAMPTZ}
          - {name: acknowledged_by, type: UUID}
          - {name: created_at, type: TIMESTAMPTZ}

      - name: audit_reports
        file: apps/database/ddl/schemas/core_audit/tables/audit_reports.sql
        status: pending
        requirement: RF-AUDIT-004
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: tenant_id, type: UUID, fk: tenants}
          - {name: name, type: VARCHAR(255)}
          - {name: report_type, type: VARCHAR(50)}
          - {name: filters, type: JSONB}
          - {name: schedule, type: VARCHAR(100)}
          - {name: recipients, type: JSONB}
          - {name: last_run_at, type: TIMESTAMPTZ}
          - {name: is_active, type: BOOLEAN, default: true}
          - {name: created_at, type: TIMESTAMPTZ}

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

    entities:
      - name: AuditLog
        file: apps/backend/src/modules/audit/entities/audit-log.entity.ts
        status: pending
        requirement: RF-AUDIT-001

      - name: AccessLog
        file: apps/backend/src/modules/audit/entities/access-log.entity.ts
        status: pending
        requirement: RF-AUDIT-002

      - name: SecurityEvent
        file: apps/backend/src/modules/audit/entities/security-event.entity.ts
        status: pending
        requirement: RF-AUDIT-003

      - name: AuditReport
        file: apps/backend/src/modules/audit/entities/audit-report.entity.ts
        status: pending
        requirement: RF-AUDIT-004

    services:
      - name: AuditTrailService
        file: apps/backend/src/modules/audit/audit-trail.service.ts
        status: pending
        requirement: RF-AUDIT-001
        methods:
          - {name: log, description: Registrar evento de auditoria}
          - {name: getEntityHistory, description: Obtener historial de entidad}
          - {name: search, description: Buscar en audit logs}

      - name: AccessLogService
        file: apps/backend/src/modules/audit/access-log.service.ts
        status: pending
        requirement: RF-AUDIT-002
        methods:
          - {name: log, description: Registrar acceso HTTP}
          - {name: getStats, description: Obtener estadisticas de acceso}
          - {name: search, description: Buscar en access logs}

      - name: SecurityEventService
        file: apps/backend/src/modules/audit/security-event.service.ts
        status: pending
        requirement: RF-AUDIT-003
        methods:
          - {name: log, description: Registrar evento de seguridad}
          - {name: detectPatterns, description: Detectar patrones sospechosos}
          - {name: acknowledgeAlert, description: Reconocer alerta}

      - name: AuditQueryService
        file: apps/backend/src/modules/audit/audit-query.service.ts
        status: pending
        requirement: RF-AUDIT-004
        methods:
          - {name: search, description: Busqueda unificada}
          - {name: export, description: Exportar logs}
          - {name: generateReport, description: Generar reporte}

    interceptors:
      - name: AuditInterceptor
        file: apps/backend/src/modules/audit/interceptors/audit.interceptor.ts
        status: pending
        requirement: RF-AUDIT-001
        description: Interceptor para auditoria automatica de cambios

      - name: AccessLogInterceptor
        file: apps/backend/src/modules/audit/interceptors/access-log.interceptor.ts
        status: pending
        requirement: RF-AUDIT-002
        description: Interceptor para logging de acceso HTTP

    controllers:
      - name: AuditController
        file: apps/backend/src/modules/audit/audit.controller.ts
        status: pending
        endpoints:
          - method: GET
            path: /api/v1/audit/logs
            description: Listar logs de auditoria
            requirement: RF-AUDIT-001

          - method: GET
            path: /api/v1/audit/entity/:type/:id/history
            description: Historial de cambios de entidad
            requirement: RF-AUDIT-001

          - method: GET
            path: /api/v1/audit/access
            description: Listar logs de acceso
            requirement: RF-AUDIT-002

          - method: GET
            path: /api/v1/audit/access/stats
            description: Estadisticas de acceso
            requirement: RF-AUDIT-002

          - method: GET
            path: /api/v1/audit/security
            description: Listar eventos de seguridad
            requirement: RF-AUDIT-003

          - method: GET
            path: /api/v1/audit/security/alerts
            description: Listar alertas activas
            requirement: RF-AUDIT-003

          - method: GET
            path: /api/v1/audit/search
            description: Busqueda unificada
            requirement: RF-AUDIT-004

          - method: GET
            path: /api/v1/audit/export
            description: Exportar logs
            requirement: RF-AUDIT-004

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

dependencies:
  depends_on:
    - module: MGN-001
      type: hard
      reason: Autenticacion requerida
    - module: MGN-002
      type: hard
      reason: Referencia a usuarios
    - module: MGN-004
      type: hard
      reason: Aislamiento por tenant

  required_by: []
  # Modulo transversal, no tiene dependientes directos

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

metrics:
  story_points:
    estimated: 30
    actual: null

  documentation:
    requirements: 4
    specifications: 0
    user_stories: 0

  files:
    database: 4
    backend: 10
    frontend: 3
    total: 17

# =============================================================================
# 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-AUDIT-001: Audit Trail"
      - "RF-AUDIT-002: Access Logs"
      - "RF-AUDIT-003: Security Events"
      - "RF-AUDIT-004: Consultas y Reportes"
      - "Actualizacion de trazabilidad RF -> implementacion"
