Create New Item
Item Type
File
Folder
Item Name
Search file in folder and subfolders...
Are you sure want to rename?
File Manager
/
AVIDOTAPP
/
controllers
:
Registrocontroller.php
Advanced Search
Upload
New Item
Settings
Back
Back Up
Advanced Editor
Save
<?php class RegistroController { private $modelo; public function __construct() { require_once 'models/EmpleadoModel.php'; require_once 'models/EntregaModel.php'; $this->modelo = new EmpleadoModel(); } // ════════════════════════════════════════════════════════════ // 1. FORMULARIO EMPLEADO (con autocompletar por cédula) // URL: index.php?controller=Registro&action=index // ════════════════════════════════════════════════════════════ public function index() { $this->verificarSesion(); $centrosCosto = $this->modelo->getCentrosCosto(); $areas = $this->modelo->getAreas(); $cargos = $this->modelo->getCargos(); $errores = $_SESSION['errores_registro'] ?? []; unset($_SESSION['errores_registro']); include 'views/registro/formulario_empleado.php'; } // ════════════════════════════════════════════════════════════ // 2. AJAX — autocompletar campos por cédula // URL: index.php?controller=Registro&action=buscarCedulaAjax // Responde JSON con los datos del último registro // ════════════════════════════════════════════════════════════ public function buscarCedulaAjax() { header('Content-Type: application/json; charset=utf-8'); $cedula = trim($_GET['cedula'] ?? ''); if (empty($cedula)) { echo json_encode(['ok' => false]); exit(); } $emp = $this->modelo->buscarUltimoRegistroPorCedula($cedula); echo $emp ? json_encode(['ok' => true, 'data' => $emp]) : json_encode(['ok' => false]); exit(); } // ════════════════════════════════════════════════════════════ // 3. GUARDAR EMPLEADO EN SESIÓN → redirige a formulario EPP // URL: index.php?controller=Registro&action=guardarEmpleadoYMostrarEPP (POST) // ════════════════════════════════════════════════════════════ public function guardarEmpleadoYMostrarEPP() { $this->verificarSesion(); if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header('Location: index.php?controller=Registro&action=index'); exit(); } $errores = $this->modelo->validarDatosEmpleado($_POST); if (!empty($errores)) { $_SESSION['errores_registro'] = $errores; header('Location: index.php?controller=Registro&action=index'); exit(); } $_SESSION['empleado_data'] = [ 'fingreso' => $_POST['fingreso'], 'ident' => strtoupper(trim($_POST['ident'])), 'nombre' => strtoupper(trim($_POST['nombre'])), 'ccosto' => $_POST['ccosto'], 'area' => $_POST['area'], 'cargo' => $_POST['cargo'], 'tallaPant' => strtoupper(trim($_POST['tallaPant'])), 'tallaCami' => strtoupper(trim($_POST['tallaCami'])), 'tallaBot' => strtoupper(trim($_POST['tallaBot'])), 'tallaChaq' => strtoupper(trim($_POST['tallaChaq'])), 'tallaImp' => strtoupper(trim($_POST['tallaImp'])), 'tpEntrega' => $_POST['tpEntrega'], 'tpContrato' => $_POST['tpContrato'], ]; header('Location: index.php?controller=Registro&action=formularioEPP'); exit(); } // ════════════════════════════════════════════════════════════ // 4. FORMULARIO EPP INDEPENDIENTE (con búsqueda por cédula) // URL: index.php?controller=Registro&action=formularioEPP // ════════════════════════════════════════════════════════════ public function formularioEPP() { $this->verificarSesion(); $empleado_data = $_SESSION['empleado_data'] ?? null; $empleado_buscado = null; $error_busqueda = ''; // Búsqueda directa por cédula (sin venir del flujo normal) if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buscar_cedula_epp'])) { $cedula = trim($_POST['cedula_busqueda'] ?? ''); if ($cedula) { $emp = $this->modelo->buscarUltimoRegistroPorCedula($cedula); if ($emp) { $empleado_buscado = $emp; // ✅ FIX: Guardar en sesión para que procesarRegistroCompleto lo encuentre $_SESSION['empleado_data'] = [ 'fingreso' => $emp['fingreso'] ?? $emp['FINGRESO'] ?? date('Y-m-d'), 'ident' => $emp['cedula'] ?? $emp['CEDULA'] ?? '', 'nombre' => $emp['nombre'] ?? $emp['NOMBRE'] ?? '', 'ccosto' => $emp['ccosto'] ?? $emp['CCOSTO'] ?? '', 'area' => $emp['area'] ?? $emp['AREA'] ?? '', 'cargo' => $emp['cargo'] ?? $emp['CARGO'] ?? '', 'tallaPant' => $emp['tallaPant'] ?? $emp['TALLAPANT'] ?? 'NO APLICA', 'tallaCami' => $emp['tallaCami'] ?? $emp['TALLACAMI'] ?? 'NO APLICA', 'tallaBot' => $emp['tallaBot'] ?? $emp['TALLABOT'] ?? 'NO APLICA', 'tallaChaq' => $emp['tallaChaq'] ?? $emp['TALLACHAQ'] ?? $emp['tallachaq'] ?? 'NO APLICA', 'tallaImp' => $emp['tallaImp'] ?? $emp['TALLAIMP'] ?? $emp['tallaimp'] ?? 'NO APLICA', 'tpEntrega' => $emp['tpEntrega'] ?? $emp['TPENTREGA'] ?? 'Primera Entrega', 'tpContrato' => $emp['tpContrato'] ?? $emp['TPCONTRATO'] ?? 'DIRECTO', ]; } else { $error_busqueda = 'No se encontró empleado registrado con cédula: ' . htmlspecialchars($cedula); } } else { $error_busqueda = 'Ingrese una cédula para buscar.'; } } $inventario = $this->modelo->getInventarioDisponible(); include 'views/registro/formulario_epp.php'; } // ════════════════════════════════════════════════════════════ // 5. PROCESAR REGISTRO COMPLETO // URL: index.php?controller=Registro&action=procesarRegistroCompleto (POST) // ✅ FIX: Detecta si el empleado ya existe (viene de búsqueda EPP) // o es nuevo (viene del flujo normal de registro) // ════════════════════════════════════════════════════════════ public function procesarRegistroCompleto() { $this->verificarSesion(); if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header('Location: index.php?controller=Registro&action=index'); exit(); } if (!isset($_SESSION['empleado_data'])) { $_SESSION['error_mensaje'] = 'No se encontraron datos del empleado.'; header('Location: index.php?controller=Registro&action=index'); exit(); } $empleado_data = $_SESSION['empleado_data']; $cedula = $empleado_data['ident']; // Preparar dotaciones (ahora incluye códigos) $dotaciones = []; foreach ($_POST['epp_seleccionados'] ?? [] as $idx => $desc) { $cant = intval($_POST['cantidades'][$idx] ?? 0); $codigo = trim($_POST['codigos'][$idx] ?? ''); if (!empty($desc) && $cant > 0) { $dotaciones[] = [ 'codigo' => $codigo, 'descripcion' => $desc, 'cantidad' => $cant ]; } } // Verificar si existe un registro PENDIENTE para este empleado en BD interna. // - Si hay uno Pendiente → agregar EPP al registro existente (no crear nuevo) // - Si no hay Pendiente → crear registro nuevo, aunque existan registros Entregados $empPendiente = $this->modelo->buscarEmpleadoPendienteEnBDInterna($cedula); if ($empPendiente) { // Registro Pendiente existente → solo agregar dotaciones al pendiente $resultado = $this->modelo->agregarDotacionesSoloEPP($cedula, $dotaciones); } else { // No hay Pendiente (o todos están Entregados) → crear registro nuevo $resultado = $this->modelo->insertarEmpleadoConDotacion($empleado_data, $dotaciones); } unset($_SESSION['empleado_data'], $_SESSION['errores_registro']); if ($resultado['success']) { $_SESSION['success_mensaje'] = $resultado['entregas_realizadas'] > 0 ? "Registro completado: {$resultado['nombre']}. EPP entregados: {$resultado['entregas_realizadas']}" : "Empleado registrado: {$resultado['nombre']}. Sin EPP entregados."; } else { $_SESSION['error_mensaje'] = "Error: {$resultado['error']}"; } header('Location: index.php?controller=Dashboard&action=index'); exit(); } // ════════════════════════════════════════════════════════════ // 6. CONSULTA REGISTRO POR CÉDULA // URL: index.php?controller=Registro&action=consultaRegistro // FIX: el formulario_empleado tenía &action=consulta_registro (incorrecto) // La URL correcta es &action=consultaRegistro // ════════════════════════════════════════════════════════════ public function consultaRegistro() { $this->verificarSesion(); $registros = []; $mensaje_error = ''; $cedula_buscar = ''; $epp_disponibles = $this->modelo->getEPPDisponiblesParaAgregar(); if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buscar_cedula'])) { $cedula_buscar = trim($_POST['cedula_consulta'] ?? ''); if ($cedula_buscar) { $registros = $this->modelo->obtenerRegistrosPorCedula($cedula_buscar); if (empty($registros)) $mensaje_error = 'No se encontraron registros para la cédula: ' . htmlspecialchars($cedula_buscar); } } include 'views/registro/consulta_registro.php'; } // ════════════════════════════════════════════════════════════ // 7. CARGA MASIVA CSV // URL: index.php?controller=Registro&action=cargaMasiva // ════════════════════════════════════════════════════════════ public function cargaMasiva() { $this->verificarSesion(); $resultados = []; $procesados = 0; $errores = []; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['archivo_csv'])) { $file = $_FILES['archivo_csv']; if ($file['error'] !== UPLOAD_ERR_OK) { $errores[] = 'Error al subir el archivo.'; } elseif (strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) !== 'csv') { $errores[] = 'Solo se aceptan archivos .csv'; } else { $handle = fopen($file['tmp_name'], 'r'); // Eliminar BOM UTF-8 si lo hubiera $bom = fread($handle, 3); if ($bom !== "\xEF\xBB\xBF") rewind($handle); $header = fgetcsv($handle, 0, ','); $header = array_map(fn($h) => strtolower(trim($h)), $header); $lineNum = 1; while (($row = fgetcsv($handle, 0, ',')) !== false) { $lineNum++; if (count($row) < 2) continue; $data = @array_combine($header, $row); if (!$data) { $errores[] = "Línea $lineNum: columnas no coinciden."; continue; } $emp = [ 'fingreso' => $data['fingreso'] ?? date('Y-m-d'), 'ident' => strtoupper(trim($data['cedula'] ?? '')), 'nombre' => strtoupper(trim($data['nombre'] ?? '')), 'ccosto' => $data['ccosto'] ?? '', 'area' => $data['area'] ?? '', 'cargo' => $data['cargo'] ?? '', 'tallaPant' => strtoupper(trim($data['tallapant'] ?? 'NO APLICA')), 'tallaCami' => strtoupper(trim($data['tallacami'] ?? 'NO APLICA')), 'tallaBot' => strtoupper(trim($data['tallabot'] ?? 'NO APLICA')), 'tallaChaq' => strtoupper(trim($data['tallachaq'] ?? 'NO APLICA')), 'tallaImp' => strtoupper(trim($data['tallaimp'] ?? 'NO APLICA')), 'tpEntrega' => $data['tpentrega'] ?? 'Primera Entrega', 'tpContrato' => $data['tpcontrato'] ?? 'DIRECTO', ]; $err = $this->modelo->validarDatosEmpleado($emp); if (!empty($err)) { $errores[] = "Línea $lineNum ({$emp['ident']}): " . implode(', ', $err); $resultados[] = ['cedula'=>$emp['ident'],'nombre'=>$emp['nombre'],'ok'=>false,'error'=>implode(', ',$err)]; continue; } $res = $this->modelo->insertarEmpleadoConDotacion($emp, []); if ($res['success']) { $procesados++; $resultados[] = ['cedula'=>$emp['ident'],'nombre'=>$emp['nombre'],'ok'=>true]; } else { $errores[] = "Línea $lineNum ({$emp['ident']}): {$res['error']}"; $resultados[] = ['cedula'=>$emp['ident'],'nombre'=>$emp['nombre'],'ok'=>false,'error'=>$res['error']]; } } fclose($handle); } } include 'views/registro/carga_masiva.php'; } // ════════════════════════════════════════════════════════════ // 8. DESCARGAR PLANTILLA CSV // URL: index.php?controller=Registro&action=descargarPlantilla // ════════════════════════════════════════════════════════════ public function descargarPlantilla() { header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=plantilla_empleados.csv'); $out = fopen('php://output', 'w'); fputs($out, "\xEF\xBB\xBF"); // BOM para Excel fputcsv($out, ['fingreso','cedula','nombre','ccosto','area','cargo', 'tallaPant','tallaCami','tallaBot','tallaChaq','tallaImp', 'tpEntrega','tpContrato']); fputcsv($out, ['2024-01-15','12345678','JUAN PEREZ','LOGISTICA','BODEGAS', 'AUXILIAR BODEGA','M','M','38','M','M','Primera Entrega','DIRECTO']); fputcsv($out, ['2024-02-01','98765432','MARIA LOPEZ','PRODUCCION','MANUFACTURA', 'OPERARIO','S','S','36','S','S','Ingreso','TEMPORAL']); fclose($out); exit(); } // ════════════════════════════════════════════════════════════ // 9. CANCELAR // ════════════════════════════════════════════════════════════ public function cancelar() { unset($_SESSION['empleado_data'], $_SESSION['errores_registro']); header('Location: index.php?controller=Dashboard&action=index'); exit(); } // ════════════════════════════════════════════════════════════ // 10. AGREGAR EPP // URL: index.php?controller=Registro&action=agregarEPP (POST) // ════════════════════════════════════════════════════════════ public function agregarEPP() { $this->verificarSesion(); if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $_SESSION['error_mensaje'] = '❌ Método no permitido'; header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } $empleado_id = intval($_POST['empleado_id'] ?? 0); $codigo_epp = trim($_POST['codigo_epp'] ?? ''); $nombre_epp = trim($_POST['nombre_epp'] ?? ''); $cantidad = intval($_POST['cantidad'] ?? 1); if (!$empleado_id || empty($nombre_epp) || $cantidad <= 0) { $_SESSION['error_mensaje'] = '❌ Datos inválidos para agregar EPP'; header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } // Verificar que el registro al que se agrega EPP esté en estado Pendiente $registro = $this->modelo->buscarEmpleadoPorId($empleado_id); if (!$registro || strtolower($registro['ESTADO'] ?? '') !== 'pendiente') { $_SESSION['error_mensaje'] = '❌ Solo se puede agregar EPP a registros en estado Pendiente. Este registro ya fue Entregado.'; header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } $resultado = $this->modelo->agregarEPPADotacion($empleado_id, $codigo_epp, $nombre_epp, $cantidad); if ($resultado['success']) { $_SESSION['success_mensaje'] = '✅ ' . $resultado['mensaje']; } else { $_SESSION['error_mensaje'] = '❌ Error: ' . $resultado['error']; } header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } // ════════════════════════════════════════════════════════════ // 11. ELIMINAR EPP // URL: index.php?controller=Registro&action=eliminarEPP (GET) // ════════════════════════════════════════════════════════════ public function eliminarEPP() { $this->verificarSesion(); $empleado_id = intval($_GET['empleado_id'] ?? 0); $nombre_epp = trim($_GET['nombre_epp'] ?? ''); if (!$empleado_id || !$nombre_epp) { $_SESSION['error_mensaje'] = '❌ Parámetros inválidos'; header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } $resultado = $this->modelo->eliminarEPPDeDotacion($empleado_id, $nombre_epp); if ($resultado['success']) { $_SESSION['success_mensaje'] = '✅ ' . $resultado['mensaje']; } else { $_SESSION['error_mensaje'] = '❌ Error: ' . $resultado['error']; } header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } // ════════════════════════════════════════════════════════════ // 12. ACTUALIZAR CANTIDAD EPP // URL: index.php?controller=Registro&action=actualizarCantidadEPP (POST) // ════════════════════════════════════════════════════════════ public function actualizarCantidadEPP() { $this->verificarSesion(); if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $_SESSION['error_mensaje'] = '❌ Método no permitido'; header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } $empleado_id = intval($_POST['empleado_id'] ?? 0); $nombre_epp = trim($_POST['nombre_epp'] ?? ''); $cantidad = intval($_POST['cantidad'] ?? 1); if (!$empleado_id || !$nombre_epp || $cantidad <= 0) { $_SESSION['error_mensaje'] = '❌ Datos inválidos'; header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } $resultado = $this->modelo->actualizarCantidadEPP($empleado_id, $nombre_epp, $cantidad); if ($resultado['success']) { $_SESSION['success_mensaje'] = '✅ ' . $resultado['mensaje']; } else { $_SESSION['error_mensaje'] = '❌ Error: ' . $resultado['error']; } header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } // ════════════════════════════════════════════════════════════ // 13. ELIMINAR REGISTRO COMPLETO // URL: index.php?controller=Registro&action=eliminarRegistro (GET) // ════════════════════════════════════════════════════════════ public function eliminarRegistro() { $this->verificarSesion(); $id = intval($_GET['id'] ?? 0); if (!$id) { $_SESSION['error_mensaje'] = '❌ ID de registro inválido'; header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } $resultado = $this->modelo->eliminarRegistroCompleto($id); if ($resultado['success']) { $_SESSION['success_mensaje'] = '✅ ' . $resultado['mensaje']; } else { $_SESSION['error_mensaje'] = '❌ Error: ' . $resultado['error']; } header('Location: index.php?controller=Registro&action=consultaRegistro'); exit(); } private function verificarSesion() { if (!isset($_SESSION['DIGITA'])) { header('Location: index.php'); exit(); } } } ?>