﻿/* ============================================================================
   Migracion COMANO 0003 - Catalogos de convivencia escolar y actas formativas
   Fuente: C:\Users\Alvert\Downloads\script_bd_convivencia_ie0003_mysql.sql
   Integracion: tablas prefijadas conv_* para no alterar personas, estudiantes,
   matriculas ni tablas operativas ya existentes del sistema.
   Fecha: 2026-06-11
   ============================================================================ */
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

DROP VIEW IF EXISTS vw_conv_compromisos_predefinidos;
DROP VIEW IF EXISTS vw_conv_modelos_acta;
DROP VIEW IF EXISTS vw_conv_normas_convivencia;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_accion_reparadora_acta` (
  `accion_reparadora_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `accion_tipo_id` int(10) unsigned DEFAULT NULL,
  `descripcion` text NOT NULL,
  `fecha_plazo` date DEFAULT NULL,
  `cumplida` tinyint(1) NOT NULL DEFAULT 0,
  `fecha_cumplimiento` date DEFAULT NULL,
  `observacion` text DEFAULT NULL,
  PRIMARY KEY (`accion_reparadora_id`),
  KEY `fk_ara_acta` (`acta_id`),
  KEY `fk_ara_tipo` (`accion_tipo_id`),
  CONSTRAINT `conv_fk_ara_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_ara_tipo` FOREIGN KEY (`accion_tipo_id`) REFERENCES `conv_accion_reparadora_tipo` (`accion_tipo_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_accion_reparadora_tipo` (
  `accion_tipo_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(160) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`accion_tipo_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_accion_reparadora_tipo` (`accion_tipo_id`, `nombre`, `descripcion`, `estado`) VALUES (1,'Pedir disculpas de manera respetuosa','Acción restaurativa verbal o escrita orientada a reconocer el daño generado.',1),(2,'Participar en sesión de tutoría','Participación en sesión de acompañamiento tutorial individual o grupal.',1),(3,'Elaborar reflexión escrita','Producción escrita orientada a reconocer la norma y comprometer mejora.',1),(4,'Apoyar actividad de convivencia','Participación en actividad que fortalece la convivencia escolar.',1),(5,'Participar en mediación','Espacio guiado de resolución pacífica de conflicto.',1),(6,'Limpieza o conservación de ambiente','Acción de mejora del espacio afectado.',1),(7,'Reparación o reposición del bien','Reparar, reponer o compensar el daño producido al bien común.',1),(8,'Sesión sobre tecnología responsable','Orientación sobre uso responsable de celular, dispositivos u objetos personales.',1),(9,'Diálogo reflexivo','Espacio de orientación formativa con estudiante y/o familia.',1),(10,'Retención preventiva para entrega al apoderado','Medida preventiva con registro para entrega del objeto al apoderado, según norma institucional.',1),(11,'Nueva reunión con familia','Reunión de seguimiento para reforzar compromisos y apoyo familiar.',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_acta_compromiso` (
  `acta_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `expediente_id` int(10) unsigned NOT NULL,
  `tipo_acta_id` int(10) unsigned NOT NULL,
  `codigo_acta` varchar(50) NOT NULL,
  `fecha_acta` date NOT NULL,
  `hora_acta` time DEFAULT NULL,
  `seccion_id` int(10) unsigned DEFAULT NULL,
  `area_curso` varchar(120) DEFAULT NULL,
  `descripcion_objetiva` text DEFAULT NULL,
  `fecha_hecho` date DEFAULT NULL,
  `periodo_hecho` varchar(120) DEFAULT NULL,
  `reportado_observado_por` varchar(180) DEFAULT NULL,
  `tutor_id` int(10) unsigned DEFAULT NULL,
  `responsable_convivencia_id` int(10) unsigned DEFAULT NULL,
  `director_id` int(10) unsigned DEFAULT NULL,
  `estado_acta_id` int(10) unsigned NOT NULL DEFAULT 1,
  `observaciones` text DEFAULT NULL,
  `creado_en` timestamp NOT NULL DEFAULT current_timestamp(),
  `actualizado_en` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`acta_id`),
  UNIQUE KEY `uk_acta_codigo` (`codigo_acta`),
  KEY `idx_acta_fecha` (`fecha_acta`),
  KEY `fk_acta_expediente` (`expediente_id`),
  KEY `fk_acta_tipo` (`tipo_acta_id`),
  KEY `fk_acta_seccion` (`seccion_id`),
  KEY `fk_acta_tutor` (`tutor_id`),
  KEY `fk_acta_resp_conv` (`responsable_convivencia_id`),
  KEY `fk_acta_director` (`director_id`),
  KEY `fk_acta_estado` (`estado_acta_id`),
  CONSTRAINT `conv_fk_acta_director` FOREIGN KEY (`director_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_acta_estado` FOREIGN KEY (`estado_acta_id`) REFERENCES `conv_estado_acta` (`estado_acta_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_acta_expediente` FOREIGN KEY (`expediente_id`) REFERENCES `conv_expediente_convivencia` (`expediente_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_acta_resp_conv` FOREIGN KEY (`responsable_convivencia_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_acta_seccion` FOREIGN KEY (`seccion_id`) REFERENCES `conv_seccion` (`seccion_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_acta_tipo` FOREIGN KEY (`tipo_acta_id`) REFERENCES `conv_tipo_acta` (`tipo_acta_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_acta_tutor` FOREIGN KEY (`tutor_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_acta_norma` (
  `acta_id` int(10) unsigned NOT NULL,
  `norma_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`acta_id`,`norma_id`),
  KEY `fk_acta_norma_norma` (`norma_id`),
  CONSTRAINT `conv_fk_acta_norma_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_acta_norma_norma` FOREIGN KEY (`norma_id`) REFERENCES `conv_norma_convivencia` (`norma_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_acta_respuesta_campo` (
  `respuesta_campo_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `campo_id` int(10) unsigned NOT NULL,
  `valor_texto` text DEFAULT NULL,
  `valor_fecha` date DEFAULT NULL,
  `valor_numero` decimal(12,2) DEFAULT NULL,
  `valor_booleano` tinyint(1) DEFAULT NULL,
  `creado_en` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`respuesta_campo_id`),
  UNIQUE KEY `uk_respuesta_campo` (`acta_id`,`campo_id`),
  KEY `fk_arc_campo` (`campo_id`),
  CONSTRAINT `conv_fk_arc_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_arc_campo` FOREIGN KEY (`campo_id`) REFERENCES `conv_plantilla_campo` (`campo_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_acta_respuesta_formativa` (
  `respuesta_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `pregunta_id` int(10) unsigned NOT NULL,
  `respuesta` text DEFAULT NULL,
  `creado_en` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`respuesta_id`),
  UNIQUE KEY `uk_respuesta_acta_pregunta` (`acta_id`,`pregunta_id`),
  KEY `fk_respuesta_pregunta` (`pregunta_id`),
  CONSTRAINT `conv_fk_respuesta_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_respuesta_pregunta` FOREIGN KEY (`pregunta_id`) REFERENCES `conv_pregunta_formativa` (`pregunta_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_acta_situacion` (
  `acta_situacion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `situacion_id` int(10) unsigned NOT NULL,
  `observacion` text DEFAULT NULL,
  PRIMARY KEY (`acta_situacion_id`),
  KEY `fk_as_acta` (`acta_id`),
  KEY `fk_as_situacion` (`situacion_id`),
  CONSTRAINT `conv_fk_as_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_as_situacion` FOREIGN KEY (`situacion_id`) REFERENCES `conv_situacion_acta` (`situacion_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_actor_compromiso` (
  `actor_compromiso_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(80) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`actor_compromiso_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_actor_compromiso` (`actor_compromiso_id`, `nombre`, `descripcion`) VALUES (1,'Estudiante','Compromisos asumidos directamente por el estudiante.'),(2,'Familia','Compromisos asumidos por padre, madre, tutor legal o apoderado.'),(3,'Tutor/docente/responsable','Compromisos de acompañamiento, retroalimentación y seguimiento.'),(4,'Dirección','Acciones o disposiciones asumidas por Dirección.'),(5,'Comité de Gestión del Bienestar','Intervención del comité ante casos que exceden la tutoría.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_anio_lectivo` (
  `anio_lectivo_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `institucion_id` int(10) unsigned NOT NULL,
  `anio` smallint(5) unsigned NOT NULL,
  `fecha_inicio` date DEFAULT NULL,
  `fecha_fin` date DEFAULT NULL,
  `estado` varchar(20) NOT NULL DEFAULT 'Activo',
  PRIMARY KEY (`anio_lectivo_id`),
  UNIQUE KEY `uk_anio_ie` (`institucion_id`,`anio`),
  CONSTRAINT `conv_fk_anio_ie` FOREIGN KEY (`institucion_id`) REFERENCES `conv_institucion_educativa` (`institucion_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_anio_lectivo` (`anio_lectivo_id`, `institucion_id`, `anio`, `fecha_inicio`, `fecha_fin`, `estado`) VALUES (1,1,2026,'2026-03-01','2026-12-31','Activo');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_apoderado_estudiante` (
  `apoderado_estudiante_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `estudiante_id` int(10) unsigned NOT NULL,
  `apoderado_id` int(10) unsigned NOT NULL,
  `parentesco` varchar(60) NOT NULL,
  `es_principal` tinyint(1) NOT NULL DEFAULT 1,
  `vive_con_estudiante` tinyint(1) NOT NULL DEFAULT 0,
  `observacion` text DEFAULT NULL,
  PRIMARY KEY (`apoderado_estudiante_id`),
  UNIQUE KEY `uk_apoderado_estudiante` (`estudiante_id`,`apoderado_id`),
  KEY `fk_ae_apoderado` (`apoderado_id`),
  CONSTRAINT `conv_fk_ae_apoderado` FOREIGN KEY (`apoderado_id`) REFERENCES `conv_persona` (`persona_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_ae_estudiante` FOREIGN KEY (`estudiante_id`) REFERENCES `conv_estudiante` (`estudiante_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_base_legal` (
  `base_legal_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `documento_id` int(10) unsigned NOT NULL,
  `norma` varchar(180) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  PRIMARY KEY (`base_legal_id`),
  KEY `fk_base_legal_doc` (`documento_id`),
  CONSTRAINT `conv_fk_base_legal_doc` FOREIGN KEY (`documento_id`) REFERENCES `conv_documento_gestion` (`documento_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_base_legal` (`base_legal_id`, `documento_id`, `norma`, `descripcion`, `orden`) VALUES (1,1,'Constitución Política del Perú','Establece el derecho fundamental a la educación y la responsabilidad del Estado de garantizar su calidad y equidad.',1),(2,1,'Ley N° 28044 - Ley General de Educación','Regula el sistema educativo peruano y establece principios, fines y organización de la educación.',2),(3,1,'Decreto Supremo N.° 011-2012-ED','Reglamento de la Ley General de Educación; el artículo 137 señala que el Reglamento Interno regula la organización y funcionamiento integral de la institución educativa.',3),(4,1,'Ley N° 29944 - Ley de Reforma Magisterial','Regula derechos, deberes y desarrollo profesional de los docentes.',4),(5,1,'Decreto Supremo N° 004-2013-ED','Reglamento de la Ley de Reforma Magisterial.',5),(6,1,'Ley N° 28988','Declara a la Educación Básica Regular como servicio público esencial.',6),(7,1,'Ley N° 27337 - Código de los Niños y Adolescentes','Garantiza la protección integral de los derechos de los estudiantes.',7),(8,1,'Decreto Supremo N° 004-2018-MINEDU','Lineamientos para la gestión de la convivencia escolar, prevención y atención de la violencia contra estudiantes.',8),(9,1,'Resolución Ministerial N° 474-2022-MINEDU','Disposiciones para la prestación del servicio educativo en instituciones educativas de Educación Básica.',9),(10,1,'Resolución Ministerial N° 094-2020-MINEDU','Norma sobre evaluación de los aprendizajes en Educación Básica.',10),(11,1,'Resolución Ministerial N° 447-2020-MINEDU','Disposiciones sobre el proceso de matrícula en instituciones educativas públicas.',11);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_categoria_situacion` (
  `categoria_situacion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(120) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`categoria_situacion_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_categoria_situacion` (`categoria_situacion_id`, `nombre`, `descripcion`) VALUES (1,'Asistencia y presentación','Situaciones vinculadas a puntualidad, asistencia, uniforme y presentación personal.'),(2,'Responsabilidad académica','Situaciones vinculadas a materiales, participación y evidencias de aprendizaje.'),(3,'Convivencia y buen trato','Situaciones vinculadas a agresiones, conflictos, burlas o discriminación.'),(4,'Bien común e infraestructura','Situaciones vinculadas a bienes, mobiliario, ambientes y recursos educativos.'),(5,'Objetos no permitidos','Situaciones vinculadas a celulares, audífonos, objetos peligrosos o sustancias no permitidas.'),(6,'Hábitos saludables','Situaciones vinculadas a higiene, autocuidado, salud y alimentación.'),(7,'Causa identificada','Causas asociadas a una situación de convivencia o asistencia.'),(8,'Otro','Situación no prevista en los catálogos.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_cierre_seguimiento_acta` (
  `cierre_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `decision_id` int(10) unsigned NOT NULL,
  `fecha_cierre` date NOT NULL,
  `observaciones` text DEFAULT NULL,
  `responsable_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`cierre_id`),
  UNIQUE KEY `uk_cierre_acta` (`acta_id`),
  KEY `fk_cierre_decision` (`decision_id`),
  KEY `fk_cierre_responsable` (`responsable_id`),
  CONSTRAINT `conv_fk_cierre_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_cierre_decision` FOREIGN KEY (`decision_id`) REFERENCES `conv_decision_cierre` (`decision_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_cierre_responsable` FOREIGN KEY (`responsable_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_comite_funcion` (
  `comite_funcion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `comite_id` int(10) unsigned NOT NULL,
  `descripcion` text NOT NULL,
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  PRIMARY KEY (`comite_funcion_id`),
  KEY `fk_comite_funcion` (`comite_id`),
  CONSTRAINT `conv_fk_comite_funcion` FOREIGN KEY (`comite_id`) REFERENCES `conv_comite_institucional` (`comite_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_comite_funcion` (`comite_funcion_id`, `comite_id`, `descripcion`, `orden`) VALUES (1,3,'Elaborar, ejecutar y evaluar acciones de tutoría, orientación educativa y convivencia escolar integradas a los instrumentos de gestión.',1),(2,3,'Contribuir en la prevención y atención oportuna de casos de violencia escolar y otras situaciones de vulneración de derechos.',2),(3,3,'Articular acciones con instituciones públicas, privadas, autoridades comunales y locales para consolidar redes de apoyo.',3),(4,3,'Promover disciplina, ciudadanía y sana convivencia con enfoque de derechos, sin castigos físicos, humillantes ni discriminatorios.',4);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_comite_institucional` (
  `comite_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `institucion_id` int(10) unsigned NOT NULL,
  `nombre` varchar(160) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `compromiso_cge` varchar(20) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`comite_id`),
  UNIQUE KEY `uk_comite_ie_nombre` (`institucion_id`,`nombre`),
  CONSTRAINT `conv_fk_comite_ie` FOREIGN KEY (`institucion_id`) REFERENCES `conv_institucion_educativa` (`institucion_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_comite_institucional` (`comite_id`, `institucion_id`, `nombre`, `descripcion`, `compromiso_cge`, `estado`) VALUES (1,1,'Comité de Gestión de Condiciones Operativas','Comité responsable de condiciones operativas, recursos, infraestructura, gestión de riesgos, matrícula y sostenimiento del servicio educativo.','CGE 3',1),(2,1,'Comité de Gestión Pedagógica','Comité orientado al logro de aprendizajes, comunidades de aprendizaje, uso pedagógico de recursos y PEAI.','CGE 4',1),(3,1,'Comité de Gestión del Bienestar','Comité responsable de tutoría, orientación educativa, convivencia escolar, prevención y atención de violencia y bienestar estudiantil.','CGE 5',1),(4,1,'Brigadas de Educación Ambiental y Gestión del Riesgo de Desastres','Brigadas para enfoque ambiental, gestión del riesgo, simulacros y proyectos ambientales.',NULL,1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_compromiso_acta` (
  `compromiso_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `actor_compromiso_id` int(10) unsigned NOT NULL,
  `persona_id` int(10) unsigned DEFAULT NULL,
  `descripcion` text NOT NULL,
  `fecha_inicio` date DEFAULT NULL,
  `fecha_plazo` date DEFAULT NULL,
  `estado` varchar(30) NOT NULL DEFAULT 'Pendiente',
  `fecha_cumplimiento` date DEFAULT NULL,
  `observacion` text DEFAULT NULL,
  PRIMARY KEY (`compromiso_id`),
  KEY `fk_comp_acta` (`acta_id`),
  KEY `fk_comp_actor` (`actor_compromiso_id`),
  KEY `fk_comp_persona` (`persona_id`),
  CONSTRAINT `conv_fk_comp_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_comp_actor` FOREIGN KEY (`actor_compromiso_id`) REFERENCES `conv_actor_compromiso` (`actor_compromiso_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_comp_persona` FOREIGN KEY (`persona_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_compromiso_predefinido` (
  `compromiso_predefinido_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tipo_acta_id` int(10) unsigned DEFAULT NULL,
  `actor_compromiso_id` int(10) unsigned NOT NULL,
  `descripcion` text NOT NULL,
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`compromiso_predefinido_id`),
  KEY `fk_compromiso_pre_tipo` (`tipo_acta_id`),
  KEY `fk_compromiso_pre_actor` (`actor_compromiso_id`),
  CONSTRAINT `conv_fk_compromiso_pre_actor` FOREIGN KEY (`actor_compromiso_id`) REFERENCES `conv_actor_compromiso` (`actor_compromiso_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_compromiso_pre_tipo` FOREIGN KEY (`tipo_acta_id`) REFERENCES `conv_tipo_acta` (`tipo_acta_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_compromiso_predefinido` (`compromiso_predefinido_id`, `tipo_acta_id`, `actor_compromiso_id`, `descripcion`, `orden`, `estado`) VALUES (1,NULL,2,'Acompañar diariamente el cumplimiento de las normas.',1,1),(2,NULL,2,'Mantener comunicación con tutoría.',2,1),(3,NULL,2,'Asistir a las reuniones convocadas.',3,1),(4,NULL,3,'Realizar seguimiento formativo.',1,1),(5,NULL,3,'Brindar retroalimentación oportuna.',2,1),(6,NULL,3,'Informar avances y dificultades.',3,1),(7,2,1,'Asistir puntualmente.',1,1),(8,2,1,'Organizar uniforme y materiales desde el día anterior.',2,1),(9,2,1,'Comunicar dificultades oportunamente.',3,1),(10,2,1,'Respetar el horario de ingreso.',4,1),(11,2,2,'Garantizar la llegada puntual.',1,1),(12,2,2,'Justificar inasistencias o tardanzas.',2,1),(13,2,2,'Verificar presentación personal y materiales.',3,1),(14,2,2,'Comunicar situaciones familiares o de salud.',4,1),(15,3,1,'Traer cuadernos, textos y útiles necesarios.',1,1),(16,3,1,'Participar en actividades.',2,1),(17,3,1,'Presentar evidencias en fechas acordadas.',3,1),(18,3,1,'Pedir apoyo cuando tenga dificultades.',4,1),(19,3,2,'Revisar diariamente materiales.',1,1),(20,3,2,'Acondicionar horario de estudio.',2,1),(21,3,2,'Revisar cuaderno o medio de comunicación.',3,1),(22,3,2,'Asistir a reuniones de seguimiento.',4,1),(23,4,1,'Tratar con respeto a compañeros, docentes y personal.',1,1),(24,4,1,'Evitar insultos, burlas, apodos y agresiones.',2,1),(25,4,1,'Usar el diálogo para resolver conflictos.',3,1),(26,4,1,'Pedir apoyo del tutor cuando sea necesario.',4,1),(27,5,1,'Cuidar ambientes, mobiliario y materiales.',1,1),(28,5,1,'Usar adecuadamente los bienes comunes.',2,1),(29,5,1,'Informar daños observados.',3,1),(30,5,1,'Participar en acciones de limpieza o conservación.',4,1),(31,5,2,'Orientar sobre el cuidado del bien común.',1,1),(32,5,2,'Asumir, de corresponder, la reparación o reposición.',2,1),(33,5,2,'Participar en acciones de mejora institucional.',3,1),(34,6,1,'No traer objetos no permitidos.',1,1),(35,6,1,'Usar tecnología solo con autorización pedagógica.',2,1),(36,6,1,'Respetar normas sobre celulares.',3,1),(37,6,1,'Cuidar mi seguridad y la de mis compañeros.',4,1),(38,6,2,'Verificar que no porte objetos no permitidos.',1,1),(39,6,2,'Orientar sobre tecnología responsable.',2,1),(40,6,2,'Coordinar casos excepcionales de comunicación urgente con tutoría.',3,1),(41,7,1,'Cuidar mi higiene personal diariamente.',1,1),(42,7,1,'Asistir con presentación adecuada.',2,1),(43,7,1,'Practicar lavado de manos.',3,1),(44,7,1,'Consumir alimentos saludables.',4,1),(45,7,1,'Comunicar malestar o dificultad de salud.',5,1),(46,7,2,'Supervisar higiene y presentación personal.',1,1),(47,7,2,'Promover alimentación saludable.',2,1),(48,7,2,'Comunicar situaciones de salud.',3,1),(49,7,2,'Coordinar con la IE y puesto de salud cuando sea necesario.',4,1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_criterio_seguimiento` (
  `criterio_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(180) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`criterio_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_criterio_seguimiento` (`criterio_id`, `nombre`, `descripcion`, `estado`) VALUES (1,'Reconoce la norma incumplida','El estudiante identifica la norma relacionada con la situación.',1),(2,'Reflexiona sobre las consecuencias de su conducta','El estudiante comprende efectos de su conducta en sí mismo y en otros.',1),(3,'Cumple los compromisos asumidos','El estudiante evidencia cumplimiento progresivo de compromisos.',1),(4,'Repara o mejora la situación generada','El estudiante desarrolla acciones reparadoras o de mejora.',1),(5,'Demuestra cambios sostenidos en su conducta','El cambio se mantiene durante el periodo de seguimiento.',1),(6,'Recibe acompañamiento de la familia','La familia participa y acompaña el proceso de mejora.',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_decision_cierre` (
  `decision_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(180) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`decision_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_decision_cierre` (`decision_id`, `nombre`, `descripcion`, `estado`) VALUES (1,'Cumplió satisfactoriamente los compromisos','Se cierra el seguimiento con cumplimiento adecuado.',1),(2,'Requiere ampliar el plazo de seguimiento','Se amplía el seguimiento formativo por necesidad de mayor acompañamiento.',1),(3,'Requiere intervención del Comité de Gestión del Bienestar','Se deriva internamente al Comité de Gestión del Bienestar.',1),(4,'Requiere derivación a aliado estratégico según corresponda','Se deriva externamente por requerir soporte especializado.',1),(5,'Requiere nueva reunión con la familia','Se programa nueva reunión con padre, madre o apoderado.',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_derivacion_caso` (
  `derivacion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `aliado_id` int(10) unsigned NOT NULL,
  `fecha_derivacion` date NOT NULL,
  `motivo` text NOT NULL,
  `estado` varchar(40) NOT NULL DEFAULT 'Derivado',
  `respuesta` text DEFAULT NULL,
  `fecha_respuesta` date DEFAULT NULL,
  PRIMARY KEY (`derivacion_id`),
  KEY `fk_derivacion_acta` (`acta_id`),
  KEY `fk_derivacion_aliado` (`aliado_id`),
  CONSTRAINT `conv_fk_derivacion_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_derivacion_aliado` FOREIGN KEY (`aliado_id`) REFERENCES `conv_institucion_aliada` (`aliado_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_documento_gestion` (
  `documento_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `institucion_id` int(10) unsigned NOT NULL,
  `anio_lectivo_id` int(10) unsigned DEFAULT NULL,
  `tipo_documento` varchar(80) NOT NULL,
  `titulo` varchar(220) NOT NULL,
  `finalidad` text DEFAULT NULL,
  `responsable` varchar(180) DEFAULT NULL,
  `version_documento` varchar(50) DEFAULT NULL,
  `fecha_documento` date DEFAULT NULL,
  `archivo_referencia` varchar(255) DEFAULT NULL,
  `estado` varchar(20) NOT NULL DEFAULT 'Vigente',
  PRIMARY KEY (`documento_id`),
  KEY `fk_doc_ie` (`institucion_id`),
  KEY `fk_doc_anio` (`anio_lectivo_id`),
  CONSTRAINT `conv_fk_doc_anio` FOREIGN KEY (`anio_lectivo_id`) REFERENCES `conv_anio_lectivo` (`anio_lectivo_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_doc_ie` FOREIGN KEY (`institucion_id`) REFERENCES `conv_institucion_educativa` (`institucion_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_documento_gestion` (`documento_id`, `institucion_id`, `anio_lectivo_id`, `tipo_documento`, `titulo`, `finalidad`, `responsable`, `version_documento`, `fecha_documento`, `archivo_referencia`, `estado`) VALUES (1,1,1,'Reglamento Interno','Reglamento Interno 2026','Regular la organización, funcionamiento integral, derechos, responsabilidades, normas de convivencia y mecanismos de atención de la comunidad educativa.','Dirección','2026','2026-03-10','RI - 2026.docx','Vigente'),(2,1,1,'Plantillas de actas','Modelos de Actas de Compromiso Formativo de Convivencia Escolar','Acompañamiento, reflexión, reparación y mejora progresiva de la conducta.','Dirección, Comité de Gestión del Bienestar, tutores y docentes','2026','2026-06-11','Actas_Compromiso_Formativo_Convivencia_IE0003_El_Dorado.docx','Vigente');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_estado_acta` (
  `estado_acta_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(40) NOT NULL,
  `descripcion` text NOT NULL,
  PRIMARY KEY (`estado_acta_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_estado_acta` (`estado_acta_id`, `nombre`, `descripcion`) VALUES (1,'Abierto','El compromiso se encuentra en proceso de seguimiento.'),(2,'Cumplido','El estudiante evidenció mejora y cumplió los acuerdos.'),(3,'Ampliado','Se requiere mayor tiempo de acompañamiento.'),(4,'Derivado','El caso requiere intervención de Comité de Bienestar o aliado estratégico.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_estudiante` (
  `estudiante_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `persona_id` int(10) unsigned NOT NULL,
  `codigo_estudiante` varchar(30) DEFAULT NULL,
  `seccion_id` int(10) unsigned DEFAULT NULL,
  `anio_lectivo_id` int(10) unsigned DEFAULT NULL,
  `condicion` varchar(40) NOT NULL DEFAULT 'Regular',
  `observacion` text DEFAULT NULL,
  PRIMARY KEY (`estudiante_id`),
  UNIQUE KEY `uk_estudiante_persona_anio` (`persona_id`,`anio_lectivo_id`),
  KEY `fk_estudiante_seccion` (`seccion_id`),
  KEY `fk_estudiante_anio` (`anio_lectivo_id`),
  CONSTRAINT `conv_fk_estudiante_anio` FOREIGN KEY (`anio_lectivo_id`) REFERENCES `conv_anio_lectivo` (`anio_lectivo_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_estudiante_persona` FOREIGN KEY (`persona_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_estudiante_seccion` FOREIGN KEY (`seccion_id`) REFERENCES `conv_seccion` (`seccion_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_expediente_convivencia` (
  `expediente_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `estudiante_id` int(10) unsigned NOT NULL,
  `anio_lectivo_id` int(10) unsigned NOT NULL,
  `codigo_expediente` varchar(40) NOT NULL,
  `fecha_apertura` date NOT NULL,
  `motivo_apertura` text DEFAULT NULL,
  `estado` varchar(30) NOT NULL DEFAULT 'Activo',
  PRIMARY KEY (`expediente_id`),
  UNIQUE KEY `uk_expediente_codigo` (`codigo_expediente`),
  UNIQUE KEY `uk_expediente_estudiante_anio` (`estudiante_id`,`anio_lectivo_id`),
  KEY `fk_exp_anio` (`anio_lectivo_id`),
  CONSTRAINT `conv_fk_exp_anio` FOREIGN KEY (`anio_lectivo_id`) REFERENCES `conv_anio_lectivo` (`anio_lectivo_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_exp_estudiante` FOREIGN KEY (`estudiante_id`) REFERENCES `conv_estudiante` (`estudiante_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_firma_acta` (
  `firma_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `persona_id` int(10) unsigned DEFAULT NULL,
  `rol_firma` varchar(80) NOT NULL,
  `nombre_firmante` varchar(180) DEFAULT NULL,
  `dni_firmante` varchar(15) DEFAULT NULL,
  `fecha_firma` date DEFAULT NULL,
  `firmado` tinyint(1) NOT NULL DEFAULT 0,
  `observacion` text DEFAULT NULL,
  PRIMARY KEY (`firma_id`),
  KEY `fk_firma_acta` (`acta_id`),
  KEY `fk_firma_persona` (`persona_id`),
  CONSTRAINT `conv_fk_firma_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_firma_persona` FOREIGN KEY (`persona_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_grado` (
  `grado_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nivel_id` int(10) unsigned NOT NULL,
  `nombre` varchar(50) NOT NULL,
  `numero` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`grado_id`),
  UNIQUE KEY `uk_grado_nivel_numero` (`nivel_id`,`numero`),
  CONSTRAINT `conv_fk_grado_nivel` FOREIGN KEY (`nivel_id`) REFERENCES `conv_nivel_educativo` (`nivel_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_grado` (`grado_id`, `nivel_id`, `nombre`, `numero`) VALUES (1,1,'Primer grado de primaria',1),(2,1,'Segundo grado de primaria',2),(3,1,'Tercer grado de primaria',3),(4,1,'Cuarto grado de primaria',4),(5,1,'Quinto grado de primaria',5),(6,1,'Sexto grado de primaria',6),(7,2,'Primer grado de secundaria',1),(8,2,'Segundo grado de secundaria',2),(9,2,'Tercer grado de secundaria',3),(10,2,'Cuarto grado de secundaria',4),(11,2,'Quinto grado de secundaria',5);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_institucion_aliada` (
  `aliado_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(160) NOT NULL,
  `proposito` text NOT NULL,
  `direccion` varchar(180) DEFAULT NULL,
  `actor_clave` varchar(160) DEFAULT NULL,
  `contacto` varchar(80) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`aliado_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_institucion_aliada` (`aliado_id`, `nombre`, `proposito`, `direccion`, `actor_clave`, `contacto`, `estado`) VALUES (1,'Centro de Emergencia Mujer','Servicio público especializado y gratuito de atención integral y multidisciplinaria para víctimas de violencia familiar y sexual.','Saposoa','Cristina Sánchez Infante',NULL,1),(2,'Centro de Salud','Atención a emergencias y accidentes de cualquier miembro de la comunidad educativa.','Centro de Salud El Dorado','Erika Julissa Huertas Alemán',NULL,1),(3,'Ronda Campesina','Garantiza el orden público, la seguridad ciudadana y la paz social.','C.P. El Dorado','Sr. Melanio Zurita',NULL,1),(4,'Fiscalía Especializada de Familia','Interviene en casos de violencia familiar, abandono, tutela de derechos de menores y acciones preventivas.','Saposoa',NULL,NULL,1),(5,'Defensoría del Pueblo','Defiende derechos de las personas y supervisa la actuación estatal y la prestación de servicios públicos.','Saposoa',NULL,NULL,1),(6,'DEMUNA','Protege y promueve los derechos de niños y adolescentes en la jurisdicción municipal.','Saposoa','MPH',NULL,1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_institucion_educativa` (
  `institucion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `codigo_modular` varchar(20) DEFAULT NULL,
  `nombre` varchar(180) NOT NULL,
  `tipo_gestion` varchar(80) NOT NULL DEFAULT 'Pública',
  `modalidad` varchar(80) NOT NULL DEFAULT 'Educación Básica Regular',
  `centro_poblado` varchar(120) NOT NULL,
  `distrito` varchar(120) NOT NULL,
  `provincia` varchar(120) NOT NULL,
  `region` varchar(120) NOT NULL,
  `direccion_referencia` varchar(255) DEFAULT NULL,
  `resolucion_aprobacion` varchar(80) DEFAULT NULL,
  `fecha_aprobacion` date DEFAULT NULL,
  `mision` text DEFAULT NULL,
  `vision` text DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `creado_en` timestamp NOT NULL DEFAULT current_timestamp(),
  `actualizado_en` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`institucion_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_institucion_educativa` (`institucion_id`, `codigo_modular`, `nombre`, `tipo_gestion`, `modalidad`, `centro_poblado`, `distrito`, `provincia`, `region`, `direccion_referencia`, `resolucion_aprobacion`, `fecha_aprobacion`, `mision`, `vision`, `estado`, `creado_en`, `actualizado_en`) VALUES (1,NULL,'Institución Educativa Integrada N.° 0003 - El Dorado','Pública','Educación Básica Regular','El Dorado','Saposoa','Huallaga','San Martín',NULL,'020-2026-I.E. N° 0003-ED-CPD','2026-03-10','Somos una Institución Educativa Integrada Pública que brinda educación de calidad mediante gestión escolar participativa, concertada y orientada a la mejora continua, promoviendo aprendizajes significativos, valores, convivencia democrática, inclusión y formación integral.','Al 2027, la I.E. N.° 0003 del Centro Poblado El Dorado aspira a ser reconocida como una institución pública que brinda servicio educativo de calidad en primaria y secundaria, con cultura de prevención y mejora continua, intercultural, inclusiva, equitativa y ambientalmente responsable.',1,'2026-06-11 15:50:18','2026-06-11 15:50:18');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_linea_accion_convivencia` (
  `linea_accion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(120) NOT NULL,
  `descripcion` text NOT NULL,
  PRIMARY KEY (`linea_accion_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_linea_accion_convivencia` (`linea_accion_id`, `nombre`, `descripcion`) VALUES (1,'Promoción de la convivencia escolar','Fomento, fortalecimiento y reconocimiento de relaciones democráticas basadas en el buen trato para la formación integral y el logro de aprendizajes.'),(2,'Prevención de la violencia contra niñas, niños y adolescentes','Intervención anticipada mediante acciones preventivas y redes de aliados estratégicos frente a mayor exposición a violencia directa o potencial.'),(3,'Atención de la violencia contra niñas, niños y adolescentes','Intervención oportuna, efectiva y reparadora ante hechos de violencia en el ámbito escolar o fuera de él.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_mecanismo_conflicto` (
  `mecanismo_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ambito` varchar(80) NOT NULL,
  `descripcion` text NOT NULL,
  PRIMARY KEY (`mecanismo_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_mecanismo_conflicto` (`mecanismo_id`, `ambito`, `descripcion`) VALUES (1,'Conflictos que involucran a estudiantes','Ruta institucional gradual para conflictos con estudiantes, con participación de familia y registro de evidencias.'),(2,'Conflictos entre personal de la I.E.','Ruta con testimonios, CONEI/APAFA u órgano equivalente, actas y reserva del caso.'),(3,'Conflictos que involucran a familias','Ruta con directivo, CONEI, evidencias, conciliación cuando corresponda, acuerdos escritos y consulta a UGEL si requiere sanción administrativa.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_mecanismo_conflicto_paso` (
  `paso_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `mecanismo_id` int(10) unsigned NOT NULL,
  `orden` smallint(5) unsigned NOT NULL,
  `accion` text NOT NULL,
  PRIMARY KEY (`paso_id`),
  KEY `fk_mcp_mecanismo` (`mecanismo_id`),
  CONSTRAINT `conv_fk_mcp_mecanismo` FOREIGN KEY (`mecanismo_id`) REFERENCES `conv_mecanismo_conflicto` (`mecanismo_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_mecanismo_conflicto_paso` (`paso_id`, `mecanismo_id`, `orden`, `accion`) VALUES (1,1,1,'Primera instancia: docente y familia.'),(2,1,2,'Segunda instancia: tutor y familia.'),(3,1,3,'Si no se resuelve, solicitar cita con Dirección.'),(4,1,4,'Considerar protocolos de atención a la violencia establecidos en el D.S. N.° 004-2018-MINEDU.'),(5,1,5,'Registrar en libro de incidencias y portal SíseVe cuando corresponda.'),(6,1,6,'Recolectar evidencias: videos, fotografías, capturas, testimonios escritos, actas o acuerdos firmados.'),(7,2,1,'Citar a las familias involucradas para recoger testimonio cuando corresponda.'),(8,2,2,'Involucrar CONEI y/o APAFA para evitar conflictos de intereses.'),(9,2,3,'Registrar reunión, testimonio o acuerdo en acta firmada con reserva del caso.'),(10,3,1,'Involucrar al directivo y al CONEI para asegurar mirada objetiva.'),(11,3,2,'Recopilar evidencias físicas o testimoniales.'),(12,3,3,'Buscar conciliación cuando sea procedente; ningún hecho de violencia es conciliable.'),(13,3,4,'Dejar acuerdos por escrito con firmas y acción reparadora.'),(14,3,5,'Consultar o involucrar a UGEL si requiere sanciones administrativas mayores.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_mecanismo_urgencia` (
  `urgencia_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tipo` varchar(120) NOT NULL,
  `descripcion` text NOT NULL,
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  PRIMARY KEY (`urgencia_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_mecanismo_urgencia` (`urgencia_id`, `tipo`, `descripcion`, `orden`) VALUES (1,'Intervención ante inasistencias injustificadas','Conocer motivo, definir consecuencia restitutiva, pedir compromiso familiar, recuperación académica o apoyo institucional, dejando acuerdo por escrito.',1),(2,'Actuación ante posible permanencia en el grado','Comunicar resultados, realizar reuniones, programa de recuperación pedagógica y medidas preventivas.',2),(3,'Actuación ante accidentes dentro de la I.E.','Identificar accidente, comunicar a responsable, contactar centro médico y familia, brindar primeros auxilios, trasladar si corresponde, registrar incidente.',3);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_medida_correctiva` (
  `medida_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `descripcion` text NOT NULL,
  `enfoque` varchar(80) NOT NULL DEFAULT 'Formativo',
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`medida_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_medida_correctiva` (`medida_id`, `descripcion`, `enfoque`, `estado`) VALUES (1,'Promover la autorreflexión del comportamiento del estudiante.','Formativo',1),(2,'Fomentar la reflexión empática en los estudiantes.','Formativo',1),(3,'Compromiso firmado con la familia.','Corresponsabilidad familia-escuela',1),(4,'Desarrollar habilidades socioemocionales con énfasis en autorregulación.','Socioemocional',1),(5,'Realizar acciones alentadoras para transformar la meta equivocada en una positiva.','Restaurativo',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_nivel_avance` (
  `nivel_avance_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(40) NOT NULL,
  `orden` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`nivel_avance_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_nivel_avance` (`nivel_avance_id`, `nombre`, `orden`) VALUES (1,'En inicio',1),(2,'En proceso',2),(3,'Logrado',3),(4,'Destacado',4);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_nivel_educativo` (
  `nivel_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(80) NOT NULL,
  `codigo` varchar(20) NOT NULL,
  PRIMARY KEY (`nivel_id`),
  UNIQUE KEY `uk_nivel_codigo` (`codigo`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_nivel_educativo` (`nivel_id`, `nombre`, `codigo`) VALUES (1,'Primaria','PRI'),(2,'Secundaria','SEC');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_norma_convivencia` (
  `norma_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `documento_id` int(10) unsigned NOT NULL,
  `numero` tinyint(3) unsigned NOT NULL,
  `titulo` varchar(180) NOT NULL,
  `descripcion` text NOT NULL,
  `aspecto_formativo` varchar(180) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`norma_id`),
  UNIQUE KEY `uk_norma_documento_numero` (`documento_id`,`numero`),
  CONSTRAINT `conv_fk_norma_doc` FOREIGN KEY (`documento_id`) REFERENCES `conv_documento_gestion` (`documento_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_norma_convivencia` (`norma_id`, `documento_id`, `numero`, `titulo`, `descripcion`, `aspecto_formativo`, `estado`) VALUES (1,1,1,'Asistencia, puntualidad, orden y uniforme','Asistimos diariamente a la institución educativa de manera puntual, ordenada y correctamente uniformados, respetando las disposiciones institucionales.','Asistencia diaria, puntualidad, orden y uniforme.',1),(2,1,2,'Respeto de horarios establecidos','Respetamos los horarios establecidos, considerando una tolerancia máxima de 5 minutos; las tardanzas reiteradas serán comunicadas a las familias y, de persistir, se derivarán a las instancias correspondientes.','Respeto de horarios establecidos y tolerancia de ingreso.',1),(3,1,3,'Presentación personal adecuada','Mantenemos una presentación personal adecuada según disposiciones institucionales.','Presentación personal adecuada.',1),(4,1,4,'Materiales educativos completos','Asistimos a clases con todos nuestros materiales educativos completos, evitando interrupciones del proceso de aprendizaje.','Materiales educativos completos.',1),(5,1,5,'Respeto, tolerancia y buen trato','Practicamos el respeto, la tolerancia y el buen trato entre todos los miembros de la comunidad educativa, evitando cualquier tipo de agresión física, verbal o psicológica.','Respeto, tolerancia y buen trato.',1),(6,1,6,'Participación en actividades académicas y formativas','Participamos activamente en las actividades académicas, formativas y extracurriculares programadas por la institución.','Participación en actividades académicas y formativas.',1),(7,1,7,'Cuidado de infraestructura, mobiliario y recursos','Cuidamos la infraestructura, mobiliario y recursos educativos; en caso de daños, los padres de familia asumirán la reparación o reposición en el plazo establecido.','Cuidado de infraestructura, mobiliario y recursos.',1),(8,1,8,'No portar objetos distractores o peligrosos','Evitamos portar objetos que distraigan o pongan en riesgo la seguridad escolar.','No portar objetos distractores o peligrosos.',1),(9,1,9,'Hábitos saludables, higiene y autocuidado','Promovemos hábitos saludables, higiene personal, alimentación adecuada y cuidado de la salud.','Hábitos saludables, higiene y autocuidado.',1),(10,1,10,'Cumplimiento del RI y acta de compromiso','Cumplimos los compromisos asumidos en el Reglamento Interno y el Acta de Compromiso, fortaleciendo la responsabilidad compartida entre escuela y familia.','Cumplimiento del RI y del Acta de Compromiso.',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_norma_detalle` (
  `norma_detalle_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `norma_id` int(10) unsigned NOT NULL,
  `detalle` text NOT NULL,
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  PRIMARY KEY (`norma_detalle_id`),
  KEY `fk_norma_detalle` (`norma_id`),
  CONSTRAINT `conv_fk_norma_detalle` FOREIGN KEY (`norma_id`) REFERENCES `conv_norma_convivencia` (`norma_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_norma_detalle` (`norma_detalle_id`, `norma_id`, `detalle`, `orden`) VALUES (1,3,'Las estudiantes deben asistir con el cabello recogido, sin maquillaje ni accesorios llamativos.',1),(2,3,'Los estudiantes varones deben portar corte de cabello escolar, evitando estilos inadecuados.',2),(3,3,'En temporada de frío, se permite el uso de prendas adicionales debajo del uniforme institucional.',3),(4,8,'Celulares prohibidos durante la jornada escolar.',1),(5,8,'Equipos de sonido y audífonos.',2),(6,8,'Objetos punzocortantes o peligrosos.',3),(7,8,'Productos de belleza o sustancias no permitidas.',4);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_persona` (
  `persona_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tipo_persona_id` int(10) unsigned NOT NULL,
  `dni` varchar(15) DEFAULT NULL,
  `nombres` varchar(120) NOT NULL,
  `apellido_paterno` varchar(100) DEFAULT NULL,
  `apellido_materno` varchar(100) DEFAULT NULL,
  `sexo` varchar(20) DEFAULT NULL,
  `fecha_nacimiento` date DEFAULT NULL,
  `telefono` varchar(30) DEFAULT NULL,
  `correo` varchar(120) DEFAULT NULL,
  `direccion` varchar(255) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  `creado_en` timestamp NOT NULL DEFAULT current_timestamp(),
  `actualizado_en` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`persona_id`),
  UNIQUE KEY `uk_persona_dni` (`dni`),
  KEY `idx_persona_apellidos` (`apellido_paterno`,`apellido_materno`,`nombres`),
  KEY `fk_persona_tipo` (`tipo_persona_id`),
  CONSTRAINT `conv_fk_persona_tipo` FOREIGN KEY (`tipo_persona_id`) REFERENCES `conv_tipo_persona` (`tipo_persona_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_persona_rol_institucional` (
  `persona_rol_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `persona_id` int(10) unsigned NOT NULL,
  `rol_id` int(10) unsigned NOT NULL,
  `anio_lectivo_id` int(10) unsigned DEFAULT NULL,
  `seccion_id` int(10) unsigned DEFAULT NULL,
  `fecha_inicio` date DEFAULT NULL,
  `fecha_fin` date DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`persona_rol_id`),
  UNIQUE KEY `uk_persona_rol_anio_seccion` (`persona_id`,`rol_id`,`anio_lectivo_id`,`seccion_id`),
  KEY `fk_pri_rol` (`rol_id`),
  KEY `fk_pri_anio` (`anio_lectivo_id`),
  KEY `fk_pri_seccion` (`seccion_id`),
  CONSTRAINT `conv_fk_pri_anio` FOREIGN KEY (`anio_lectivo_id`) REFERENCES `conv_anio_lectivo` (`anio_lectivo_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_pri_persona` FOREIGN KEY (`persona_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_pri_rol` FOREIGN KEY (`rol_id`) REFERENCES `conv_rol_institucional` (`rol_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_pri_seccion` FOREIGN KEY (`seccion_id`) REFERENCES `conv_seccion` (`seccion_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_plantilla_campo` (
  `campo_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `plantilla_seccion_id` int(10) unsigned NOT NULL,
  `nombre_campo` varchar(100) NOT NULL,
  `etiqueta` varchar(255) NOT NULL,
  `tipo_dato` varchar(30) NOT NULL DEFAULT 'texto',
  `obligatorio` tinyint(1) NOT NULL DEFAULT 0,
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  PRIMARY KEY (`campo_id`),
  UNIQUE KEY `uk_campo_seccion_nombre` (`plantilla_seccion_id`,`nombre_campo`),
  CONSTRAINT `conv_fk_plantilla_campo_seccion` FOREIGN KEY (`plantilla_seccion_id`) REFERENCES `conv_plantilla_seccion` (`plantilla_seccion_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_plantilla_campo` (`campo_id`, `plantilla_seccion_id`, `nombre_campo`, `etiqueta`, `tipo_dato`, `obligatorio`, `orden`) VALUES (1,1,'fecha','Fecha','fecha',1,1),(2,1,'hora','Hora','hora',0,2),(3,1,'grado_seccion','Grado y sección','texto',1,3),(4,1,'nivel','Nivel','seleccion',1,4),(5,1,'estudiante','Estudiante','texto',1,5),(6,1,'dni_estudiante','DNI del estudiante','texto',0,6),(7,1,'apoderado','Padre, madre o apoderado','texto',1,7),(8,1,'dni_apoderado','DNI del apoderado','texto',0,8),(9,1,'tutor','Tutor(a)','texto',0,9),(10,1,'responsable_convivencia','Responsable de convivencia','texto',0,10),(11,3,'descripcion_objetiva','Descripción objetiva de la situación','textarea',1,1),(12,3,'fecha_periodo_hecho','Fecha o periodo en que ocurrió','texto',0,2),(13,3,'reportado_por','Reportado u observado por','texto',0,3),(14,6,'accion_acordada','Acción acordada','textarea',0,1),(15,6,'plazo_cumplimiento','Plazo de cumplimiento','fecha',0,2);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_plantilla_campo_opcion` (
  `opcion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `campo_id` int(10) unsigned NOT NULL,
  `valor` varchar(180) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  PRIMARY KEY (`opcion_id`),
  KEY `fk_campo_opcion` (`campo_id`),
  CONSTRAINT `conv_fk_campo_opcion` FOREIGN KEY (`campo_id`) REFERENCES `conv_plantilla_campo` (`campo_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_plantilla_campo_opcion` (`opcion_id`, `campo_id`, `valor`, `descripcion`, `orden`) VALUES (1,4,'Primaria','Nivel primaria',1),(2,4,'Secundaria','Nivel secundaria',2);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_plantilla_seccion` (
  `plantilla_seccion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tipo_acta_id` int(10) unsigned NOT NULL,
  `nombre` varchar(160) NOT NULL,
  `orden` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`plantilla_seccion_id`),
  UNIQUE KEY `uk_plantilla_seccion_orden` (`tipo_acta_id`,`orden`),
  CONSTRAINT `conv_fk_plantilla_seccion_tipo` FOREIGN KEY (`tipo_acta_id`) REFERENCES `conv_tipo_acta` (`tipo_acta_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_plantilla_seccion` (`plantilla_seccion_id`, `tipo_acta_id`, `nombre`, `orden`) VALUES (1,1,'Datos generales',1),(2,1,'Norma de convivencia relacionada',2),(3,1,'Situación observada',3),(4,1,'Reflexión formativa',4),(5,1,'Compromisos asumidos',5),(6,1,'Acción reparadora o de mejora',6),(7,1,'Seguimiento',7),(8,1,'Firmas',8),(9,2,'Datos generales',1),(10,2,'Situación identificada',2),(11,2,'Análisis formativo',3),(12,2,'Compromisos del estudiante y familia',4),(13,2,'Meta de mejora y seguimiento',5),(14,2,'Firmas',6),(15,3,'Datos generales',1),(16,3,'Situación observada',2),(17,3,'Reflexión formativa',3),(18,3,'Compromisos',4),(19,3,'Evaluación formativa de avance',5),(20,3,'Firmas',6),(21,4,'Datos generales',1),(22,4,'Situación presentada',2),(23,4,'Diálogo restaurativo',3),(24,4,'Compromisos y acción reparadora',4),(25,4,'Compromiso de la familia y seguimiento',5),(26,4,'Firmas',6),(27,5,'Datos generales',1),(28,5,'Bien afectado o situación identificada',2),(29,5,'Reflexión formativa',3),(30,5,'Compromisos y acción reparadora',4),(31,5,'Seguimiento',5),(32,5,'Firmas',6),(33,6,'Datos generales',1),(34,6,'Objeto identificado',2),(35,6,'Análisis formativo',3),(36,6,'Compromisos y medida formativa',4),(37,6,'Firmas',5),(38,7,'Datos generales',1),(39,7,'Situación identificada',2),(40,7,'Reflexión formativa y compromisos',3),(41,7,'Seguimiento semanal',4),(42,7,'Firmas',5),(43,8,'Datos generales',1),(44,8,'Criterios de seguimiento',2),(45,8,'Registro de avances',3),(46,8,'Decisión formativa',4),(47,8,'Firmas',5),(48,9,'Registro consolidado',1),(49,9,'Criterios de estado del seguimiento',2),(50,9,'Firmas institucionales',3);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_pregunta_formativa` (
  `pregunta_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tipo_acta_id` int(10) unsigned DEFAULT NULL,
  `texto_pregunta` varchar(255) NOT NULL,
  `enfoque` varchar(80) NOT NULL DEFAULT 'Reflexión formativa',
  `orden` smallint(5) unsigned NOT NULL DEFAULT 1,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`pregunta_id`),
  KEY `fk_pregunta_tipo_acta` (`tipo_acta_id`),
  CONSTRAINT `conv_fk_pregunta_tipo_acta` FOREIGN KEY (`tipo_acta_id`) REFERENCES `conv_tipo_acta` (`tipo_acta_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_pregunta_formativa` (`pregunta_id`, `tipo_acta_id`, `texto_pregunta`, `enfoque`, `orden`, `estado`) VALUES (1,1,'¿Qué ocurrió?','Reflexión formativa',1,1),(2,1,'¿Qué norma no se cumplió?','Reflexión formativa',2,1),(3,1,'¿A quién afectó mi conducta?','Reflexión formativa',3,1),(4,1,'¿Qué puedo hacer para mejorar?','Reflexión formativa',4,1),(5,1,'¿Qué apoyo necesito?','Reflexión formativa',5,1),(6,3,'¿Qué materiales o actividades no estoy cumpliendo?','Reflexión académica',1,1),(7,3,'¿Cómo afecta esto a mi aprendizaje?','Reflexión académica',2,1),(8,3,'¿Qué necesito para mejorar?','Reflexión académica',3,1),(9,3,'¿Qué apoyo requiero de mi familia?','Reflexión académica',4,1),(10,4,'¿Qué ocurrió?','Diálogo restaurativo',1,1),(11,4,'¿Qué pensabas o sentías?','Diálogo restaurativo',2,1),(12,4,'¿A quién afectó tu conducta?','Diálogo restaurativo',3,1),(13,4,'¿Cómo se sintió la otra persona?','Diálogo restaurativo',4,1),(14,4,'¿Qué puedes hacer para reparar?','Diálogo restaurativo',5,1),(15,4,'¿Qué harás diferente la próxima vez?','Diálogo restaurativo',6,1),(16,5,'¿Qué bien fue afectado?','Reflexión sobre bien común',1,1),(17,5,'¿Cómo afecta esto a mis compañeros?','Reflexión sobre bien común',2,1),(18,5,'¿Qué responsabilidad asumo?','Reflexión sobre bien común',3,1),(19,5,'¿Cómo puedo reparar o compensar el daño?','Reflexión sobre bien común',4,1),(20,6,'¿Por qué traje o usé este objeto?','Uso responsable de tecnología y objetos',1,1),(21,6,'¿Cómo afectó mi aprendizaje o la convivencia?','Uso responsable de tecnología y objetos',2,1),(22,6,'¿Qué decisión responsable debo tomar?','Uso responsable de tecnología y objetos',3,1),(23,6,'¿Qué apoyo necesito de mi familia?','Uso responsable de tecnología y objetos',4,1),(24,7,'¿Qué hábito debo mejorar?','Hábitos saludables',1,1),(25,7,'¿Cómo influye este hábito en mi salud?','Hábitos saludables',2,1),(26,7,'¿Qué puedo hacer diariamente para mejorar?','Hábitos saludables',3,1),(27,7,'¿Cómo me apoyará mi familia?','Hábitos saludables',4,1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_regla_asistencia` (
  `regla_asistencia_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `institucion_id` int(10) unsigned NOT NULL,
  `descripcion` text NOT NULL,
  `tolerancia_minutos` tinyint(3) unsigned DEFAULT NULL,
  `limite_tardanzas_bimestre` tinyint(3) unsigned DEFAULT NULL,
  `accion_al_superar_limite` text DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`regla_asistencia_id`),
  KEY `fk_regla_asistencia_ie` (`institucion_id`),
  CONSTRAINT `conv_fk_regla_asistencia_ie` FOREIGN KEY (`institucion_id`) REFERENCES `conv_institucion_educativa` (`institucion_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_regla_asistencia` (`regla_asistencia_id`, `institucion_id`, `descripcion`, `tolerancia_minutos`, `limite_tardanzas_bimestre`, `accion_al_superar_limite`, `estado`) VALUES (1,1,'Se considera tardanza la asistencia fuera del horario establecido o fuera de la tolerancia institucional.',5,3,'Cumplidas 03 tardanzas en un bimestre el tutor envía esquela escrita a casa; cumplida la 4.° tardanza, el estudiante debe presentarse con sus padres o apoderados para su ingreso a la I.E.',1),(2,1,'La justificación de tardanza o ausencia debe presentarse formalmente por el padre, madre o apoderado dentro del plazo establecido.',NULL,NULL,'La justificación debe contener nombres, apellidos, firma y DNI; por salud debe adjuntar receta, constancia o ficha de atención médica.',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_rol_institucional` (
  `rol_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(80) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`rol_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_rol_institucional` (`rol_id`, `nombre`, `descripcion`) VALUES (1,'Director(a)','Responsable de la conducción institucional.'),(2,'Tutor(a)','Docente responsable de acompañamiento tutorial de una sección.'),(3,'Docente','Docente de aula o área curricular.'),(4,'Responsable de convivencia','Responsable de convivencia escolar.'),(5,'Coordinador(a) de tutoría','Responsable de coordinación de tutoría y orientación educativa.'),(6,'Responsable de inclusión','Responsable de atención a la diversidad e inclusión.'),(7,'Padre/madre/apoderado','Representante familiar del estudiante.'),(8,'Estudiante','Estudiante participante del proceso formativo.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_ruta_atencion_formativa` (
  `ruta_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `paso` tinyint(3) unsigned NOT NULL,
  `accion` varchar(80) NOT NULL,
  `descripcion` text NOT NULL,
  PRIMARY KEY (`ruta_id`),
  UNIQUE KEY `uk_ruta_paso` (`paso`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_ruta_atencion_formativa` (`ruta_id`, `paso`, `accion`, `descripcion`) VALUES (1,1,'Observar','Identificar la situación con objetividad y registrar datos relevantes.'),(2,2,'Dialogar','Escuchar al estudiante y comprender causas, emociones y consecuencias.'),(3,3,'Retroalimentar','Explicar la norma, el impacto de la conducta y la mejora esperada.'),(4,4,'Comprometer','Establecer acuerdos concretos con estudiante y familia.'),(5,5,'Reparar','Definir una acción que restaure el daño o mejore la situación.'),(6,6,'Hacer seguimiento','Verificar avances, registrar evidencias y brindar nueva orientación.');
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_seccion` (
  `seccion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `grado_id` int(10) unsigned NOT NULL,
  `nombre` varchar(20) NOT NULL,
  `turno` varchar(30) DEFAULT NULL,
  `anio_lectivo_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`seccion_id`),
  UNIQUE KEY `uk_seccion_grado_anio` (`grado_id`,`nombre`,`anio_lectivo_id`),
  KEY `fk_seccion_anio` (`anio_lectivo_id`),
  CONSTRAINT `conv_fk_seccion_anio` FOREIGN KEY (`anio_lectivo_id`) REFERENCES `conv_anio_lectivo` (`anio_lectivo_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_seccion_grado` FOREIGN KEY (`grado_id`) REFERENCES `conv_grado` (`grado_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_seccion` (`seccion_id`, `grado_id`, `nombre`, `turno`, `anio_lectivo_id`) VALUES (1,1,'U','Mañana',1),(2,2,'U','Mañana',1),(3,3,'A','Mañana',1),(4,3,'B','Mañana',1),(5,4,'U','Mañana',1),(6,5,'A','Mañana',1),(7,5,'B','Mañana',1),(8,6,'U','Mañana',1),(9,7,'A','Mañana',1),(10,7,'B','Mañana',1),(11,8,'A','Mañana',1),(12,8,'B','Mañana',1),(13,9,'A','Mañana',1),(14,9,'B','Mañana',1),(15,10,'A','Mañana',1),(16,10,'B','Mañana',1),(17,11,'A','Mañana',1),(18,11,'B','Mañana',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_seguimiento_acta` (
  `seguimiento_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `acta_id` int(10) unsigned NOT NULL,
  `fecha_seguimiento` date NOT NULL,
  `avance_observado` text DEFAULT NULL,
  `dificultad_identificada` text DEFAULT NULL,
  `retroalimentacion_brindada` text DEFAULT NULL,
  `recomendacion` text DEFAULT NULL,
  `responsable_id` int(10) unsigned DEFAULT NULL,
  `creado_en` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`seguimiento_id`),
  KEY `idx_seg_acta_fecha` (`acta_id`,`fecha_seguimiento`),
  KEY `fk_seg_responsable` (`responsable_id`),
  CONSTRAINT `conv_fk_seg_acta` FOREIGN KEY (`acta_id`) REFERENCES `conv_acta_compromiso` (`acta_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_seg_responsable` FOREIGN KEY (`responsable_id`) REFERENCES `conv_persona` (`persona_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_seguimiento_criterio_evaluacion` (
  `seguimiento_criterio_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `seguimiento_id` int(10) unsigned NOT NULL,
  `criterio_id` int(10) unsigned NOT NULL,
  `nivel_avance_id` int(10) unsigned NOT NULL,
  `observacion` text DEFAULT NULL,
  PRIMARY KEY (`seguimiento_criterio_id`),
  UNIQUE KEY `uk_seg_criterio` (`seguimiento_id`,`criterio_id`),
  KEY `fk_sce_criterio` (`criterio_id`),
  KEY `fk_sce_nivel` (`nivel_avance_id`),
  CONSTRAINT `conv_fk_sce_criterio` FOREIGN KEY (`criterio_id`) REFERENCES `conv_criterio_seguimiento` (`criterio_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_sce_nivel` FOREIGN KEY (`nivel_avance_id`) REFERENCES `conv_nivel_avance` (`nivel_avance_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_sce_seguimiento` FOREIGN KEY (`seguimiento_id`) REFERENCES `conv_seguimiento_acta` (`seguimiento_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_situacion_acta` (
  `situacion_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tipo_acta_id` int(10) unsigned DEFAULT NULL,
  `categoria_situacion_id` int(10) unsigned NOT NULL,
  `nombre` varchar(180) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`situacion_id`),
  KEY `fk_situacion_tipo_acta` (`tipo_acta_id`),
  KEY `fk_situacion_categoria` (`categoria_situacion_id`),
  CONSTRAINT `conv_fk_situacion_categoria` FOREIGN KEY (`categoria_situacion_id`) REFERENCES `conv_categoria_situacion` (`categoria_situacion_id`) ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_situacion_tipo_acta` FOREIGN KEY (`tipo_acta_id`) REFERENCES `conv_tipo_acta` (`tipo_acta_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_situacion_acta` (`situacion_id`, `tipo_acta_id`, `categoria_situacion_id`, `nombre`, `descripcion`, `estado`) VALUES (1,2,1,'Tardanzas reiteradas',NULL,1),(2,2,1,'Inasistencias injustificadas',NULL,1),(3,2,1,'Uso inadecuado del uniforme',NULL,1),(4,2,1,'Presentación personal no acorde al Reglamento Interno',NULL,1),(5,2,7,'Dificultades familiares',NULL,1),(6,2,7,'Distancia, transporte o clima',NULL,1),(7,2,7,'Falta de organización personal',NULL,1),(8,2,7,'Descuido en casa',NULL,1),(9,3,2,'No trae materiales educativos',NULL,1),(10,3,2,'No cumple actividades de aprendizaje',NULL,1),(11,3,2,'No participa activamente en clase',NULL,1),(12,3,2,'No entrega evidencias de aprendizaje',NULL,1),(13,3,2,'No usa adecuadamente cuadernos de trabajo del MINEDU',NULL,1),(14,3,2,'Requiere mayor acompañamiento familiar',NULL,1),(15,4,3,'Agresión verbal',NULL,1),(16,4,3,'Agresión física',NULL,1),(17,4,3,'Burla o apodo ofensivo',NULL,1),(18,4,3,'Falta de respeto a un compañero',NULL,1),(19,4,3,'Falta de respeto a un docente',NULL,1),(20,4,3,'Exclusión o discriminación',NULL,1),(21,4,3,'Conflicto entre estudiantes',NULL,1),(22,5,4,'Carpeta o silla afectada',NULL,1),(23,5,4,'Pizarra afectada',NULL,1),(24,5,4,'Puerta o ventana afectada',NULL,1),(25,5,4,'Servicios higiénicos afectados',NULL,1),(26,5,4,'Material educativo afectado',NULL,1),(27,5,4,'Área verde afectada',NULL,1),(28,5,4,'Equipo tecnológico afectado',NULL,1),(29,6,5,'Celular durante la jornada escolar',NULL,1),(30,6,5,'Audífonos',NULL,1),(31,6,5,'Equipo de sonido',NULL,1),(32,6,5,'Objeto punzocortante',NULL,1),(33,6,5,'Producto de belleza no permitido',NULL,1),(34,6,5,'Sustancia no permitida',NULL,1),(35,7,6,'Higiene personal inadecuada',NULL,1),(36,7,6,'Presentación personal descuidada',NULL,1),(37,7,6,'Consumo frecuente de alimentos no saludables',NULL,1),(38,7,6,'Falta de cuidado frente a enfermedades',NULL,1),(39,7,6,'No práctica de lavado de manos',NULL,1),(40,NULL,8,'Otro',NULL,1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_tipo_acta` (
  `tipo_acta_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(20) NOT NULL,
  `nombre` varchar(220) NOT NULL,
  `descripcion` text DEFAULT NULL,
  `aplica_a` varchar(120) DEFAULT NULL,
  `estado` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`tipo_acta_id`),
  UNIQUE KEY `codigo` (`codigo`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_tipo_acta` (`tipo_acta_id`, `codigo`, `nombre`, `descripcion`, `aplica_a`, `estado`) VALUES (1,'M01','Acta de compromiso formativo del estudiante y padre de familia','Compromiso general por incumplimiento de una o más normas de convivencia institucional.','Normas 1 a 10',1),(2,'M02','Acta por puntualidad, asistencia y presentación personal','Atiende tardanzas, inasistencias, uniforme y presentación personal.','Normas 1, 2 y 3',1),(3,'M03','Acta por responsabilidad académica y uso de materiales educativos','Atiende materiales educativos, participación, evidencias y responsabilidades académicas.','Normas 4, 6 y 10',1),(4,'M04','Acta por buen trato y resolución pacífica de conflictos','Atiende agresiones, conflictos, faltas de respeto, exclusión y discriminación.','Norma 5',1),(5,'M05','Acta por cuidado de infraestructura, mobiliario y recursos educativos','Atiende daños o uso inadecuado de bienes, espacios y recursos institucionales.','Norma 7',1),(6,'M06','Acta por uso inadecuado de celular u objetos no permitidos','Atiende porte o uso de objetos distractores o peligrosos.','Norma 8',1),(7,'M07','Acta por hábitos saludables, higiene y autocuidado','Atiende hábitos de higiene, presentación personal, alimentación saludable y autocuidado.','Normas 3 y 9',1),(8,'M08','Ficha de seguimiento formativo del acta de compromiso','Instrumento complementario para seguimiento de compromisos de convivencia.','Aplicable a todas',1),(9,'M09','Registro consolidado de actas de compromiso','Instrumento para Dirección, Comité de Gestión del Bienestar y tutoría.','Gestión institucional',1);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_tipo_acta_norma` (
  `tipo_acta_id` int(10) unsigned NOT NULL,
  `norma_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`tipo_acta_id`,`norma_id`),
  KEY `fk_tan_norma` (`norma_id`),
  CONSTRAINT `conv_fk_tan_norma` FOREIGN KEY (`norma_id`) REFERENCES `conv_norma_convivencia` (`norma_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `conv_fk_tan_tipo_acta` FOREIGN KEY (`tipo_acta_id`) REFERENCES `conv_tipo_acta` (`tipo_acta_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_tipo_acta_norma` (`tipo_acta_id`, `norma_id`) VALUES (1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(1,10),(2,1),(2,2),(2,3),(3,4),(3,6),(3,10),(4,5),(5,7),(6,8),(7,3),(7,9),(8,1),(8,2),(8,3),(8,4),(8,5),(8,6),(8,7),(8,8),(8,9),(8,10);
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `conv_tipo_persona` (
  `tipo_persona_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(80) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`tipo_persona_id`),
  UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT IGNORE INTO `conv_tipo_persona` (`tipo_persona_id`, `nombre`, `descripcion`) VALUES (1,'Estudiante','Niña, niño o adolescente matriculado en la institución educativa.'),(2,'Apoderado','Padre, madre, tutor legal o apoderado responsable del estudiante.'),(3,'Docente','Docente responsable de área, aula o tutoría.'),(4,'Directivo','Director o responsable de gestión institucional.'),(5,'Administrativo','Personal administrativo de la institución educativa.'),(6,'Aliado institucional','Representante de institución aliada externa.');

DROP VIEW IF EXISTS vw_conv_normas_convivencia;
CREATE VIEW vw_conv_normas_convivencia AS
SELECT
    n.norma_id,
    n.numero,
    n.titulo,
    n.descripcion,
    n.aspecto_formativo,
    d.tipo_documento,
    d.titulo AS documento,
    GROUP_CONCAT(nd.detalle ORDER BY nd.orden SEPARATOR ' | ') AS detalles
FROM conv_norma_convivencia n
INNER JOIN conv_documento_gestion d ON d.documento_id = n.documento_id
LEFT JOIN conv_norma_detalle nd ON nd.norma_id = n.norma_id
GROUP BY n.norma_id, n.numero, n.titulo, n.descripcion, n.aspecto_formativo, d.tipo_documento, d.titulo;

DROP VIEW IF EXISTS vw_conv_modelos_acta;
CREATE VIEW vw_conv_modelos_acta AS
SELECT
    ta.tipo_acta_id,
    ta.codigo,
    ta.nombre,
    ta.descripcion,
    ta.aplica_a,
    ta.estado,
    COUNT(DISTINCT tan.norma_id) AS total_normas,
    COUNT(DISTINCT ps.plantilla_seccion_id) AS total_secciones,
    COUNT(DISTINCT pc.campo_id) AS total_campos,
    COUNT(DISTINCT cp.compromiso_predefinido_id) AS total_compromisos
FROM conv_tipo_acta ta
LEFT JOIN conv_tipo_acta_norma tan ON tan.tipo_acta_id = ta.tipo_acta_id
LEFT JOIN conv_plantilla_seccion ps ON ps.tipo_acta_id = ta.tipo_acta_id
LEFT JOIN conv_plantilla_campo pc ON pc.plantilla_seccion_id = ps.plantilla_seccion_id
LEFT JOIN conv_compromiso_predefinido cp ON cp.tipo_acta_id = ta.tipo_acta_id
GROUP BY ta.tipo_acta_id, ta.codigo, ta.nombre, ta.descripcion, ta.aplica_a, ta.estado;

DROP VIEW IF EXISTS vw_conv_compromisos_predefinidos;
CREATE VIEW vw_conv_compromisos_predefinidos AS
SELECT
    cp.compromiso_predefinido_id,
    ta.codigo AS modelo_codigo,
    ta.nombre AS modelo,
    ac.nombre AS actor,
    cp.descripcion,
    cp.orden,
    cp.estado
FROM conv_compromiso_predefinido cp
LEFT JOIN conv_tipo_acta ta ON ta.tipo_acta_id = cp.tipo_acta_id
INNER JOIN conv_actor_compromiso ac ON ac.actor_compromiso_id = cp.actor_compromiso_id;

SET SESSION group_concat_max_len = 10000;

INSERT INTO tut_acta_modelo (
    codigo, titulo, descripcion, normas_vinculadas, orden, estado
)
SELECT
    codigo,
    nombre,
    descripcion,
    aplica_a,
    tipo_acta_id,
    estado
FROM conv_tipo_acta
ON DUPLICATE KEY UPDATE
    titulo = VALUES(titulo),
    descripcion = VALUES(descripcion),
    normas_vinculadas = VALUES(normas_vinculadas),
    orden = VALUES(orden),
    estado = VALUES(estado);

UPDATE tut_acta_modelo m
INNER JOIN (
    SELECT
        modelo_codigo AS codigo,
        GROUP_CONCAT(CASE WHEN actor = 'Estudiante' THEN descripcion END ORDER BY orden SEPARATOR '\n') AS compromisos_estudiante,
        GROUP_CONCAT(CASE WHEN actor = 'Familia' THEN descripcion END ORDER BY orden SEPARATOR '\n') AS compromisos_familia
    FROM vw_conv_compromisos_predefinidos
    WHERE modelo_codigo IS NOT NULL
    GROUP BY modelo_codigo
) c ON c.codigo = m.codigo
SET
    m.plantilla_compromisos_estudiante = COALESCE(NULLIF(c.compromisos_estudiante, ''), m.plantilla_compromisos_estudiante),
    m.plantilla_compromisos_familia = COALESCE(NULLIF(c.compromisos_familia, ''), m.plantilla_compromisos_familia);

SET FOREIGN_KEY_CHECKS = 1;

