# TRACEABILITY.yml - MAE-008: Contabilidad
# Matriz de trazabilidad: Documentacion -> Codigo
# Ubicacion: apps/verticales/construccion/docs/02-definicion-modulos/MAE-008-contabilidad/implementacion/

epic_code: MAE-008
epic_name: Contabilidad
vertical: construccion
phase: 2
phase_name: Modulos de Negocio
story_points: 30
status: rf_documented

# =============================================================================
# REUTILIZACION DE CORE
# =============================================================================

reusability:
  core_module: MGN-010
  core_module_name: Financial
  reuse_percentage: 65
  strategy: extension
  description: |
    Este modulo extiende la funcionalidad base de MGN-010 (Financial) para
    adaptarla a las necesidades especificas del vertical de construccion.
    Se reutiliza la infraestructura contable base (cuentas, asientos, periodos)
    y se extiende con funcionalidad especifica para construccion.

  reused_components:
    database:
      - chart_of_accounts
      - accounts
      - account_balances
      - currencies
      - exchange_rates
      - fiscal_years
      - fiscal_periods
      - journal_entries
      - journal_lines
      - cost_centers

    services:
      - ChartOfAccountsService
      - AccountsService
      - CurrenciesService
      - ExchangeRateService
      - FiscalPeriodService
      - JournalService

    endpoints:
      - GET /api/v1/financial/charts
      - POST /api/v1/financial/charts
      - GET /api/v1/financial/charts/:id/accounts
      - POST /api/v1/financial/charts/:id/accounts
      - GET /api/v1/financial/currencies
      - POST /api/v1/financial/currencies/convert
      - GET /api/v1/financial/fiscal-years
      - POST /api/v1/financial/fiscal-years
      - GET /api/v1/financial/journal
      - POST /api/v1/financial/journal
      - POST /api/v1/financial/journal/:id/post

  extended_components:
    - component: cost_centers
      extension: Vinculacion con obras y frentes de trabajo
    - component: journal_entries
      extension: Integracion con estimaciones y valuaciones
    - component: account_balances
      extension: Reportes por obra y centro de costos
    - component: accounts
      extension: Plantilla de cuentas especifica para construccion

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

