-- ============================================================
-- quoERP — Cierre contable de períodos
-- Migración: 021_accounting_periods.sql
-- Versión: 1.0.0 | Fecha: 2026-06-07
-- ============================================================
-- Permite bloquear períodos mensuales o anuales para impedir
-- la creación o modificación de asientos en fechas pasadas.
-- El cierre anual genera el asiento de cierre de resultados
-- (cero ingresos/gastos → traslado a Resultados acumulados).
-- ============================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ─────────────────────────────────────────────────────────────
-- TABLA: accounting_periods — Control de períodos contables
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS accounting_periods (
    id              INT UNSIGNED   NOT NULL AUTO_INCREMENT,
    company_id      INT UNSIGNED   NOT NULL,
    year            SMALLINT UNSIGNED NOT NULL,
    month           TINYINT UNSIGNED  DEFAULT NULL
        COMMENT 'NULL = cierre anual del ejercicio; 1-12 = cierre mensual',
    label           VARCHAR(60)    NOT NULL
        COMMENT 'Ej: "Enero 2025", "Ejercicio 2025"',
    is_closed       TINYINT(1)     NOT NULL DEFAULT 0,
    closing_entry_id INT UNSIGNED  DEFAULT NULL
        COMMENT 'Asiento de cierre anual generado (solo para cierres anuales)',
    closed_at       DATETIME       DEFAULT NULL,
    closed_by       INT UNSIGNED   DEFAULT NULL,
    reopened_at     DATETIME       DEFAULT NULL,
    reopened_by     INT UNSIGNED   DEFAULT NULL,
    notes           TEXT           DEFAULT NULL,
    created_at      DATETIME       NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME       DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uk_period (company_id, year, month),
    INDEX idx_company (company_id),
    INDEX idx_closed  (is_closed)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─────────────────────────────────────────────────────────────
-- Cuentas para el asiento de cierre anual en company_account_map
-- ─────────────────────────────────────────────────────────────
ALTER TABLE company_account_map
    ADD COLUMN IF NOT EXISTS acc_current_year_result INT UNSIGNED DEFAULT NULL
        COMMENT 'Resultado del ejercicio (patrimonio). Receptora del cierre de ingresos/gastos.',
    ADD COLUMN IF NOT EXISTS acc_retained_earnings    INT UNSIGNED DEFAULT NULL
        COMMENT 'Resultados acumulados (patrimonio). Destino definitivo al cierre del ejercicio.';

SET FOREIGN_KEY_CHECKS = 1;

-- ─────────────────────────────────────────────────────────────
-- FIN DE MIGRACIÓN
-- Tablas nuevas: accounting_periods
-- ALTER: company_account_map (acc_current_year_result, acc_retained_earnings)
-- ─────────────────────────────────────────────────────────────
