-- ============================================================
-- quoERP — Configuración: IVA, Numeración SRI, Acceso Módulos
-- Migración: 013_settings_tax_sri_modules.sql
-- Versión: 1.0.0 | Fecha: 2026-06-06
-- ============================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ─────────────────────────────────────────────────────────────
-- TABLA: tax_rates — Historial de tasas de IVA por empresa
-- Permite configurar el % de IVA vigente con fecha de entrada
-- en vigor. Cada cambio queda en el log para auditoría.
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS tax_rates (
    id             INT UNSIGNED    NOT NULL AUTO_INCREMENT,
    company_id     INT UNSIGNED    NOT NULL,
    rate           DECIMAL(5,2)    NOT NULL
        COMMENT 'Porcentaje IVA vigente (Ej: 12.00 = 12%)',
    effective_from DATE            NOT NULL
        COMMENT 'Fecha a partir de la cual rige esta tasa',
    is_current     TINYINT(1)      NOT NULL DEFAULT 0
        COMMENT '1 = tasa actualmente vigente para la empresa',
    notes          TEXT            DEFAULT NULL,
    created_by     INT UNSIGNED    DEFAULT NULL,
    created_at     DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,

    PRIMARY KEY (id),
    INDEX idx_company   (company_id),
    INDEX idx_effective (company_id, effective_from),

    CONSTRAINT fk_tr_company FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Historial de tasas de IVA vigentes. Solo un registro con is_current=1 por empresa.';


-- ─────────────────────────────────────────────────────────────
-- TABLA: sri_invoice_config — Numeración de facturas SRI Ecuador
-- Formato: 001-001-000000001
--   Local (3) + Punto Venta (3) + Secuencia (9)
-- La Secuencia se incrementa automáticamente con cada factura.
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS sri_invoice_config (
    id             INT UNSIGNED    NOT NULL AUTO_INCREMENT,
    company_id     INT UNSIGNED    NOT NULL,
    local_code     CHAR(3)         NOT NULL DEFAULT '001'
        COMMENT 'Código de establecimiento (001-999)',
    pos_code       CHAR(3)         NOT NULL DEFAULT '001'
        COMMENT 'Código de punto de emisión (001-999)',
    sequence       INT UNSIGNED    NOT NULL DEFAULT 1
        COMMENT 'Número secuencial actual (se incrementa por factura)',
    is_active      TINYINT(1)      NOT NULL DEFAULT 1,
    updated_by     INT UNSIGNED    DEFAULT NULL,
    updated_at     DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    PRIMARY KEY (id),
    UNIQUE KEY uq_company (company_id),

    CONSTRAINT fk_sic_company FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Configuración de numeración SRI. Secuencia se auto-incrementa con cada factura emitida.';


-- ─────────────────────────────────────────────────────────────
-- TABLA: company_module_access — Control de acceso a módulos
-- Permite activar/desactivar módulos por empresa.
-- Solo visible y editable por usuarios SuperAdmin.
-- Si is_enabled=0, el módulo muestra pantalla "No Disponible".
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS company_module_access (
    id             INT UNSIGNED    NOT NULL AUTO_INCREMENT,
    company_id     INT UNSIGNED    NOT NULL,
    module_key     VARCHAR(50)     NOT NULL
        COMMENT 'Clave del módulo (sales, inventory, purchases, finance, hr, payroll, maintenance, chat)',
    is_enabled     TINYINT(1)      NOT NULL DEFAULT 1,
    updated_by     INT UNSIGNED    DEFAULT NULL,
    updated_at     DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    PRIMARY KEY (id),
    UNIQUE KEY uq_module (company_id, module_key),
    INDEX idx_company (company_id),

    CONSTRAINT fk_cma_company FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Control de acceso a módulos por empresa. Solo SuperAdmin puede gestionar.';


-- ─────────────────────────────────────────────────────────────
-- AJUSTE: sale_invoices — campos SRI e integración con OT
-- ─────────────────────────────────────────────────────────────
ALTER TABLE sale_invoices
    ADD COLUMN IF NOT EXISTS sri_number     VARCHAR(17)  DEFAULT NULL
        COMMENT 'N° SRI: 001-001-000000001. Identificador oficial para el SRI Ecuador.',
    ADD COLUMN IF NOT EXISTS work_order_id  INT UNSIGNED DEFAULT NULL
        COMMENT 'OT de origen cuando la factura se generó desde el módulo de Mantenimiento',
    ADD INDEX IF NOT EXISTS idx_sri_number  (sri_number),
    ADD INDEX IF NOT EXISTS idx_wo          (work_order_id);


SET FOREIGN_KEY_CHECKS = 1;

-- ─────────────────────────────────────────────────────────────
-- FIN DE MIGRACIÓN
-- Tablas nuevas: tax_rates, sri_invoice_config, company_module_access
-- ALTER sale_invoices: sri_number, work_order_id
-- ─────────────────────────────────────────────────────────────