documentation:

  requirements:
    - id: RF-CONT-001
      title: Catalogo de Cuentas Contables
      file: ../requerimientos/RF-CONT-001.md
      priority: P0
      story_points: 8
      status: documented
      reuses: RF-FIN-001
      extensions:
        - Plantilla de cuentas especifica para construccion
        - Cuentas predefinidas para estimaciones y anticipos
        - Cuentas de costos por tipo de obra
        - Integracion con catalogo de obras (MAE-002)
      traces_to:
        tables: [chart_of_accounts, accounts, account_balances]
        services: [ChartOfAccountsService, AccountsService, ConstructionAccountsService]
        endpoints:
          - GET /api/v1/construccion/contabilidad/catalogo-cuentas
          - POST /api/v1/construccion/contabilidad/catalogo-cuentas/:id/accounts
          - GET /api/v1/construccion/contabilidad/plantillas/construccion

    - id: RF-CONT-002
      title: Polizas Contables
      file: ../requerimientos/RF-CONT-002.md
      priority: P0
      story_points: 8
      status: documented
      reuses: RF-FIN-004
      extensions:
        - Polizas automaticas desde estimaciones
        - Polizas automaticas desde valuaciones de obra
        - Polizas de anticipos a proveedores
        - Polizas de retenciones (5 al millar, IMSS patronal)
        - Vinculacion con obras y subcontratos
      traces_to:
        tables: [journal_entries, journal_lines, cost_centers, construction_journal_sources]
        services: [JournalService, ConstructionJournalService, EstimationJournalService]
        endpoints:
          - GET /api/v1/construccion/contabilidad/polizas
          - POST /api/v1/construccion/contabilidad/polizas
          - POST /api/v1/construccion/contabilidad/polizas/desde-estimacion
          - POST /api/v1/construccion/contabilidad/polizas/desde-valuacion
          - POST /api/v1/construccion/contabilidad/polizas/:id/mayorizar

    - id: RF-CONT-003
      title: Balanzas y Estados Financieros
      file: ../requerimientos/RF-CONT-003.md
      priority: P0
      story_points: 8
      status: documented
      reuses: RF-FIN-001
      extensions:
        - Balanza por obra
        - Balanza por centro de costos
        - Estado de resultados por obra
        - Comparativos presupuesto vs real
        - Exportacion a Excel con formatos fiscales
      traces_to:
        tables: [account_balances, fiscal_periods, construction_balance_views]
        services: [AccountsService, BalanceService, ConstructionBalanceService]
        endpoints:
          - GET /api/v1/construccion/contabilidad/balanza
          - GET /api/v1/construccion/contabilidad/balanza/por-obra
          - GET /api/v1/construccion/contabilidad/estados-financieros
          - GET /api/v1/construccion/contabilidad/estados-financieros/por-obra
          - POST /api/v1/construccion/contabilidad/exportar/balanza

    - id: RF-CONT-004
      title: Centro de Costos
      file: ../requerimientos/RF-CONT-004.md
      priority: P0
      story_points: 6
      status: documented
      reuses: RF-FIN-004
      extensions:
        - Centros de costo vinculados a obras
        - Centros de costo vinculados a frentes de trabajo
        - Centros de costo por tipo de actividad
        - Jerarquia de centros de costos
        - Reporte de costos por centro
      traces_to:
        tables: [cost_centers, construction_cost_centers]
        services: [CostCenterService, ConstructionCostCenterService]
        endpoints:
          - GET /api/v1/construccion/contabilidad/centros-costo
          - POST /api/v1/construccion/contabilidad/centros-costo
          - GET /api/v1/construccion/contabilidad/centros-costo/:id/costos
          - GET /api/v1/construccion/contabilidad/centros-costo/por-obra/:obraId

  specifications: []
  # Pendiente de documentacion

  user_stories: []
  # Pendiente de documentacion

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

