-- =============================================================
-- ABISFACT - INSTALACION LIMPIA
-- Generado desde el esquema final validado del proyecto.
-- Requisito: ejecutar sobre una base de datos VACIA.
-- Usuario inicial: admin
-- Clave inicial: Admin123*
-- =============================================================

SET NAMES utf8mb4;
SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';
SET FOREIGN_KEY_CHECKS = 0;

-- =============================================================
-- 1. TABLAS
-- =============================================================

CREATE TABLE `acciones` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(80) NOT NULL,
  `nombre` varchar(120) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `auth_refresh_tokens` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `session_id` char(36) NOT NULL,
  `user_id` bigint(20) unsigned NOT NULL,
  `empresa_id` bigint(20) unsigned DEFAULT NULL,
  `token_hash` char(64) NOT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` varchar(255) DEFAULT NULL,
  `expires_at` datetime NOT NULL,
  `last_used_at` datetime DEFAULT NULL,
  `revoked_at` datetime DEFAULT NULL,
  `created_at` datetime NOT NULL DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_afectaciones_igv` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(4) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `tipo_afectacion` char(1) NOT NULL,
  `codigo_tributo` varchar(10) NOT NULL,
  `nombre_tributo` varchar(20) NOT NULL,
  `abreviatura` varchar(20) NOT NULL,
  `porcentaje` decimal(5,2) NOT NULL DEFAULT 0.00,
  `afecta_igv` tinyint(1) NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_detracciones` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(10) NOT NULL,
  `descripcion` varchar(180) NOT NULL,
  `porcentaje` decimal(6,2) NOT NULL DEFAULT 0.00,
  `limite_minimo` decimal(14,2) NOT NULL DEFAULT 0.00,
  `comentario` varchar(255) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_formas_pago` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(20) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `comentario` varchar(255) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_items` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tipo_id` bigint(20) unsigned NOT NULL COMMENT '1=Producto, 2=Servicio',
  `unidad_medida_id` bigint(20) unsigned DEFAULT NULL,
  `afectacion_igv_id` bigint(20) unsigned NOT NULL COMMENT 'Referencia a catalogo_afectaciones_igv',
  `catalogo_detraccion_id` bigint(20) unsigned DEFAULT NULL,
  `descripcion_editable` tinyint(1) NOT NULL DEFAULT 0,
  `codigo` varchar(50) DEFAULT NULL,
  `codigo_sunat` varchar(20) DEFAULT NULL,
  `codigo_gs1` varchar(20) DEFAULT NULL,
  `descripcion` varchar(255) NOT NULL,
  `unidad_medida` varchar(10) NOT NULL DEFAULT 'NIU',
  `valor_unitario` decimal(14,2) NOT NULL DEFAULT 0.00,
  `precio_unitario` decimal(14,2) NOT NULL DEFAULT 0.00,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_medios_pago` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(30) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `comentario` varchar(255) DEFAULT NULL,
  `es_credito` tinyint(1) NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_tipo_documentos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo_sunat` varchar(5) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `comentario` varchar(255) DEFAULT NULL,
  `orden` int(10) unsigned NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_tipo_items` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(20) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `comentario` varchar(255) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `catalogo_tipo_movimiento` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(20) NOT NULL,
  `descripcion` varchar(80) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `empresa_certificados_digitales` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `alias` varchar(120) NOT NULL,
  `archivo_pfx` varchar(600) NOT NULL,
  `password_pfx` varchar(255) NOT NULL,
  `fecha_vencimiento` date DEFAULT NULL,
  `es_activo` tinyint(1) NOT NULL DEFAULT 1,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `empresa_cuentas_bancarias` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `banco` varchar(120) NOT NULL,
  `moneda` char(3) NOT NULL DEFAULT 'PEN',
  `numero_cuenta` varchar(60) NOT NULL,
  `cci` varchar(60) DEFAULT NULL,
  `alias` varchar(120) DEFAULT NULL,
  `es_detracciones` tinyint(1) NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `empresa_modulos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `modulo_id` bigint(20) unsigned NOT NULL,
  `habilitado` tinyint(1) NOT NULL DEFAULT 1,
  `configuracion` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`configuracion`)),
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `empresa_sucursales` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `codigo` varchar(20) NOT NULL,
  `nombre` varchar(180) NOT NULL,
  `direccion` varchar(255) DEFAULT NULL,
  `telefono` varchar(50) DEFAULT NULL,
  `ubigeo` char(6) DEFAULT NULL,
  `logo` varchar(500) DEFAULT NULL,
  `es_principal` tinyint(1) NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `empresa_usuarios` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `usuario_id` bigint(20) unsigned NOT NULL,
  `rol_id` bigint(20) unsigned DEFAULT NULL,
  `estado` enum('ACTIVO','INACTIVO') NOT NULL DEFAULT 'ACTIVO',
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `empresas` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `ruc` char(11) NOT NULL,
  `razon_social` varchar(200) NOT NULL,
  `nombre_comercial` varchar(200) DEFAULT NULL,
  `logo` varchar(500) DEFAULT NULL,
  `tipo_empresa_id` bigint(20) unsigned NOT NULL DEFAULT 1,
  `giro_negocio_id` bigint(20) unsigned DEFAULT NULL,
  `sunat_usuario_secundario` varchar(120) DEFAULT NULL,
  `sunat_clave_secundaria` varchar(255) DEFAULT NULL,
  `sunat_client_id` varchar(120) DEFAULT NULL,
  `sunat_client_secret` varchar(255) DEFAULT NULL,
  `envio_automatico_activo` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0=Desactivado, 1=Activado',
  `envio_automatico_fecha_inicio` date DEFAULT NULL,
  `envio_automatico_boletas_modo` varchar(12) NOT NULL DEFAULT 'RESUMEN' COMMENT 'INDIVIDUAL o RESUMEN',
  `envio_automatico_facturas_dias` int(10) unsigned NOT NULL DEFAULT 3,
  `envio_automatico_boletas_dias` int(10) unsigned NOT NULL DEFAULT 5,
  `envio_automatico_resumen_dias` int(10) unsigned NOT NULL DEFAULT 7,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `requiere_placa_vehicular` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobante_detalles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `comprobante_id` bigint(20) unsigned NOT NULL,
  `catalogo_item_id` bigint(20) unsigned DEFAULT NULL,
  `unidad_medida_id` bigint(20) unsigned DEFAULT NULL,
  `item` int(10) unsigned NOT NULL,
  `descripcion` varchar(255) NOT NULL,
  `cantidad` decimal(14,2) NOT NULL DEFAULT 1.00,
  `unidad_medida` varchar(10) NOT NULL DEFAULT 'NIU',
  `valor_unitario` decimal(14,2) NOT NULL DEFAULT 0.00,
  `precio_unitario` decimal(14,2) NOT NULL DEFAULT 0.00,
  `descuento` decimal(14,2) NOT NULL DEFAULT 0.00,
  `afecto_igv` tinyint(1) NOT NULL DEFAULT 1,
  `afectacion_igv_id` bigint(20) unsigned DEFAULT NULL,
  `subtotal` decimal(14,2) NOT NULL DEFAULT 0.00,
  `igv` decimal(14,2) NOT NULL DEFAULT 0.00,
  `total` decimal(14,2) NOT NULL DEFAULT 0.00,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobante_detracciones` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `comprobante_id` bigint(20) unsigned NOT NULL,
  `catalogo_detraccion_id` bigint(20) unsigned DEFAULT NULL,
  `base` decimal(14,2) NOT NULL DEFAULT 0.00,
  `monto` decimal(14,2) NOT NULL DEFAULT 0.00,
  `created_by` bigint(20) unsigned DEFAULT NULL,
  `updated_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobante_eventos` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(30) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `comentario` varchar(255) DEFAULT NULL COMMENT 'Descripcion extendida del evento',
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobante_historial` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `comprobante_id` bigint(20) unsigned NOT NULL,
  `evento_id` tinyint(3) unsigned NOT NULL COMMENT 'Referencia a facturacion_comprobante_eventos.id',
  `detalle` varchar(500) DEFAULT NULL,
  `archivo_ruta` varchar(600) DEFAULT NULL,
  `respuesta` longtext DEFAULT NULL,
  `created_by` bigint(20) unsigned DEFAULT NULL,
  `updated_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `ticket` varchar(80) DEFAULT NULL COMMENT 'Ticket SUNAT cuando el evento lo genera',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobante_movimientos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `comprobante_id` bigint(20) unsigned NOT NULL,
  `tipo_movimiento_id` tinyint(3) unsigned NOT NULL,
  `numero_cuota` int(10) unsigned DEFAULT NULL,
  `medio_pago_id` bigint(20) unsigned DEFAULT NULL,
  `fecha_movimiento` date DEFAULT NULL,
  `monto` decimal(14,2) NOT NULL DEFAULT 0.00,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `referencia` varchar(150) DEFAULT NULL,
  `observacion` varchar(255) DEFAULT NULL,
  `created_by` bigint(20) unsigned DEFAULT NULL,
  `updated_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobantes` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `sucursal_id` bigint(20) unsigned DEFAULT NULL,
  `pos_id` bigint(20) unsigned DEFAULT NULL,
  `tipo_operacion_id` tinyint(3) unsigned NOT NULL DEFAULT 1,
  `tercero_id` bigint(20) unsigned DEFAULT NULL,
  `tipo_comprobante_id` bigint(20) unsigned NOT NULL,
  `comprobante_referencia_id` bigint(20) unsigned DEFAULT NULL,
  `nota_motivo_id` bigint(20) unsigned DEFAULT NULL,
  `nota_motivo_codigo` varchar(10) DEFAULT NULL,
  `nota_motivo_descripcion` varchar(180) DEFAULT NULL,
  `serie_id` bigint(20) unsigned DEFAULT NULL,
  `serie` varchar(10) NOT NULL,
  `numero` int(10) unsigned NOT NULL,
  `fecha_emision` date NOT NULL,
  `fecha_vencimiento` date DEFAULT NULL,
  `moneda` char(3) NOT NULL DEFAULT 'PEN',
  `placa_vehicular` varchar(15) DEFAULT NULL,
  `subtotal` decimal(14,2) NOT NULL DEFAULT 0.00,
  `igv` decimal(14,2) NOT NULL DEFAULT 0.00,
  `total` decimal(14,2) NOT NULL DEFAULT 0.00,
  `estado` enum('BORRADOR','EMITIDO','ANULADO') NOT NULL DEFAULT 'BORRADOR',
  `observacion` varchar(255) DEFAULT NULL,
  `created_by` bigint(20) unsigned DEFAULT NULL,
  `updated_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_conductores` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tipo_documento` varchar(2) NOT NULL DEFAULT '1',
  `numero_documento` varchar(20) NOT NULL,
  `nombres` varchar(150) NOT NULL,
  `apellidos` varchar(150) NOT NULL,
  `licencia` varchar(30) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_cotizacion_detalles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `cotizacion_id` bigint(20) unsigned NOT NULL,
  `catalogo_item_id` bigint(20) unsigned DEFAULT NULL,
  `unidad_medida_id` bigint(20) unsigned DEFAULT NULL,
  `item` varchar(30) DEFAULT NULL,
  `descripcion` varchar(255) NOT NULL,
  `cantidad` decimal(15,4) NOT NULL DEFAULT 0.0000,
  `unidad_medida` varchar(20) NOT NULL,
  `valor_unitario` decimal(15,2) NOT NULL DEFAULT 0.00,
  `precio_unitario` decimal(15,2) NOT NULL DEFAULT 0.00,
  `descuento` decimal(15,2) NOT NULL DEFAULT 0.00,
  `afecto_igv` tinyint(1) NOT NULL DEFAULT 1,
  `afectacion_igv_id` bigint(20) unsigned DEFAULT NULL,
  `subtotal` decimal(15,2) NOT NULL DEFAULT 0.00,
  `igv` decimal(15,2) NOT NULL DEFAULT 0.00,
  `total` decimal(15,2) NOT NULL DEFAULT 0.00,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_cotizaciones` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tercero_id` bigint(20) unsigned DEFAULT NULL,
  `tipo_operacion_id` tinyint(3) unsigned NOT NULL DEFAULT 3 COMMENT '3=Cotizacion',
  `serie` varchar(20) NOT NULL DEFAULT 'COT',
  `numero` int(10) unsigned NOT NULL DEFAULT 1,
  `fecha_emision` date NOT NULL,
  `fecha_vigencia` date DEFAULT NULL,
  `dias_vigencia` int(10) unsigned NOT NULL DEFAULT 15,
  `moneda` char(3) NOT NULL DEFAULT 'PEN',
  `subtotal` decimal(15,2) NOT NULL DEFAULT 0.00,
  `igv` decimal(15,2) NOT NULL DEFAULT 0.00,
  `total` decimal(15,2) NOT NULL DEFAULT 0.00,
  `estado` tinyint(3) unsigned NOT NULL DEFAULT 0 COMMENT '0=BORRADOR, 1=EMITIDO, 2=ANULADO, 3=ENVIADO, 4=PENDIENTE, 5=ACEPTADO, 6=RECHAZADO, 7=VENCIDO',
  `observacion` text DEFAULT NULL,
  `created_by` bigint(20) unsigned DEFAULT NULL,
  `updated_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_direcciones` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tercero_id` bigint(20) unsigned DEFAULT NULL COMMENT 'Opcional: direccion asociada a un tercero',
  `descripcion` varchar(255) NOT NULL,
  `ubigeo` varchar(6) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_guia_catalogos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `categoria` varchar(30) NOT NULL COMMENT 'MOTIVO_TRASLADO | MODALIDAD_TRANSPORTE',
  `codigo` varchar(5) NOT NULL,
  `descripcion` varchar(180) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_guia_transporte` (
  `comprobante_id` bigint(20) unsigned NOT NULL,
  `fecha_traslado` date NOT NULL,
  `peso_total` decimal(12,3) NOT NULL DEFAULT 0.000,
  `unidad_peso` varchar(10) NOT NULL DEFAULT 'KGM',
  `bultos` int(10) unsigned NOT NULL DEFAULT 0,
  `motivo_traslado_codigo` varchar(5) NOT NULL,
  `motivo_traslado_descripcion` varchar(180) DEFAULT NULL,
  `modalidad_transporte_codigo` varchar(5) NOT NULL,
  `transportista_id` bigint(20) unsigned DEFAULT NULL,
  `conductor_id` bigint(20) unsigned DEFAULT NULL,
  `direccion_partida_id` bigint(20) unsigned DEFAULT NULL,
  `direccion_llegada_id` bigint(20) unsigned DEFAULT NULL,
  `transportista_documento_tipo` varchar(2) DEFAULT NULL,
  `transportista_documento` varchar(20) DEFAULT NULL,
  `transportista_nombre` varchar(200) DEFAULT NULL,
  `transportista_registro_mtc` varchar(50) DEFAULT NULL,
  `conductor_documento_tipo` varchar(2) DEFAULT NULL,
  `conductor_documento` varchar(20) DEFAULT NULL,
  `conductor_nombres` varchar(150) DEFAULT NULL,
  `conductor_apellidos` varchar(150) DEFAULT NULL,
  `conductor_licencia` varchar(30) DEFAULT NULL,
  `placa` varchar(15) DEFAULT NULL,
  `indicador_m1l` tinyint(1) NOT NULL DEFAULT 0,
  `qr_sunat` varchar(500) DEFAULT NULL,
  `partida_ubigeo` varchar(6) NOT NULL,
  `partida_direccion` varchar(255) NOT NULL,
  `llegada_ubigeo` varchar(6) NOT NULL,
  `llegada_direccion` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`comprobante_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_integracion_endpoints` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(50) NOT NULL,
  `descripcion` varchar(180) NOT NULL,
  `tipo` varchar(40) NOT NULL,
  `proveedor` varchar(20) NOT NULL DEFAULT 'CUSTOM',
  `ambiente` varchar(20) NOT NULL DEFAULT 'PRODUCCION',
  `metodo` varchar(10) NOT NULL DEFAULT 'POST',
  `url` varchar(600) DEFAULT NULL,
  `headers_json` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`headers_json`)),
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `es_defecto` tinyint(1) NOT NULL DEFAULT 0,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_motivos_nota` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `tipo` char(1) NOT NULL COMMENT 'C = nota de credito, D = nota de debito',
  `codigo` varchar(10) NOT NULL,
  `descripcion` varchar(180) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_resumen_diario_detalles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `resumen_id` bigint(20) unsigned NOT NULL,
  `comprobante_id` bigint(20) unsigned NOT NULL,
  `line_id` int(10) unsigned NOT NULL,
  `documento_tipo_codigo` varchar(2) NOT NULL,
  `documento_serie` varchar(20) NOT NULL,
  `documento_numero` varchar(20) NOT NULL,
  `cliente_documento_tipo` varchar(5) DEFAULT NULL,
  `cliente_documento_numero` varchar(20) DEFAULT NULL,
  `cliente_razon_social` varchar(255) DEFAULT NULL,
  `condicion_code` varchar(2) NOT NULL DEFAULT '1',
  `moneda` varchar(3) NOT NULL DEFAULT 'PEN',
  `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  `gravadas` decimal(14,2) NOT NULL DEFAULT 0.00,
  `exoneradas` decimal(14,2) NOT NULL DEFAULT 0.00,
  `inafectas` decimal(14,2) NOT NULL DEFAULT 0.00,
  `igv` decimal(14,2) NOT NULL DEFAULT 0.00,
  `created_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_resumen_diarios` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tipo_documento` varchar(2) NOT NULL DEFAULT 'RC' COMMENT 'RC = Resumen diario',
  `fecha_generacion` date NOT NULL,
  `fecha_referencia` date NOT NULL,
  `fecha_envio` date NOT NULL,
  `serie` varchar(20) NOT NULL,
  `correlativo` int(10) unsigned NOT NULL DEFAULT 1,
  `nombre_xml` varchar(120) DEFAULT NULL,
  `xml_path` varchar(600) DEFAULT NULL,
  `xml_firmado_path` varchar(600) DEFAULT NULL,
  `zip_path` varchar(600) DEFAULT NULL,
  `cdr_zip_path` varchar(600) DEFAULT NULL,
  `cdr_xml_path` varchar(600) DEFAULT NULL,
  `ticket` varchar(80) DEFAULT NULL,
  `estado` varchar(20) NOT NULL DEFAULT 'GENERADO' COMMENT 'GENERADO, FIRMADO, ZIPIADO, ENVIADO, PENDIENTE, ACEPTADO, RECHAZADO, ERROR',
  `codigo_sunat` varchar(20) DEFAULT NULL,
  `mensaje_sunat` varchar(600) DEFAULT NULL,
  `respuesta_soap` longtext DEFAULT NULL,
  `total_documentos` int(10) unsigned NOT NULL DEFAULT 0,
  `total_importe` decimal(14,2) NOT NULL DEFAULT 0.00,
  `created_by` bigint(20) unsigned DEFAULT NULL,
  `updated_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_series` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tipo_comprobante_id` bigint(20) unsigned NOT NULL,
  `serie` varchar(10) NOT NULL,
  `es_electronico` tinyint(1) NOT NULL DEFAULT 1 COMMENT '0=No electronico, 1=Electronico',
  `en_modulo` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Facturacion, 2=Guias, 3=Cotizaciones',
  `correlativo_actual` int(10) unsigned NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_tipo_comprobante` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(5) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `afecta_igv` tinyint(1) NOT NULL DEFAULT 1,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_transportistas` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tipo_documento` varchar(2) NOT NULL DEFAULT '6',
  `numero_documento` varchar(20) NOT NULL,
  `razon_social` varchar(200) NOT NULL,
  `registro_mtc` varchar(50) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `giro_negocio` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(50) NOT NULL,
  `nombre` varchar(120) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `historial` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `usuario_id` bigint(20) unsigned DEFAULT NULL,
  `modulo` varchar(80) NOT NULL,
  `accion` varchar(80) NOT NULL,
  `registro_id` bigint(20) unsigned DEFAULT NULL,
  `resumen` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`resumen`)),
  `ip` varchar(60) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `inventario` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tipo_operacion_id` tinyint(3) unsigned NOT NULL COMMENT 'Referencia a tipo_operacion.id (1=Venta, 2=Compra)',
  `origen_tipo` varchar(30) NOT NULL DEFAULT 'MANUAL' COMMENT 'MANUAL, COMPROBANTE, COTIZACION, DOCUMENTO_INTERNO',
  `origen_id` bigint(20) unsigned DEFAULT NULL COMMENT 'Id del documento origen',
  `fecha_movimiento` date NOT NULL,
  `glosa` varchar(255) DEFAULT NULL,
  `sentido` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Entrada, 2=Salida',
  `ambito` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Fiscal, 2=Interno',
  `estado` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Activo, 0=Anulado',
  `created_by` bigint(20) unsigned DEFAULT NULL,
  `updated_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `inventario_detalle` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `inventario_id` bigint(20) unsigned NOT NULL,
  `catalogo_item_id` bigint(20) unsigned DEFAULT NULL,
  `unidad_medida_id` bigint(20) unsigned DEFAULT NULL,
  `item` int(10) unsigned NOT NULL DEFAULT 1,
  `descripcion` varchar(255) NOT NULL,
  `cantidad` decimal(14,4) NOT NULL DEFAULT 0.0000,
  `unidad_medida` varchar(10) NOT NULL DEFAULT 'NIU',
  `valor_unitario` decimal(14,4) NOT NULL DEFAULT 0.0000,
  `valor_total` decimal(14,2) NOT NULL DEFAULT 0.00,
  `estado` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Activo, 0=Anulado',
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `inventario_saldos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `catalogo_item_id` bigint(20) unsigned NOT NULL,
  `stock_cantidad` decimal(14,4) NOT NULL DEFAULT 0.0000,
  `stock_valorizado` decimal(14,2) NOT NULL DEFAULT 0.00,
  `costo_promedio` decimal(14,4) NOT NULL DEFAULT 0.0000,
  `updated_at` datetime DEFAULT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `modulos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(80) NOT NULL,
  `nombre` varchar(120) NOT NULL,
  `categoria` enum('CORE','VERTICAL','LEGAL') NOT NULL DEFAULT 'CORE',
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `permisos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `rol_id` bigint(20) unsigned NOT NULL,
  `modulo_id` bigint(20) unsigned NOT NULL,
  `accion_id` bigint(20) unsigned NOT NULL,
  `permitido` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `roles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `nombre` varchar(120) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `sucursal_pos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `sucursal_id` bigint(20) unsigned NOT NULL,
  `codigo` varchar(20) NOT NULL,
  `nombre` varchar(180) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  `impresion_formato` enum('A4','A5','TICKET') NOT NULL DEFAULT 'TICKET',
  `es_principal` tinyint(1) NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `terceros` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint(20) unsigned NOT NULL,
  `tipo` enum('CLIENTE','PROVEEDOR','AMBOS') NOT NULL DEFAULT 'CLIENTE',
  `tipo_documento_id` bigint(20) unsigned DEFAULT NULL,
  `numero_documento` varchar(20) DEFAULT NULL,
  `razon_social` varchar(200) NOT NULL,
  `nombre_comercial` varchar(200) DEFAULT NULL,
  `direccion` varchar(255) DEFAULT NULL,
  `email` varchar(150) DEFAULT NULL,
  `telefono` varchar(50) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `tipo_empresa` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(30) NOT NULL,
  `nombre` varchar(120) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `tipo_operacion` (
  `id` tinyint(3) unsigned NOT NULL,
  `codigo` varchar(20) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `unidades_medida` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(10) NOT NULL,
  `descripcion` varchar(120) NOT NULL,
  `simbolo` varchar(20) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `usuario_pos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `usuario_id` bigint(20) unsigned NOT NULL,
  `pos_id` bigint(20) unsigned NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `usuario_sucursales` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `usuario_id` bigint(20) unsigned NOT NULL,
  `sucursal_id` bigint(20) unsigned NOT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `usuarios` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(150) NOT NULL,
  `usuario` varchar(80) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password_hash` varchar(255) NOT NULL,
  `es_super_admin` tinyint(1) NOT NULL DEFAULT 0,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `ultimo_login` datetime DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobante_cuotas` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `comprobante_id` bigint unsigned NOT NULL,
  `numero_cuota` int unsigned NOT NULL,
  `fecha_vencimiento` date NOT NULL,
  `monto` decimal(14,2) NOT NULL DEFAULT 0.00,
  `estado` varchar(20) NOT NULL DEFAULT 'PENDIENTE' COMMENT 'PENDIENTE, PAGADA o ANULADA',
  `observacion` varchar(255) DEFAULT NULL,
  `created_by` bigint unsigned DEFAULT NULL,
  `updated_by` bigint unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `facturacion_comprobante_pagos` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `comprobante_id` bigint unsigned NOT NULL,
  `medio_pago_id` bigint unsigned NOT NULL,
  `monto` decimal(14,2) NOT NULL DEFAULT 0.00,
  `referencia` varchar(150) DEFAULT NULL,
  `fecha_pago` date DEFAULT NULL,
  `observacion` varchar(255) DEFAULT NULL,
  `created_by` bigint unsigned DEFAULT NULL,
  `updated_by` bigint unsigned DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- =============================================================
-- 2. INDICES Y CLAVES UNICAS
-- =============================================================

ALTER TABLE `acciones` ADD UNIQUE KEY `uq_acciones_codigo` (`codigo`);
ALTER TABLE `auth_refresh_tokens` ADD UNIQUE KEY `uq_auth_refresh_session` (`session_id`);
ALTER TABLE `auth_refresh_tokens` ADD UNIQUE KEY `uq_auth_refresh_token` (`token_hash`);
ALTER TABLE `auth_refresh_tokens` ADD KEY `idx_auth_refresh_user` (`user_id`);
ALTER TABLE `auth_refresh_tokens` ADD KEY `idx_auth_refresh_empresa` (`empresa_id`);
ALTER TABLE `auth_refresh_tokens` ADD KEY `idx_auth_refresh_expires` (`expires_at`);
ALTER TABLE `catalogo_afectaciones_igv` ADD UNIQUE KEY `uq_catalogo_afectacion_codigo` (`codigo`);
ALTER TABLE `catalogo_detracciones` ADD UNIQUE KEY `uq_catalogo_detracciones_codigo` (`codigo`);
ALTER TABLE `catalogo_detracciones` ADD KEY `idx_catalogo_detracciones_descripcion` (`descripcion`);
ALTER TABLE `catalogo_formas_pago` ADD UNIQUE KEY `uq_catalogo_formas_codigo` (`codigo`);
ALTER TABLE `catalogo_items` ADD KEY `idx_catalogo_empresa` (`empresa_id`);
ALTER TABLE `catalogo_items` ADD KEY `idx_catalogo_descripcion` (`descripcion`);
ALTER TABLE `catalogo_items` ADD KEY `fk_catalogo_unidad_medida` (`unidad_medida_id`);
ALTER TABLE `catalogo_items` ADD KEY `fk_catalogo_tipo_item` (`tipo_id`);
ALTER TABLE `catalogo_items` ADD KEY `fk_catalogo_afectacion_igv` (`afectacion_igv_id`);
ALTER TABLE `catalogo_items` ADD KEY `idx_catalogo_detraccion` (`catalogo_detraccion_id`);
ALTER TABLE `catalogo_medios_pago` ADD UNIQUE KEY `uq_catalogo_medios_codigo` (`codigo`);
ALTER TABLE `catalogo_tipo_documentos` ADD UNIQUE KEY `uq_catalogo_tipo_documento_codigo` (`codigo_sunat`);
ALTER TABLE `catalogo_tipo_items` ADD UNIQUE KEY `uq_catalogo_tipo_codigo` (`codigo`);
ALTER TABLE `catalogo_tipo_movimiento` ADD UNIQUE KEY `uq_catalogo_tipo_movimiento_codigo` (`codigo`);
ALTER TABLE `empresa_certificados_digitales` ADD KEY `idx_cert_empresa` (`empresa_id`);
ALTER TABLE `empresa_certificados_digitales` ADD KEY `idx_cert_activo` (`empresa_id`,`es_activo`,`estado`);
ALTER TABLE `empresa_cuentas_bancarias` ADD UNIQUE KEY `uq_empresa_cuenta_banco` (`empresa_id`,`numero_cuenta`);
ALTER TABLE `empresa_cuentas_bancarias` ADD KEY `idx_empresa_cuenta_empresa` (`empresa_id`);
ALTER TABLE `empresa_cuentas_bancarias` ADD KEY `idx_empresa_cuenta_detracciones` (`empresa_id`,`es_detracciones`);
ALTER TABLE `empresa_modulos` ADD UNIQUE KEY `uq_empresa_modulo` (`empresa_id`,`modulo_id`);
ALTER TABLE `empresa_modulos` ADD KEY `idx_empresa_modulos_modulo` (`modulo_id`);
ALTER TABLE `empresa_sucursales` ADD UNIQUE KEY `uq_empresa_sucursal` (`empresa_id`,`codigo`);
ALTER TABLE `empresa_sucursales` ADD KEY `idx_empresa_sucursal_empresa` (`empresa_id`);
ALTER TABLE `empresa_usuarios` ADD UNIQUE KEY `uq_empresa_usuario` (`empresa_id`,`usuario_id`);
ALTER TABLE `empresa_usuarios` ADD KEY `idx_eu_usuario` (`usuario_id`);
ALTER TABLE `empresa_usuarios` ADD KEY `idx_eu_rol` (`rol_id`);
ALTER TABLE `empresas` ADD UNIQUE KEY `uq_empresas_ruc` (`ruc`);
ALTER TABLE `empresas` ADD KEY `idx_empresas_tipo_empresa` (`tipo_empresa_id`);
ALTER TABLE `empresas` ADD KEY `idx_empresas_giro_negocio` (`giro_negocio_id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD KEY `idx_fact_detalle_comp` (`comprobante_id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD KEY `idx_fact_detalle_catalogo` (`catalogo_item_id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD KEY `fk_fact_detalle_unidad_medida` (`unidad_medida_id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD KEY `fk_fact_detalle_afectacion_igv` (`afectacion_igv_id`);
ALTER TABLE `facturacion_comprobante_detracciones` ADD UNIQUE KEY `uq_fact_det_comprobante` (`comprobante_id`);
ALTER TABLE `facturacion_comprobante_detracciones` ADD KEY `idx_fact_det_catalogo` (`catalogo_detraccion_id`);
ALTER TABLE `facturacion_comprobante_eventos` ADD UNIQUE KEY `uq_fact_comprobante_eventos_codigo` (`codigo`);
ALTER TABLE `facturacion_comprobante_historial` ADD KEY `idx_fact_hist_comprobante` (`comprobante_id`);
ALTER TABLE `facturacion_comprobante_historial` ADD KEY `idx_fact_hist_evento` (`evento_id`);
ALTER TABLE `facturacion_comprobante_historial` ADD KEY `idx_fact_hist_fecha` (`created_at`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD UNIQUE KEY `uq_fact_mov_comprobante_cuota` (`comprobante_id`,`tipo_movimiento_id`,`numero_cuota`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD KEY `idx_fact_mov_comprobante` (`comprobante_id`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD KEY `idx_fact_mov_medio` (`medio_pago_id`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD KEY `idx_fact_mov_fecha` (`fecha_movimiento`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD KEY `idx_fact_mov_tipo` (`tipo_movimiento_id`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD KEY `idx_fact_mov_estado` (`estado`);
ALTER TABLE `facturacion_comprobantes` ADD UNIQUE KEY `uq_fact_comprobante` (`empresa_id`,`tipo_comprobante_id`,`serie`,`numero`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comprobante_empresa_fecha` (`empresa_id`,`fecha_emision`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comprobante_tercero` (`tercero_id`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comprobante_tipo` (`tipo_comprobante_id`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `fk_fact_comprobante_serie` (`serie_id`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comprobante_tipo_operacion` (`tipo_operacion_id`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comprobante_sucursal` (`sucursal_id`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comprobante_pos` (`pos_id`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comp_ref` (`comprobante_referencia_id`);
ALTER TABLE `facturacion_comprobantes` ADD KEY `idx_fact_comp_nota_motivo` (`nota_motivo_id`);
ALTER TABLE `facturacion_conductores` ADD UNIQUE KEY `uq_fact_conductor` (`empresa_id`,`numero_documento`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD KEY `idx_cot_det_cotizacion` (`cotizacion_id`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD KEY `idx_cot_det_item` (`catalogo_item_id`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD KEY `idx_cot_det_unidad` (`unidad_medida_id`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD KEY `fk_cot_det_afectacion` (`afectacion_igv_id`);
ALTER TABLE `facturacion_cotizaciones` ADD UNIQUE KEY `uq_cotizacion_empresa_serie_numero` (`empresa_id`,`serie`,`numero`);
ALTER TABLE `facturacion_cotizaciones` ADD KEY `idx_cotizacion_empresa_fecha` (`empresa_id`,`fecha_emision`);
ALTER TABLE `facturacion_cotizaciones` ADD KEY `idx_cotizacion_tercero` (`tercero_id`);
ALTER TABLE `facturacion_cotizaciones` ADD KEY `idx_cotizacion_tipo_operacion` (`tipo_operacion_id`);
ALTER TABLE `facturacion_direcciones` ADD KEY `idx_fact_dir_empresa` (`empresa_id`);
ALTER TABLE `facturacion_direcciones` ADD KEY `idx_fact_dir_tercero` (`tercero_id`);
ALTER TABLE `facturacion_guia_catalogos` ADD UNIQUE KEY `uq_fact_guia_cat` (`categoria`,`codigo`);
ALTER TABLE `facturacion_guia_catalogos` ADD KEY `idx_fact_guia_cat_categoria` (`categoria`);
ALTER TABLE `facturacion_integracion_endpoints` ADD UNIQUE KEY `uq_facturacion_integracion_codigo` (`codigo`);
ALTER TABLE `facturacion_integracion_endpoints` ADD KEY `idx_facturacion_integracion_tipo` (`tipo`);
ALTER TABLE `facturacion_integracion_endpoints` ADD KEY `idx_facturacion_integracion_proveedor` (`proveedor`);
ALTER TABLE `facturacion_integracion_endpoints` ADD KEY `idx_facturacion_integracion_ambiente` (`ambiente`);
ALTER TABLE `facturacion_motivos_nota` ADD UNIQUE KEY `uq_fact_motivos_nota` (`tipo`,`codigo`);
ALTER TABLE `facturacion_motivos_nota` ADD KEY `idx_fact_motivos_nota_tipo` (`tipo`);
ALTER TABLE `facturacion_motivos_nota` ADD KEY `idx_fact_motivos_nota_estado` (`estado`);
ALTER TABLE `facturacion_resumen_diario_detalles` ADD KEY `idx_resumen_detalle_resumen` (`resumen_id`);
ALTER TABLE `facturacion_resumen_diario_detalles` ADD KEY `idx_resumen_detalle_comprobante` (`comprobante_id`);
ALTER TABLE `facturacion_resumen_diarios` ADD UNIQUE KEY `uq_resumen_empresa_serie_correlativo` (`empresa_id`,`serie`,`correlativo`);
ALTER TABLE `facturacion_resumen_diarios` ADD KEY `idx_resumen_empresa_fecha` (`empresa_id`,`fecha_referencia`);
ALTER TABLE `facturacion_resumen_diarios` ADD KEY `idx_resumen_empresa_estado` (`empresa_id`,`estado`);
ALTER TABLE `facturacion_series` ADD UNIQUE KEY `uq_fact_series` (`empresa_id`,`tipo_comprobante_id`,`serie`);
ALTER TABLE `facturacion_series` ADD KEY `idx_fact_series_empresa_tipo` (`empresa_id`,`tipo_comprobante_id`);
ALTER TABLE `facturacion_series` ADD KEY `fk_fact_series_tipo` (`tipo_comprobante_id`);
ALTER TABLE `facturacion_tipo_comprobante` ADD UNIQUE KEY `uq_fact_tipo_codigo` (`codigo`);
ALTER TABLE `facturacion_transportistas` ADD UNIQUE KEY `uq_fact_transportista` (`empresa_id`,`numero_documento`);
ALTER TABLE `giro_negocio` ADD UNIQUE KEY `uq_giro_negocio_codigo` (`codigo`);
ALTER TABLE `historial` ADD KEY `idx_historial_empresa_fecha` (`empresa_id`,`created_at`);
ALTER TABLE `historial` ADD KEY `idx_historial_modulo_registro` (`modulo`,`registro_id`);
ALTER TABLE `historial` ADD KEY `fk_historial_usuario` (`usuario_id`);
ALTER TABLE `inventario` ADD KEY `idx_inventario_empresa_fecha` (`empresa_id`,`fecha_movimiento`);
ALTER TABLE `inventario` ADD KEY `idx_inventario_origen` (`origen_tipo`,`origen_id`);
ALTER TABLE `inventario` ADD KEY `idx_inventario_tipo_operacion` (`tipo_operacion_id`);
ALTER TABLE `inventario_detalle` ADD KEY `idx_inv_det_inventario` (`inventario_id`);
ALTER TABLE `inventario_detalle` ADD KEY `idx_inv_det_catalogo` (`catalogo_item_id`);
ALTER TABLE `inventario_detalle` ADD KEY `fk_inv_det_unidad` (`unidad_medida_id`);
ALTER TABLE `inventario_saldos` ADD UNIQUE KEY `uq_inv_saldo_empresa_catalogo` (`empresa_id`,`catalogo_item_id`);
ALTER TABLE `inventario_saldos` ADD KEY `idx_inv_saldo_empresa` (`empresa_id`);
ALTER TABLE `inventario_saldos` ADD KEY `fk_inv_saldo_catalogo` (`catalogo_item_id`);
ALTER TABLE `modulos` ADD UNIQUE KEY `uq_modulos_codigo` (`codigo`);
ALTER TABLE `permisos` ADD UNIQUE KEY `uq_permiso` (`rol_id`,`modulo_id`,`accion_id`);
ALTER TABLE `permisos` ADD KEY `fk_permisos_modulo` (`modulo_id`);
ALTER TABLE `permisos` ADD KEY `fk_permisos_accion` (`accion_id`);
ALTER TABLE `roles` ADD KEY `idx_roles_empresa` (`empresa_id`);
ALTER TABLE `sucursal_pos` ADD UNIQUE KEY `uq_sucursal_pos` (`sucursal_id`,`codigo`);
ALTER TABLE `sucursal_pos` ADD KEY `idx_pos_sucursal` (`sucursal_id`);
ALTER TABLE `terceros` ADD UNIQUE KEY `uq_terceros_empresa_tipo_doc` (`empresa_id`,`tipo_documento_id`,`numero_documento`);
ALTER TABLE `terceros` ADD KEY `idx_terceros_empresa` (`empresa_id`);
ALTER TABLE `terceros` ADD KEY `idx_terceros_nombre` (`razon_social`);
ALTER TABLE `terceros` ADD KEY `idx_terceros_tipo_documento_id` (`tipo_documento_id`);
ALTER TABLE `tipo_empresa` ADD UNIQUE KEY `uq_tipo_empresa_codigo` (`codigo`);
ALTER TABLE `tipo_operacion` ADD UNIQUE KEY `uq_tipo_operacion_codigo` (`codigo`);
ALTER TABLE `unidades_medida` ADD UNIQUE KEY `uq_unidades_codigo` (`codigo`);
ALTER TABLE `unidades_medida` ADD KEY `idx_unidades_descripcion` (`descripcion`);
ALTER TABLE `usuario_pos` ADD UNIQUE KEY `uq_usuario_pos` (`usuario_id`,`pos_id`);
ALTER TABLE `usuario_pos` ADD KEY `idx_usuario_pos_usuario` (`usuario_id`);
ALTER TABLE `usuario_pos` ADD KEY `idx_usuario_pos_pos` (`pos_id`);
ALTER TABLE `usuario_sucursales` ADD UNIQUE KEY `uq_usuario_sucursal` (`usuario_id`,`sucursal_id`);
ALTER TABLE `usuario_sucursales` ADD KEY `idx_usuario_sucursal_usuario` (`usuario_id`);
ALTER TABLE `usuario_sucursales` ADD KEY `idx_usuario_sucursal_sucursal` (`sucursal_id`);
ALTER TABLE `usuarios` ADD UNIQUE KEY `uq_usuarios_usuario` (`usuario`);
ALTER TABLE `usuarios` ADD UNIQUE KEY `uq_usuarios_email` (`email`);
ALTER TABLE `facturacion_comprobante_cuotas` ADD UNIQUE KEY `uq_fact_cuota_comprobante` (`comprobante_id`,`numero_cuota`);
ALTER TABLE `facturacion_comprobante_cuotas` ADD KEY `idx_fact_cuota_comprobante` (`comprobante_id`);
ALTER TABLE `facturacion_comprobante_pagos` ADD KEY `idx_fact_pago_comprobante` (`comprobante_id`);
ALTER TABLE `facturacion_comprobante_pagos` ADD KEY `idx_fact_pago_medio` (`medio_pago_id`);

-- =============================================================
-- 3. CLAVES FORANEAS
-- =============================================================

ALTER TABLE `auth_refresh_tokens` ADD CONSTRAINT `fk_auth_refresh_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`) ON DELETE SET NULL;
ALTER TABLE `auth_refresh_tokens` ADD CONSTRAINT `fk_auth_refresh_user` FOREIGN KEY (`user_id`) REFERENCES `usuarios` (`id`) ON DELETE CASCADE;
ALTER TABLE `catalogo_items` ADD CONSTRAINT `fk_catalogo_afectacion_igv` FOREIGN KEY (`afectacion_igv_id`) REFERENCES `catalogo_afectaciones_igv` (`id`);
ALTER TABLE `catalogo_items` ADD CONSTRAINT `fk_catalogo_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `catalogo_items` ADD CONSTRAINT `fk_catalogo_item_detraccion` FOREIGN KEY (`catalogo_detraccion_id`) REFERENCES `catalogo_detracciones` (`id`);
ALTER TABLE `catalogo_items` ADD CONSTRAINT `fk_catalogo_tipo_item` FOREIGN KEY (`tipo_id`) REFERENCES `catalogo_tipo_items` (`id`);
ALTER TABLE `catalogo_items` ADD CONSTRAINT `fk_catalogo_unidad_medida` FOREIGN KEY (`unidad_medida_id`) REFERENCES `unidades_medida` (`id`);
ALTER TABLE `empresa_certificados_digitales` ADD CONSTRAINT `fk_cert_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `empresa_cuentas_bancarias` ADD CONSTRAINT `fk_empresa_cuenta_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `empresa_modulos` ADD CONSTRAINT `fk_empresa_modulos_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `empresa_modulos` ADD CONSTRAINT `fk_empresa_modulos_modulo` FOREIGN KEY (`modulo_id`) REFERENCES `modulos` (`id`);
ALTER TABLE `empresa_sucursales` ADD CONSTRAINT `fk_empresa_sucursal_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `empresa_usuarios` ADD CONSTRAINT `fk_eu_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `empresa_usuarios` ADD CONSTRAINT `fk_eu_rol` FOREIGN KEY (`rol_id`) REFERENCES `roles` (`id`);
ALTER TABLE `empresa_usuarios` ADD CONSTRAINT `fk_eu_usuario` FOREIGN KEY (`usuario_id`) REFERENCES `usuarios` (`id`);
ALTER TABLE `empresas` ADD CONSTRAINT `fk_empresas_giro_negocio` FOREIGN KEY (`giro_negocio_id`) REFERENCES `giro_negocio` (`id`);
ALTER TABLE `empresas` ADD CONSTRAINT `fk_empresas_tipo_empresa` FOREIGN KEY (`tipo_empresa_id`) REFERENCES `tipo_empresa` (`id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD CONSTRAINT `fk_fact_detalle_afectacion_igv` FOREIGN KEY (`afectacion_igv_id`) REFERENCES `catalogo_afectaciones_igv` (`id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD CONSTRAINT `fk_fact_detalle_catalogo` FOREIGN KEY (`catalogo_item_id`) REFERENCES `catalogo_items` (`id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD CONSTRAINT `fk_fact_detalle_comp` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_comprobante_detalles` ADD CONSTRAINT `fk_fact_detalle_unidad_medida` FOREIGN KEY (`unidad_medida_id`) REFERENCES `unidades_medida` (`id`);
ALTER TABLE `facturacion_comprobante_detracciones` ADD CONSTRAINT `fk_fact_det_catalogo` FOREIGN KEY (`catalogo_detraccion_id`) REFERENCES `catalogo_detracciones` (`id`);
ALTER TABLE `facturacion_comprobante_detracciones` ADD CONSTRAINT `fk_fact_det_comprobante` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_comprobante_historial` ADD CONSTRAINT `fk_fact_hist_comprobante` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_comprobante_historial` ADD CONSTRAINT `fk_fact_hist_evento` FOREIGN KEY (`evento_id`) REFERENCES `facturacion_comprobante_eventos` (`id`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD CONSTRAINT `fk_fact_mov_comprobante` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD CONSTRAINT `fk_fact_mov_medio` FOREIGN KEY (`medio_pago_id`) REFERENCES `catalogo_medios_pago` (`id`);
ALTER TABLE `facturacion_comprobante_movimientos` ADD CONSTRAINT `fk_fact_mov_tipo` FOREIGN KEY (`tipo_movimiento_id`) REFERENCES `catalogo_tipo_movimiento` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comp_nota_motivo` FOREIGN KEY (`nota_motivo_id`) REFERENCES `facturacion_motivos_nota` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comp_ref` FOREIGN KEY (`comprobante_referencia_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comprobante_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comprobante_pos` FOREIGN KEY (`pos_id`) REFERENCES `sucursal_pos` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comprobante_serie` FOREIGN KEY (`serie_id`) REFERENCES `facturacion_series` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comprobante_sucursal` FOREIGN KEY (`sucursal_id`) REFERENCES `empresa_sucursales` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comprobante_tercero` FOREIGN KEY (`tercero_id`) REFERENCES `terceros` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comprobante_tipo` FOREIGN KEY (`tipo_comprobante_id`) REFERENCES `facturacion_tipo_comprobante` (`id`);
ALTER TABLE `facturacion_comprobantes` ADD CONSTRAINT `fk_fact_comprobante_tipo_operacion` FOREIGN KEY (`tipo_operacion_id`) REFERENCES `tipo_operacion` (`id`);
ALTER TABLE `facturacion_conductores` ADD CONSTRAINT `fk_fact_conductor_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD CONSTRAINT `fk_cot_det_afectacion` FOREIGN KEY (`afectacion_igv_id`) REFERENCES `catalogo_afectaciones_igv` (`id`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD CONSTRAINT `fk_cot_det_cotizacion` FOREIGN KEY (`cotizacion_id`) REFERENCES `facturacion_cotizaciones` (`id`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD CONSTRAINT `fk_cot_det_item` FOREIGN KEY (`catalogo_item_id`) REFERENCES `catalogo_items` (`id`);
ALTER TABLE `facturacion_cotizacion_detalles` ADD CONSTRAINT `fk_cot_det_unidad` FOREIGN KEY (`unidad_medida_id`) REFERENCES `unidades_medida` (`id`);
ALTER TABLE `facturacion_direcciones` ADD CONSTRAINT `fk_fact_dir_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `facturacion_direcciones` ADD CONSTRAINT `fk_fact_dir_tercero` FOREIGN KEY (`tercero_id`) REFERENCES `terceros` (`id`);
ALTER TABLE `facturacion_guia_transporte` ADD CONSTRAINT `fk_guia_transporte_comp` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_resumen_diario_detalles` ADD CONSTRAINT `fk_resumen_detalle_comprobante` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_resumen_diario_detalles` ADD CONSTRAINT `fk_resumen_detalle_resumen` FOREIGN KEY (`resumen_id`) REFERENCES `facturacion_resumen_diarios` (`id`);
ALTER TABLE `facturacion_resumen_diarios` ADD CONSTRAINT `fk_resumen_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `facturacion_series` ADD CONSTRAINT `fk_fact_series_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `facturacion_series` ADD CONSTRAINT `fk_fact_series_tipo` FOREIGN KEY (`tipo_comprobante_id`) REFERENCES `facturacion_tipo_comprobante` (`id`);
ALTER TABLE `facturacion_transportistas` ADD CONSTRAINT `fk_fact_transportista_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `historial` ADD CONSTRAINT `fk_historial_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `historial` ADD CONSTRAINT `fk_historial_usuario` FOREIGN KEY (`usuario_id`) REFERENCES `usuarios` (`id`);
ALTER TABLE `inventario` ADD CONSTRAINT `fk_inventario_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `inventario` ADD CONSTRAINT `fk_inventario_tipo_operacion` FOREIGN KEY (`tipo_operacion_id`) REFERENCES `tipo_operacion` (`id`);
ALTER TABLE `inventario_detalle` ADD CONSTRAINT `fk_inv_det_catalogo` FOREIGN KEY (`catalogo_item_id`) REFERENCES `catalogo_items` (`id`);
ALTER TABLE `inventario_detalle` ADD CONSTRAINT `fk_inv_det_inventario` FOREIGN KEY (`inventario_id`) REFERENCES `inventario` (`id`);
ALTER TABLE `inventario_detalle` ADD CONSTRAINT `fk_inv_det_unidad` FOREIGN KEY (`unidad_medida_id`) REFERENCES `unidades_medida` (`id`);
ALTER TABLE `inventario_saldos` ADD CONSTRAINT `fk_inv_saldo_catalogo` FOREIGN KEY (`catalogo_item_id`) REFERENCES `catalogo_items` (`id`);
ALTER TABLE `inventario_saldos` ADD CONSTRAINT `fk_inv_saldo_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `permisos` ADD CONSTRAINT `fk_permisos_accion` FOREIGN KEY (`accion_id`) REFERENCES `acciones` (`id`);
ALTER TABLE `permisos` ADD CONSTRAINT `fk_permisos_modulo` FOREIGN KEY (`modulo_id`) REFERENCES `modulos` (`id`);
ALTER TABLE `permisos` ADD CONSTRAINT `fk_permisos_rol` FOREIGN KEY (`rol_id`) REFERENCES `roles` (`id`);
ALTER TABLE `roles` ADD CONSTRAINT `fk_roles_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `sucursal_pos` ADD CONSTRAINT `fk_pos_sucursal` FOREIGN KEY (`sucursal_id`) REFERENCES `empresa_sucursales` (`id`);
ALTER TABLE `terceros` ADD CONSTRAINT `fk_terceros_empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresas` (`id`);
ALTER TABLE `terceros` ADD CONSTRAINT `fk_terceros_tipo_documento` FOREIGN KEY (`tipo_documento_id`) REFERENCES `catalogo_tipo_documentos` (`id`);
ALTER TABLE `usuario_pos` ADD CONSTRAINT `fk_usuario_pos_pos` FOREIGN KEY (`pos_id`) REFERENCES `sucursal_pos` (`id`);
ALTER TABLE `usuario_pos` ADD CONSTRAINT `fk_usuario_pos_usuario` FOREIGN KEY (`usuario_id`) REFERENCES `usuarios` (`id`);
ALTER TABLE `usuario_sucursales` ADD CONSTRAINT `fk_usuario_sucursal_sucursal` FOREIGN KEY (`sucursal_id`) REFERENCES `empresa_sucursales` (`id`);
ALTER TABLE `usuario_sucursales` ADD CONSTRAINT `fk_usuario_sucursal_usuario` FOREIGN KEY (`usuario_id`) REFERENCES `usuarios` (`id`);
ALTER TABLE `facturacion_comprobante_cuotas` ADD CONSTRAINT `fk_fact_cuota_comprobante` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_comprobante_pagos` ADD CONSTRAINT `fk_fact_pago_comprobante` FOREIGN KEY (`comprobante_id`) REFERENCES `facturacion_comprobantes` (`id`);
ALTER TABLE `facturacion_comprobante_pagos` ADD CONSTRAINT `fk_fact_pago_medio` FOREIGN KEY (`medio_pago_id`) REFERENCES `catalogo_medios_pago` (`id`);

-- =============================================================
-- 4. DATOS MAESTROS
-- =============================================================

INSERT INTO `acciones` (`id`, `codigo`, `nombre`, `estado`, `created_at`) VALUES (1,'ver','Ver',1,'2026-08-17 21:38:43'),(2,'crear','Crear',1,'2026-08-17 21:38:43'),(3,'editar','Editar',1,'2026-08-17 21:38:43'),(4,'eliminar','Eliminar',1,'2026-08-17 21:38:43'),(5,'anular','Anular',1,'2026-08-17 21:38:43');
INSERT INTO `catalogo_afectaciones_igv` (`id`, `codigo`, `descripcion`, `tipo_afectacion`, `codigo_tributo`, `nombre_tributo`, `abreviatura`, `porcentaje`, `afecta_igv`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'10','OP. GRAVADAS','S','1000','IGV','VAT',18.00,1,1,'2026-08-20 11:30:42',NULL,NULL),(2,'20','OP. EXONERADAS','E','9997','EXO','VAT',0.00,0,1,'2026-08-20 11:30:42',NULL,NULL),(3,'30','OP. INAFECTAS','O','9998','INA','FRE',0.00,0,1,'2026-08-20 11:30:42',NULL,NULL);
INSERT INTO `catalogo_detracciones` (`id`, `codigo`, `descripcion`, `porcentaje`, `limite_minimo`, `comentario`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'01','Intermediacion laboral y tercerizacion',12.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(2,'02','Arrendamiento de bienes',10.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(3,'03','Mantenimiento y reparacion de bienes muebles',12.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(4,'04','Movimiento de carga',10.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(5,'05','Otros servicios empresariales',12.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(6,'06','Comision mercantil',10.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(7,'07','Fabricacion de bienes por encargo',10.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(8,'08','Servicio de transporte de personas',10.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(9,'09','Contratos de construccion',4.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(10,'10','Demas servicios gravados con IGV',12.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL),(11,'11','Servicio de beneficio de minerales metalicos gravado con IGV',12.00,700.00,'Servicio sujeto a detraccion segun anexo 3 SUNAT',1,'2026-08-20 15:19:33',NULL,NULL);
INSERT INTO `catalogo_formas_pago` (`id`, `codigo`, `descripcion`, `comentario`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'CONTADO','Contado','Pago al momento de la operacion',1,'2026-08-20 13:09:14',NULL,NULL),(2,'CREDITO','Credito','Pago diferido o en cuotas',1,'2026-08-20 13:09:14',NULL,NULL);
INSERT INTO `catalogo_medios_pago` (`id`, `codigo`, `descripcion`, `comentario`, `es_credito`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'EFECTIVO','Efectivo','Pago en efectivo',0,1,'2026-08-20 13:09:14',NULL,NULL),(2,'CREDITO','Credito','Pago diferido o en cuotas',1,1,'2026-08-20 17:53:47',NULL,NULL),(3,'YAPE','Yape','Pago por Yape',0,1,'2026-08-20 13:09:14',NULL,NULL),(4,'PLIN','Plin','Pago por Plin',0,1,'2026-08-20 13:09:14',NULL,NULL),(5,'TRANSFERENCIA','Transferencia','Transferencia bancaria',0,1,'2026-08-20 13:09:14',NULL,NULL),(6,'CHEQUE','Cheque','Pago con cheque',0,1,'2026-08-20 13:09:14',NULL,NULL),(7,'TARJETA','Tarjeta','Pago con tarjeta de debito o credito',0,1,'2026-08-20 13:09:14',NULL,NULL),(8,'DEPOSITO','Deposito','Deposito bancario',0,1,'2026-08-20 13:09:14',NULL,NULL),(9,'OTRO','Otro','Otro medio de pago',0,1,'2026-08-20 13:09:14',NULL,NULL);
INSERT INTO `catalogo_tipo_documentos` (`id`, `codigo_sunat`, `descripcion`, `comentario`, `orden`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'6','RUC','Registro Unico de Contribuyentes',1,1,'2026-08-22 07:18:28',NULL,NULL),(2,'1','DNI','Documento Nacional de Identidad',2,1,'2026-08-22 07:18:28',NULL,NULL),(3,'4','CARNET EXTRANJERIA','Carnet de Extranjeria',3,1,'2026-08-22 07:18:28',NULL,NULL),(4,'7','PASAPORTE','Pasaporte',4,1,'2026-08-22 07:18:28',NULL,NULL),(5,'0','SIN DOCUMENTO','Consumidor final u otros',5,1,'2026-08-22 07:18:28',NULL,NULL),(6,'A','CEDULA DIPLOMATICA','Cedula Diplomatica de Identidad',6,1,'2026-08-22 07:18:28',NULL,NULL);
INSERT INTO `catalogo_tipo_items` (`id`, `codigo`, `descripcion`, `comentario`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'PRODUCTO','Producto','1 = productos',1,'2026-08-20 11:30:42',NULL,NULL),(2,'SERVICIO','Servicio','2 = servicios',1,'2026-08-20 11:30:42',NULL,NULL);
INSERT INTO `catalogo_tipo_movimiento` (`id`, `codigo`, `descripcion`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'PAGO','Pago',1,'2026-08-20 20:18:50',NULL,NULL),(2,'CUOTA','Cuota',1,'2026-08-20 20:18:50',NULL,NULL);
INSERT INTO `facturacion_comprobante_eventos` (`id`, `codigo`, `descripcion`, `comentario`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'GENERADO','Generado','Se generó el XML del comprobante',1,'2026-08-21 20:32:50',NULL,NULL),(2,'FIRMADO','Firmado','Se firmó el XML del comprobante',1,'2026-08-21 20:32:50',NULL,NULL),(3,'ZIPIADO','Zipiado','Se comprimió el XML firmado en ZIP',1,'2026-08-21 20:32:50',NULL,NULL),(4,'ENVIADO','Enviado','Se envió el ZIP a SUNAT u otro endpoint',1,'2026-08-21 20:32:50',NULL,NULL),(5,'ACEPTADO','Aceptado','SUNAT aceptó el comprobante',1,'2026-08-21 20:32:50',NULL,NULL),(6,'RECHAZADO','Rechazado','SUNAT rechazó el comprobante',1,'2026-08-21 20:32:50',NULL,NULL),(7,'ERROR','Error','Ocurrió un error durante el proceso',1,'2026-08-21 20:32:50',NULL,NULL),(8,'ANULADO','Anulado','Comprobante anulado por sistema o por baja electrónica',1,'2026-08-21 23:08:33',NULL,NULL);
INSERT INTO `facturacion_guia_catalogos` (`id`, `categoria`, `codigo`, `descripcion`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'MODALIDAD_TRANSPORTE','01','Publico',1,'2026-08-22 20:16:44',NULL,NULL),(2,'MODALIDAD_TRANSPORTE','02','Privado',1,'2026-08-22 20:16:44',NULL,NULL),(3,'MOTIVO_TRASLADO','01','Venta',1,'2026-08-22 20:16:44',NULL,NULL),(4,'MOTIVO_TRASLADO','02','Compra',1,'2026-08-22 20:16:44',NULL,NULL),(5,'MOTIVO_TRASLADO','03','Venta con entrega a terceros',1,'2026-08-22 20:16:44',NULL,NULL),(6,'MOTIVO_TRASLADO','04','Traslado entre establecimientos de la misma empresa',1,'2026-08-22 20:16:44',NULL,NULL),(7,'MOTIVO_TRASLADO','05','Consignacion',1,'2026-08-22 20:16:44',NULL,NULL),(8,'MOTIVO_TRASLADO','06','Devolucion',1,'2026-08-22 20:16:44',NULL,NULL),(9,'MOTIVO_TRASLADO','07','Traslado entre establecimientos de la misma empresa (bienes transformados)',1,'2026-08-22 20:16:44',NULL,NULL),(10,'MOTIVO_TRASLADO','08','Importacion',1,'2026-08-22 20:16:44',NULL,NULL),(11,'MOTIVO_TRASLADO','09','Exportacion',1,'2026-08-22 20:16:44',NULL,NULL),(12,'MOTIVO_TRASLADO','13','Otros',1,'2026-08-22 20:16:44',NULL,NULL);
INSERT INTO `facturacion_integracion_endpoints` (`id`, `codigo`, `descripcion`, `tipo`, `proveedor`, `ambiente`, `metodo`, `url`, `headers_json`, `estado`, `es_defecto`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'SUNAT_FACTURA','Envio de comprobantes a SUNAT','EMISION','SUNAT','PRODUCCION','POST','https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService','[]',1,1,'2026-08-21 12:47:08','2026-08-21 13:45:39',NULL),(2,'SUNAT_CONSULTA','Consulta de CDR / estado','CONSULTA','SUNAT','PRODUCCION','POST','https://e-factura.sunat.gob.pe/ol-it-wsconscpegem/billConsultService?wsdl',NULL,1,0,'2026-08-21 12:47:08','2026-08-22 09:46:37',NULL),(3,'SUNAT_GUIA','Envio de guia de remision','GUIA','SUNAT','PRODUCCION','POST',NULL,NULL,1,0,'2026-08-21 12:47:08',NULL,NULL),(4,'SUNAT_SUMARIO_BOLETA','Resumen diario de boletas','RESUMEN_BOLETAS','SUNAT','PRODUCCION','POST','https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService',NULL,1,0,'2026-08-21 12:47:08',NULL,NULL),(5,'SUNAT_BAJA','Comunicacion de baja','RESUMEN_BAJA','SUNAT','PRODUCCION','POST','https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService',NULL,1,0,'2026-08-21 12:47:08',NULL,NULL),(6,'OSE_FACTURA','Envio de comprobantes a OSE','EMISION','OSE','PRODUCCION','POST',NULL,'[]',0,0,'2026-08-21 12:47:08','2026-08-21 13:54:18',NULL),(7,'CUSTOM_FACTURA','Endpoint personalizado de emision','EMISION','CUSTOM','PRODUCCION','POST',NULL,'[]',0,0,'2026-08-21 12:47:08','2026-08-21 13:54:13',NULL);
INSERT INTO `facturacion_motivos_nota` (`id`, `tipo`, `codigo`, `descripcion`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'C','01','Anulacion de la operacion',1,'2026-08-22 17:14:25',NULL,NULL),(2,'C','03','Descuento global',1,'2026-08-22 17:14:25',NULL,NULL),(3,'C','04','Descuento por item',1,'2026-08-22 17:14:25',NULL,NULL),(4,'C','05','Devolucion total',1,'2026-08-22 17:14:25',NULL,NULL),(5,'C','06','Devolucion por item',1,'2026-08-22 17:14:25',NULL,NULL),(6,'C','07','Bonificacion',1,'2026-08-22 17:14:25',NULL,NULL),(7,'C','08','Ajustes por diferencia de precio',1,'2026-08-22 17:14:25',NULL,NULL),(8,'C','09','Otros conceptos',1,'2026-08-22 17:14:25',NULL,NULL),(9,'D','01','Intereses por mora',1,'2026-08-22 17:14:25',NULL,NULL),(10,'D','02','Aumento en el valor',1,'2026-08-22 17:14:25',NULL,NULL),(11,'D','03','Penalidades',1,'2026-08-22 17:14:25',NULL,NULL),(12,'D','04','Ajustes por diferencia de precio',1,'2026-08-22 17:14:25',NULL,NULL),(13,'D','05','Otros conceptos',1,'2026-08-22 17:14:25',NULL,NULL);
INSERT INTO `facturacion_tipo_comprobante` (`id`, `codigo`, `descripcion`, `afecta_igv`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'01','Factura',1,1,'2026-08-17 21:38:43',NULL,NULL),(2,'03','Boleta',1,1,'2026-08-17 21:38:43',NULL,NULL),(3,'07','Nota de credito',1,1,'2026-08-17 21:38:43',NULL,NULL),(4,'08','Nota de debito',1,1,'2026-08-17 21:38:43',NULL,NULL),(5,'09','Guia de remision',0,1,'2026-08-17 21:38:43',NULL,NULL),(6,'00','Documento interno',0,1,'2026-08-27 09:35:47',NULL,NULL);
INSERT INTO `giro_negocio` (`id`, `codigo`, `nombre`, `descripcion`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'GENERAL','General','Negocio generico',1,'2026-08-17 21:39:48',NULL,NULL),(2,'FERRETERIA','Ferreteria','Venta de articulos de construccion y ferreteria',1,'2026-08-17 21:39:48',NULL,NULL),(3,'RESTAURANTE','Restaurante','Atencion de mesas, salon y cocina',1,'2026-08-17 21:39:48',NULL,NULL),(4,'BODEGA','Bodega','Tienda de abarrotes y venta rapida',1,'2026-08-17 21:39:48',NULL,NULL),(5,'SPA','Spa','Servicios de bienestar y citas',1,'2026-08-17 21:39:48',NULL,NULL),(6,'SERVICIOS','Servicios','Prestacion de servicios profesionales',1,'2026-08-17 21:39:48',NULL,NULL),(7,'POLLERIA','Polleria','Venta de pollos, combos y delivery',1,'2026-08-17 21:39:48',NULL,NULL);
INSERT INTO `modulos` (`id`, `codigo`, `nombre`, `categoria`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'usuarios','Usuarios','CORE',1,'2026-08-17 21:38:43',NULL,NULL),(2,'empresas','Empresas','CORE',1,'2026-08-17 21:38:43',NULL,NULL),(3,'facturacion','Facturaci??n','CORE',1,'2026-08-17 21:38:43',NULL,NULL),(4,'auditoria','Auditor??a','CORE',1,'2026-08-17 21:38:43',NULL,NULL),(5,'catalogos_sunat','Catalogos SUNAT','LEGAL',1,'2026-08-17 21:40:17',NULL,NULL),(6,'terceros','Terceros','CORE',1,'2026-08-17 21:40:17',NULL,NULL),(7,'productos','Productos','CORE',1,'2026-08-17 21:40:17',NULL,NULL),(8,'inventario','Inventario','CORE',1,'2026-08-17 21:40:17',NULL,NULL),(9,'caja','Caja','CORE',1,'2026-08-17 21:40:17',NULL,NULL),(10,'compras','Compras','CORE',1,'2026-08-17 21:40:17',NULL,NULL),(11,'ventas','Ventas','CORE',1,'2026-08-17 21:40:17',NULL,NULL),(12,'polleria','Polleria','VERTICAL',1,'2026-08-17 21:40:17',NULL,NULL),(13,'restaurante','Restaurante','VERTICAL',1,'2026-08-17 21:40:17',NULL,NULL),(14,'bodega','Bodega','VERTICAL',1,'2026-08-17 21:40:17',NULL,NULL),(15,'spa','Spa','VERTICAL',1,'2026-08-17 21:40:17',NULL,NULL),(16,'servicios','Servicios','VERTICAL',1,'2026-08-17 21:40:17',NULL,NULL),(17,'ferreteria','Ferreteria','VERTICAL',1,'2026-08-17 21:40:17',NULL,NULL),(18,'cotizaciones','Cotizaciones','CORE',1,'2026-08-27 11:30:02',NULL,NULL),(19,'guias','Guias de remision','CORE',1,'2026-08-28 00:00:00',NULL,NULL),(20,'reportes','Reportes','CORE',1,'2026-08-28 00:00:00',NULL,NULL);
INSERT INTO `tipo_empresa` (`id`, `codigo`, `nombre`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'GENERAL','General',1,'2026-08-17 21:38:43',NULL,NULL);
INSERT INTO `tipo_operacion` (`id`, `codigo`, `descripcion`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'VENTA','Venta',1,'2026-08-18 10:23:56',NULL,NULL),(2,'COMPRA','Compra',1,'2026-08-18 10:23:56',NULL,NULL),(3,'COTIZACION','Cotizacion',1,'2026-08-27 11:30:02',NULL,NULL);
INSERT INTO `unidades_medida` (`id`, `codigo`, `descripcion`, `simbolo`, `estado`, `created_at`, `updated_at`, `deleted_at`) VALUES (1,'NIU','Unidad','UND',1,'2026-08-18 09:04:38',NULL,NULL),(2,'ZZ','Servicio','SER',1,'2026-08-18 09:04:38',NULL,NULL),(3,'HUR','Hora','H',1,'2026-08-18 09:04:38',NULL,NULL),(4,'KGM','Kilogramo','KG',1,'2026-08-18 09:04:38',NULL,NULL),(5,'LTR','Litro','L',1,'2026-08-18 09:04:38',NULL,NULL),(6,'MTR','Metro','M',1,'2026-08-18 09:04:38',NULL,NULL),(7,'C62','Unidad de producto','UND',1,'2026-08-18 09:04:38',NULL,NULL),(8,'GLL','US GALON','GL',1,'2026-08-27 22:28:20',NULL,NULL);

-- =============================================================
-- 5. EMPRESA Y USUARIO INICIALES
-- =============================================================

-- Usuario inicial: admin / Admin123*
INSERT INTO `usuarios`
    (`id`, `nombre`, `usuario`, `email`, `password_hash`, `es_super_admin`, `estado`, `created_at`)
VALUES
    (1, 'Administrador Principal', 'admin', 'admin@abisfact.local', '$2y$10$WwR0V.c0tXXSMUOu.7Vcce7lfsuhN5T.pNuFkC6jX37mAmHQftEVG', 1, 1, NOW());

INSERT INTO `empresas`
    (`id`, `ruc`, `razon_social`, `nombre_comercial`, `logo`, `tipo_empresa_id`, `giro_negocio_id`, `estado`, `created_at`)
VALUES
    (1, '00000000000', 'EMPRESA BASE', 'EMPRESA BASE', NULL, 1, 1, 1, NOW());

INSERT INTO `roles`
    (`id`, `empresa_id`, `nombre`, `descripcion`, `estado`, `created_at`)
VALUES
    (1, 1, 'Administrador', 'Acceso total para la empresa base', 1, NOW());

INSERT INTO `empresa_usuarios`
    (`id`, `empresa_id`, `usuario_id`, `rol_id`, `estado`, `created_at`)
VALUES
    (1, 1, 1, 1, 'ACTIVO', NOW());

INSERT INTO `empresa_sucursales`
    (`id`, `empresa_id`, `codigo`, `nombre`, `direccion`, `telefono`, `logo`, `es_principal`, `estado`, `created_at`)
VALUES
    (1, 1, 'SUC-01', 'Sucursal principal', NULL, NULL, NULL, 1, 1, NOW());

INSERT INTO `sucursal_pos`
    (`id`, `sucursal_id`, `codigo`, `nombre`, `descripcion`, `impresion_formato`, `es_principal`, `estado`, `created_at`)
VALUES
    (1, 1, 'POS-01', 'Caja principal', 'POS principal de la empresa', 'TICKET', 1, 1, NOW());

INSERT INTO `empresa_modulos` (`empresa_id`, `modulo_id`, `habilitado`, `created_at`)
SELECT 1, `id`, 1, NOW()
FROM `modulos`;

INSERT INTO `facturacion_series`
    (`id`, `empresa_id`, `tipo_comprobante_id`, `serie`, `es_electronico`, `en_modulo`, `correlativo_actual`, `estado`, `created_at`)
VALUES
    (1, 1, 1, 'F001', 1, 1, 0, 1, NOW()),
    (2, 1, 2, 'B001', 1, 1, 0, 1, NOW()),
    (3, 1, 3, 'FC01', 1, 1, 0, 1, NOW()),
    (4, 1, 4, 'FD01', 1, 1, 0, 1, NOW()),
    (5, 1, 5, 'T001', 1, 2, 0, 1, NOW());

INSERT INTO `usuario_sucursales`
    (`id`, `usuario_id`, `sucursal_id`, `estado`, `created_at`)
VALUES
    (1, 1, 1, 1, NOW());

INSERT INTO `usuario_pos`
    (`id`, `usuario_id`, `pos_id`, `estado`, `created_at`)
VALUES
    (1, 1, 1, 1, NOW());

SET FOREIGN_KEY_CHECKS = 1;

-- Fin de la instalacion.