implementation:

  database:
    schema: construccion_contabilidad
    path: apps/database/ddl/schemas/construccion_contabilidad/
    status: pending
    note: Extiende core_financial con tablas especificas de construccion

    tables:
      # Tablas extendidas de core
      - name: construction_cost_centers
        file: apps/database/ddl/schemas/construccion_contabilidad/tables/construction_cost_centers.sql
        status: pending
        requirement: RF-CONT-004
        extends: cost_centers
        columns:
          - {name: id, type: UUID, pk: true, fk: cost_centers}
          - {name: obra_id, type: UUID, fk: obras}
          - {name: frente_trabajo_id, type: UUID, fk: frentes_trabajo, nullable: true}
          - {name: activity_type, type: VARCHAR(50)}
          - {name: budget_amount, type: "DECIMAL(18,4)"}
          - {name: actual_amount, type: "DECIMAL(18,4)", default: 0}
          - {name: variance, type: "DECIMAL(18,4)", default: 0}
          - {name: created_at, type: TIMESTAMPTZ}
          - {name: updated_at, type: TIMESTAMPTZ}

      - name: construction_journal_sources
        file: apps/database/ddl/schemas/construccion_contabilidad/tables/construction_journal_sources.sql
        status: pending
        requirement: RF-CONT-002
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: journal_entry_id, type: UUID, fk: journal_entries}
          - {name: source_module, type: VARCHAR(50)}
          - {name: estimacion_id, type: UUID, fk: estimaciones, nullable: true}
          - {name: valuacion_id, type: UUID, fk: valuaciones, nullable: true}
          - {name: obra_id, type: UUID, fk: obras, nullable: true}
          - {name: subcontrato_id, type: UUID, fk: subcontratos, nullable: true}
          - {name: created_at, type: TIMESTAMPTZ}

      - name: construction_account_templates
        file: apps/database/ddl/schemas/construccion_contabilidad/tables/construction_account_templates.sql
        status: pending
        requirement: RF-CONT-001
        columns:
          - {name: id, type: UUID, pk: true}
          - {name: code, type: VARCHAR(50)}
          - {name: name, type: VARCHAR(255)}
          - {name: account_type, type: VARCHAR(50)}
          - {name: purpose, type: VARCHAR(100)}
          - {name: is_default, type: BOOLEAN, default: false}
          - {name: created_at, type: TIMESTAMPTZ}

      # Vistas para reportes
      - name: construction_balance_views
        file: apps/database/ddl/schemas/construccion_contabilidad/views/construction_balance_views.sql
        status: pending
        requirement: RF-CONT-003
        type: VIEW
        description: Vistas materializadas para balanzas por obra y centro de costos

  backend:
    module: construccion/contabilidad
    path: apps/verticales/construccion/backend/src/modules/contabilidad/
    framework: NestJS
    status: pending
    note: Extiende modulos de core_financial

    entities:
      # Entidades extendidas
      - name: ConstructionCostCenter
        file: apps/verticales/construccion/backend/src/modules/contabilidad/entities/construction-cost-center.entity.ts
        status: pending
        requirement: RF-CONT-004
        extends: CostCenter

      - name: ConstructionJournalSource
        file: apps/verticales/construccion/backend/src/modules/contabilidad/entities/construction-journal-source.entity.ts
        status: pending
        requirement: RF-CONT-002

      - name: ConstructionAccountTemplate
        file: apps/verticales/construccion/backend/src/modules/contabilidad/entities/construction-account-template.entity.ts
        status: pending
        requirement: RF-CONT-001

    services:
      - name: ConstructionAccountsService
        file: apps/verticales/construccion/backend/src/modules/contabilidad/construction-accounts.service.ts
        status: pending
        requirement: RF-CONT-001
        extends: AccountsService
        methods:
          - {name: createFromTemplate, description: Crear catalogo desde plantilla construccion}
          - {name: getConstructionAccounts, description: Obtener cuentas especificas de construccion}
          - {name: validateConstructionCode, description: Validar codigo segun estandar construccion}

      - name: ConstructionJournalService
        file: apps/verticales/construccion/backend/src/modules/contabilidad/construction-journal.service.ts
        status: pending
        requirement: RF-CONT-002
        extends: JournalService
        methods:
          - {name: createFromEstimacion, description: Crear poliza desde estimacion}
          - {name: createFromValuacion, description: Crear poliza desde valuacion}
          - {name: createAnticipo, description: Crear poliza de anticipo}
          - {name: createRetencion, description: Crear poliza de retenciones}
          - {name: getByObra, description: Obtener polizas por obra}

      - name: EstimationJournalService
        file: apps/verticales/construccion/backend/src/modules/contabilidad/estimation-journal.service.ts
        status: pending
        requirement: RF-CONT-002
        methods:
          - {name: generateJournalFromEstimacion, description: Generar asientos automaticos de estimacion}
          - {name: calculateRetenciones, description: Calcular retenciones (5 al millar, IMSS)}
          - {name: applyAnticipo, description: Aplicar anticipo a estimacion}

      - name: ConstructionBalanceService
        file: apps/verticales/construccion/backend/src/modules/contabilidad/construction-balance.service.ts
        status: pending
        requirement: RF-CONT-003
        methods:
          - {name: getBalanceByObra, description: Obtener balanza por obra}
          - {name: getBalanceByCostCenter, description: Obtener balanza por centro costos}
          - {name: getEstadoResultadosByObra, description: Estado de resultados por obra}
          - {name: getComparativoBudget, description: Comparativo presupuesto vs real}
          - {name: exportToExcel, description: Exportar balanza a Excel}

      - name: ConstructionCostCenterService
        file: apps/verticales/construccion/backend/src/modules/contabilidad/construction-cost-center.service.ts
        status: pending
        requirement: RF-CONT-004
        methods:
          - {name: createByObra, description: Crear centro de costos por obra}
          - {name: createByFrente, description: Crear centro costos por frente}
          - {name: getCostosByCenter, description: Obtener costos acumulados}
          - {name: getVariance, description: Calcular variacion presupuesto vs real}

    controllers:
      - name: ConstructionAccountsController
        file: apps/verticales/construccion/backend/src/modules/contabilidad/controllers/construction-accounts.controller.ts
        status: pending
        endpoints:
          - method: GET
            path: /api/v1/construccion/contabilidad/catalogo-cuentas
            description: Listar catalogo de cuentas
            requirement: RF-CONT-001

          - method: POST
            path: /api/v1/construccion/contabilidad/catalogo-cuentas
            description: Crear catalogo desde plantilla
            requirement: RF-CONT-001

          - method: GET
            path: /api/v1/construccion/contabilidad/plantillas/construccion
            description: Obtener plantilla de cuentas para construccion
            requirement: RF-CONT-001

          - method: POST
            path: /api/v1/construccion/contabilidad/catalogo-cuentas/:id/accounts
            description: Crear cuenta en catalogo
            requirement: RF-CONT-001

      - name: ConstructionJournalController
        file: apps/verticales/construccion/backend/src/modules/contabilidad/controllers/construction-journal.controller.ts
        status: pending
        endpoints:
          - method: GET
            path: /api/v1/construccion/contabilidad/polizas
            description: Listar polizas contables
            requirement: RF-CONT-002

          - method: POST
            path: /api/v1/construccion/contabilidad/polizas
            description: Crear poliza manual
            requirement: RF-CONT-002

          - method: POST
            path: /api/v1/construccion/contabilidad/polizas/desde-estimacion
            description: Generar poliza desde estimacion
            requirement: RF-CONT-002

          - method: POST
            path: /api/v1/construccion/contabilidad/polizas/desde-valuacion
            description: Generar poliza desde valuacion
            requirement: RF-CONT-002

          - method: POST
            path: /api/v1/construccion/contabilidad/polizas/:id/mayorizar
            description: Mayorizar poliza
            requirement: RF-CONT-002

          - method: GET
            path: /api/v1/construccion/contabilidad/polizas/obra/:obraId
            description: Obtener polizas por obra
            requirement: RF-CONT-002

      - name: ConstructionBalanceController
        file: apps/verticales/construccion/backend/src/modules/contabilidad/controllers/construction-balance.controller.ts
        status: pending
        endpoints:
          - method: GET
            path: /api/v1/construccion/contabilidad/balanza
            description: Obtener balanza general
            requirement: RF-CONT-003

          - method: GET
            path: /api/v1/construccion/contabilidad/balanza/por-obra
            description: Obtener balanza por obra
            requirement: RF-CONT-003

          - method: GET
            path: /api/v1/construccion/contabilidad/estados-financieros
            description: Obtener estados financieros
            requirement: RF-CONT-003

          - method: GET
            path: /api/v1/construccion/contabilidad/estados-financieros/por-obra
            description: Estados financieros por obra
            requirement: RF-CONT-003

          - method: POST
            path: /api/v1/construccion/contabilidad/exportar/balanza
            description: Exportar balanza a Excel
            requirement: RF-CONT-003

      - name: ConstructionCostCenterController
        file: apps/verticales/construccion/backend/src/modules/contabilidad/controllers/construction-cost-center.controller.ts
        status: pending
        endpoints:
          - method: GET
            path: /api/v1/construccion/contabilidad/centros-costo
            description: Listar centros de costo
            requirement: RF-CONT-004

          - method: POST
            path: /api/v1/construccion/contabilidad/centros-costo
            description: Crear centro de costo
            requirement: RF-CONT-004

          - method: GET
            path: /api/v1/construccion/contabilidad/centros-costo/:id/costos
            description: Obtener costos acumulados
            requirement: RF-CONT-004

          - method: GET
            path: /api/v1/construccion/contabilidad/centros-costo/por-obra/:obraId
            description: Centros de costo por obra
            requirement: RF-CONT-004

  frontend:
    module: construccion/contabilidad
    path: apps/verticales/construccion/frontend/src/modules/contabilidad/
    framework: Angular
    status: pending
    note: Reutiliza componentes de core_financial

    components:
      - name: CatalogoCuentasComponent
        file: apps/verticales/construccion/frontend/src/modules/contabilidad/components/catalogo-cuentas.component.ts
        status: pending
        requirement: RF-CONT-001

      - name: PolizasListComponent
        file: apps/verticales/construccion/frontend/src/modules/contabilidad/components/polizas-list.component.ts
        status: pending
        requirement: RF-CONT-002

      - name: PolizaFormComponent
        file: apps/verticales/construccion/frontend/src/modules/contabilidad/components/poliza-form.component.ts
        status: pending
        requirement: RF-CONT-002

      - name: BalanzaComponent
        file: apps/verticales/construccion/frontend/src/modules/contabilidad/components/balanza.component.ts
        status: pending
        requirement: RF-CONT-003

      - name: EstadosFinancierosComponent
        file: apps/verticales/construccion/frontend/src/modules/contabilidad/components/estados-financieros.component.ts
        status: pending
        requirement: RF-CONT-003

      - name: CentrosCostoComponent
        file: apps/verticales/construccion/frontend/src/modules/contabilidad/components/centros-costo.component.ts
        status: pending
        requirement: RF-CONT-004

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

dependencies:
  depends_on:
    # Dependencias de core
    - module: MGN-010
      type: hard
      reason: Reutiliza funcionalidad base de contabilidad (65%)
    - module: MGN-001
      type: hard
      reason: Autenticacion requerida
    - module: MGN-004
      type: hard
      reason: Aislamiento por tenant
    - module: MGN-005
      type: soft
      reason: Catalogos de monedas, tipos cuenta

    # Dependencias del vertical construccion
    - module: MAE-002
      type: hard
      reason: Vinculacion con obras para centros de costo y reportes
    - module: MAE-004
      type: hard
      reason: Generacion de polizas desde estimaciones
    - module: MAE-005
      type: soft
      reason: Generacion de polizas desde subcontratos

  required_by:
    - module: MAE-009
      type: soft
      reason: Tesoreria requiere polizas contables
    - module: MAE-010
      type: soft
      reason: Reportes financieros consolidan informacion contable

# =============================================================================
# INTEGRACIONES
# =============================================================================

integrations:
  - module: MAE-004
    name: Estimaciones
    integration_points:
      - Generacion automatica de polizas desde estimaciones
      - Contabilizacion de anticipos y retenciones
      - Vinculacion estimacion -> poliza -> obra

  - module: MAE-002
    name: Obras
    integration_points:
      - Centros de costo por obra
      - Balanzas y estados financieros por obra
      - Comparativos presupuesto vs real

  - module: MAE-005
    name: Subcontratos
    integration_points:
      - Polizas de subcontratos
      - Retenciones a subcontratistas

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

metrics:
  story_points:
    estimated: 30
    actual: null
    note: Reducido vs MGN-010 (45) por reutilizacion del 65%

  documentation:
    requirements: 4
    specifications: 0
    user_stories: 0

  files:
    database: 5
    backend: 15
    frontend: 8
    total: 28
    reused_from_core: 30

  reusability:
    core_tables_reused: 10
    core_services_reused: 6
    core_endpoints_reused: 11
    new_tables: 3
    new_services: 5
    new_endpoints: 14

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

history:
  - date: "2025-12-06"
    action: "Creacion de estructura GAMILIT"
    author: Requirements-Analyst
    changes:
      - "Creacion de TRACEABILITY.yml para MAE-008"
      - "Definicion de estructura basada en MGN-010"
      - "Definicion de reutilizacion del 65% de core"
      - "Definicion de 4 RF especificos de construccion"
      - "RF-CONT-001: Catalogo de Cuentas Contables"
      - "RF-CONT-002: Polizas Contables"
      - "RF-CONT-003: Balanzas y Estados Financieros"
      - "RF-CONT-004: Centro de Costos"
      - "Definicion de integraciones con MAE-002, MAE-004, MAE-005"
