Find this useful? Enter your email to receive occasional updates for securing PHP code.
Signing you up...
Thank you for signing up!
PHP Decode
<?php declare(strict_types=1); require_once 'config.php'; require_once 'access-control.php..
Decoded Output download
<?php declare(strict_types=1); require_once 'config.php'; require_once 'access-control.php'; clase MovimientosProveedores { private PDO $db; private AccessControl $accessControl; private array $allowedFileTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'bmp', 'gif', 'png']; private const MAX_FILE_SIZE = 10485760; // 10MB private const UPLOAD_BASE_DIR = 'uploads/movimientos'; // Directorio base para las subidas public $error = null; public function getCentrosTrabajo(): array { try { if ($this->error) { throw new RuntimeException($this->error); } $stmt = $this->db->query("SELECT id, nombre FROM centros_trabajo WHERE id > 0 ORDER BY nombre"); if (!$stmt) { throw new RuntimeException("Error al obtener centros de trabajo: " . implode(", ", $this->db->errorInfo())); } return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { error_log("Error al obtener centros de trabajo: " . $e->getMessage()); return []; } } public function handleDownload(): void { if (!isset($_GET['download']) || empty($_GET['download'])) { return; } try { // Verificar que el archivo existe en la base de datos $stmt = $this->db->prepare("SELECT ruta_documento FROM movimientos_proveedores WHERE ruta_documento = ?"); if (!$stmt->execute([$_GET['download']])) { throw new RuntimeException("Error al verificar el archivo"); } $resultado = $stmt->fetch(PDO::FETCH_ASSOC); if (!$resultado) { throw new RuntimeException("Archivo no encontrado"); } $filePath = self::UPLOAD_BASE_DIR . '/' . $resultado['ruta_documento']; if (!file_exists($filePath)) { throw new RuntimeException("Archivo fsico no encontrado"); } // Configurar encabezados para la descarga header('Content-Type: application/octet-stream'); header('Content-Disposition: attached; filename="' . basename($result['ruta_documento']) . '"'); header('Content-Length: ' . filesize($filePath)); header('Cache-Control: must-revalidate'); header('Pragma: public'); // Leer y enviar el archivo readfile($filePath); exit; } catch (Exception $e) { error_log("Error en la descarga: " . $e->getMessage()); header("HTTP/1.1 404 Not Found"); echo "Error al descargar el archivo"; exit; } } // Modificar el constructor para manejar las descargas public function __construct() { try { $this->db = Database::getInstance()- >getConnection(); $this->accessControl = new AccessControl(); $this->accessControl->requireAccess(5); // Manejar descargas si se solicita $this->handleDownload(); (Excepcin $e) { $this->error = "Error de inicializacin: " . $e->getMessage(); error_log("Error de inicializacin MovimientosProveedores: " . $e->getMessage() } } funcin privada sanitizeInput(matriz $datos): matriz { $sanitizado = []; foreach ($datos como $clave => $valor) { if (is_string($valor)) { $desinfectado[$clave] = htmlspecialchars(trim($valor), ENT_QUOTES, 'UTF-8'); } de lo contrario { $sanitized[$clave] = $valor; } } devuelve $sanitized; } funcin privada validarArchivoUpload(matriz $archivo): cadena { cambiar ($file['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: throw new RuntimeException('No se seleccion ningn archivo.'); case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new RuntimeException('El archivo excede el tamao permitido. '); predeterminado: throw new RuntimeException('Error desconocido en la carga.'); } if ($file['size'] > self::MAX_FILE_SIZE) { throw new RuntimeException('El archivo excede el tamao mximo permitido (10MB) )'); } $fileExtension = strtolower(pathinfo($file['nombre'], PATHINFO_EXTENSION)); if (!in_array($fileExtension, $this->allowedFileTypes)) { throw new RuntimeException('Tipo de archivo no permitido. Solo se permite: ' . implode(', ', $this->allowedFileTypes)); } return $extensindearchivo; } funcin pblica getFilters(): matriz { $filtros = []; $valoresfiltro = []; $validFilters = [ 'id_proveedor' => '=', 'fecha_desde' => '>=', 'fecha_hasta' => '<=', 'tipo_movimiento' => '=', 'estado_pago' => '=' ]; foreach ($validFilters como $campo => $operador) { if (isset($_GET[$campo]) && !empty($_GET[$campo])) { $filtros[] = "$campo $operador ?"; $filterValues[] = $_GET[$campo]; } } return ['condiciones' => $filtros,'valores' => $filterValues]; } funcin pblica processFormSubmission(): ?string { if ($_SERVER['REQUEST_METHOD'] !== 'POST') { return null; } try { if ($this->error) { throw new RuntimeException($this->error); } $this->db->beginTransaction(); // Manejar la accin de eliminar mediante POST if (isset($_POST['delete_id'])) { $this->handleDelete((int)$_POST['delete_id']); $this->db->commit(); return null; } // Manejar creacin/actualizacin if (isset($_POST['id_movimiento']) && !empty($_POST['id_movimiento'])) { $this->handleCreateUpdate('update'); } else { $this->handleCreateUpdate('crear'); } $this->db->commit(); devolver nulo; } catch (Excepcin $e) { $this->db->rollBack(); error_log("Error en el procesamiento de formulario: " . $e->getMessage()); return $e->getMessage(); } } funcin privada handleCreateUpdate(string $action): void { // Validar campos obligatorios primero $requiredFields = ['id_proveedor', 'fecha_movimiento', 'tipo_movimiento', 'importe']; foreach ($requiredFields as $field) { if (empty($_POST[$field])) { throw new RuntimeException("El campo $field es obligatorio"); } } $data = $this->sanitizeInput([ 'id_proveedor' => $_POST['id_proveedor'], 'id_empleado' => $_POST['id_empleado'] ?? null, 'id_centro_trabajo' => $_POST['id_centro_trabajo'] ?? null, 'fecha_movimiento' => $_POST['fecha_movimiento'], 'tipo_movimiento' => $_POST['tipo_movimiento'], 'numero_documento' => $_POST['numero_documento'], 'concepto' => $_POST['concepto'], 'importe' => floatval($_POST['importe']), 'estado_pago' => $_POST['estado_pago'], 'metodo_pago' => $_POST['metodo_pago'], 'referencia_pago' => $_POST['referencia_pago'] ?? '', 'ruta_documento' => '', 'notas' => $_POST['notas'] ?? '' ]); // Manejar la carga del archivo if (isset($_FILES['documento']) && $_FILES['documento']['error'] !== UPLOAD_ERR_NO_FILE) { try { $fileExtension = $this->validateFileUpload($_FILES['documento']); // Crear estructura de directorio en base a fecha $date = new DateTime($_POST['fecha_movimiento']); $monthYear = $date->format('Ym'); // Formato: AAAA-MM $uploadDir = self::UPLOAD_BASE_DIR . '/' . $monthYear; // Crear directorios si no existen if (!file_exists(self::UPLOAD_BASE_DIR)) { mkdir(self::UPLOAD_BASE_DIR, 0755, true); } if (!file_exists($uploadDir)) { mkdir($uploadDir, 0755, true); } $fileName = $monthYear . '/' . uniqid() . '.' . $fileExtension; $filePath = self::UPLOAD_BASE_DIR . '/' . $fileName; if (!move_uploaded_file($_FILES['documento']['tmp_name'], $filePath)) { throw new RuntimeException("Error al mover el archivo subido"); } $data['ruta_documento'] = $fileName; } catch (Exception $e) { throw new RuntimeException("Error al subir el archivo: " . $e->getMessage()); } } if ($action === 'update') { if (!isset($_POST['id_movimiento']) || !is_numeric($_POST['id_movimiento'])) { throw new RuntimeException("ID de movimiento no vlido"); } $this->updateMovimiento((int)$_POST['id_movimiento'], $data); } else { $this->createMovimiento($data); } } private function createMovimiento(array $data): void { $columns = implode(', ', array_keys($data)); $placeholders = str_repeat('?,', count($data) - 1) . '?'; $sql = "INSERT INTO movimientos_proveedores ($columns) VALUES ($placeholders)"; $stmt = $this->db->prepare($sql); if (!$stmt->execute(array_values($data))) { throw new RuntimeException("Error al crear el movimiento: " . implode(", ", $stmt->errorInfo())); } } private function updateMovimiento(int $id, array $data): void { $sets = implode(' = ?, ', array_keys($data)) . ' = ?'; $sql = "UPDATE movimientos_proveedores SET $sets WHERE id_movimiento = ?"; $values = array_values($data); $values[] = $id; $stmt = $this->db->prepare($sql); if (!$stmt->execute($values)) { throw new RuntimeException("Error al actualizar el movimiento: " . implode(", ",$stmt->errorInfo())); } } funcin privada handleDelete(int $id): void { // Primero obtenemos la ruta del documento si existe $stmt = $this->db->prepare("SELECT ruta_documento FROM movimientos_proveedores WHERE id_movimiento = ?"); if (!$stmt->execute([$id])) { throw new RuntimeException("Error al obtener informacin del movimiento"); } $movimiento = $stmt->fetch(PDO::FETCH_ASSOC); // Elimina el registro $stmt = $this->db->prepare("BORRAR DE movimientos_proveedores WHERE id_movimiento = ?"); if (!$stmt->execute([$id])) { throw new RuntimeException("Error al eliminar el movimiento"); } // Si haba un documento asociado, eliminarlo del almacenamiento local if (!empty($movimiento['ruta_documento'])) { try { $filePath = self::UPLOAD_BASE_DIR . '/' . $movimiento['ruta_documento' ]; if (file_exists($filePath)) { unlink($filePath); // Intenta eliminar el directorio vaco $dirPath = dirname($filePath); if (is_dir($dirPath) && count(scandir($dirPath)) = = 2) { // Solo quedan . y .. rmdir($dirPath); } } } catch (Exception $e) { // Registra el error pero no detiene el proceso error_log("Error al eliminar archivo local: " . $e->obtenerMensaje()); } } } funcin pblica getEditItem(): ?array { if (!isset($_GET['editar']) || !is_numeric($_GET['editar'])) { return null; } $stmt = $this- >db->prepare("SELECT * FROM movimientos_proveedores WHERE id_movimiento = ?"); if (!$stmt->execute([$_GET['edit']])) { error_log("Error al obtener el elemento para editar: " . implode(", ", $stmt->errorInfo())); return null; } return $stmt->fetch(PDO::FETCH_ASSOC); } funcin pblica obtenerMovimientos(): array { try { if ($this- >error) { lanzar nueva RuntimeException($this->error); } $filtros = $this->getFilters(); $sql = "SELECT m.*, p.nombre as nombre_proveedor FROM movimientos_proveedores m LEFT JOIN proveedores p ON m.id_proveedor = p.id_proveedor"; if (!empty($filters['conditions'])) { $sql .= " WHERE " . implode('AND', $filtros['condiciones']); } $sql .= " ORDER BY fecha_movimiento DESC"; $stmt = $this->db->prepare($sql); if (!$stmt->execute($filters['values'])) { throw new RuntimeException("Error al obtener movimientos: " . implode(", ", $stmt->errorInfo())); } return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { error_log("Error al obtener movimientos: " . $e->getMessage()); return []; } } public function getProveedores(): array { try { if ($this->error) { throw new RuntimeException($this->error); } $stmt = $this->db->query("SELECT id_proveedor, nombre_empresa FROM proveedores ORDER BY nombre_empresa"); if (!$stmt) { throw new RuntimeException("Error al obtener proveedores: " . implode(", ", $this->db->errorInfo())); } return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { error_log("Error al obtener proveedores: " . $e->getMessage()); devolver []; } } } // Inicializacin y uso $errorMessage = null; $mensaje de xito = nulo; try { $movimientosHandler = new MovimientosProveedores(); // Si hay un error de inicializacin, mostrarlo if ($movimientosHandler->error) { throw new RuntimeException($movimientosHandler->error); } // Procesar el formulario si se envi if ($_SERVER['REQUEST_METHOD'] === 'POST') { $error = $movimientosHandler->processFormSubmission(); if ($error) { $mensajeerror = $error; } else { $successMessage = "Operacin realizada con xito"; // Redirigir solo si no hay errores header('Location: ' . $_SERVER['PHP_SELF'] . '?success=true'); salida; } } // Obtener datos para la vista $editItem = $movimientosHandler->getEditItem(); $movimientos = $movimientosHandler->getMovimientos(); $proveedores = $movimientosHandler->getProveedores(); $centros = $movimientosHandler->getCentrosTrabajo(); // Agrega esta lnea } catch (Exception $e) { error_log("Error crtico: " . $e->getMessage()); $errorMessage = "Error: ". $e->getMessage(); } // Mostrar mensajes de error o xito si existen if ($errorMessage) { echo '<div class="alert alert-danger">' . htmlspecialchars($errorMessage). '</div>'; } if ($successMessage || isset($_GET['success'])) { echo '<div class="alert alert-success">Operacin realizada con xito</div>'; } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Gestin de movimientos de proveedores</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"> </head> <body> <div class="container-fluid mt-4"> <div class="row"> <div class="col"> <div class="d-flex justify-content-between align-items-center mb-4"> <h2>Movimientos de proveedores</h2> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#movimientoModal"> <i class="fas fa-plus"></i> Nuevo Movimiento </button> </div> <!-- Filtros --> <div class="card mb-4"> <div class="card-body"> <form method="GET" class="row g-3"> <div class="col-md-3"> <label class="form-label">Proveedor</label> <select name="id_proveedor" class="form-select"> <option value="">Todos</option> <?php foreach ($proveedores como $proveedor): ?> <option value="<?= $proveedor['id_proveedor'] ?>" <?= isset($_GET['id_proveedor']) && $_GET['id_proveedor'] == $proveedor['id_proveedor'] ? 'selected' :'' ?>> <?= htmlspecialchars($proveedor['nombre_empresa']) ?> </option> <?php endforeach; ?> </select> </div> <div class="col-md-2"> <label class="form-label">Fecha desde</label> <input type="date" name="fecha_desde" clase="form-control" valor="<?= $_GET['fecha_desde'] ?? '' ?>"> </div> <div clase="col-md-2"> <label clase="formulario -label">Fecha hasta</label> <input type="date" name="fecha_hasta" class="form-control" value="<?= $_GET['fecha_hasta'] ?? '' ?>"> </div> <div class="col-md-2"> <label class="form-label">Tipo</label> <select name="tipo_movimiento" class="form-select"> <option value= "">Todos</option> <option value="Factura" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Factura' ? 'seleccionado' : '' ?>>Factura</option> <opcin valor="Pago" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Pago' ? 'seleccionado' : '' ?>>Pago</option> <opcin valor="Abono" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Abono' ? 'seleccionado' : '' ?>>Abono</option> <option value="Otro" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Otro' ? 'seleccionado':'' ?>>Otro</option> </select> </div> <div class="col-md-2"> <label class="form-label">Estado</label> <select name=" estado_pago" class="form-select"> <option value="">Todos</option> <option value="Pendiente" <?= isset($_GET['estado_pago']) && $_GET['estado_pago'] == 'Pendiente' ? 'seleccionado' : '' ?>>Pendiente</option> <opcin valor="Pagado" <?= isset($_GET['estado_pago']) && $_GET['estado_pago'] == 'Pagado' ? 'selected' : '' ?>>Pagado</option> <option value="Cancelado" <?= isset($_GET['estado_pago']) && $_GET['estado_pago'] == 'Cancelado' ? 'selected ' : '' ?>>Cancelado</option> </select> </div> <div class="col-md-1 d-flex align-items-end"> <button type="submit" class=" btn btn-primary">Filtrar</button> </div> </form> </div> </div> <?php if (isset($_GET['xito'])):?> <div class="alert alert-success alert-dismissible fade show" role="alert">Operacin realizada con xito <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php endif; ?> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead class="table-dark"> <tr> <th>ID</th> <th>Proveedor</th> <th>Empleado</th> <th>Centro</th> <th>Fecha</th> <th>Tipo</th> <th>Documento</th> <th>Concepto</th> <th>Importar</th> <th>Estado</th> <th>Mtodo Pago</th> <th>Documento</th> <th>Acciones</th> </tr> </thead> <tbody> <?php foreach ($movimientos as $mov): ?> <tr> <td><?= htmlspecialchars($mov['id_movimiento']) ?></td> <td><?= htmlspecialchars($mov['nombre_proveedor']) ?></td> <td><?= htmlspecialchars($mov['id_empleado']) ?></td> <td><?= htmlspecialchars($mov['id_centro_trabajo']) ?></td> <td><?= htmlspecialchars($mov['fecha_movimiento']) ?></td> <td><?= htmlspecialchars($mov['tipo_movimiento']) ?></td> <td><?= htmlspecialchars($mov['numero_documento']) ?></td> <td><?= htmlspecialchars($mov['concepto']) ?></td> <td><?= number_format($mov['importe'],2) ?> </td> <td><?= htmlspecialchars($mov['estado_pago']) ?></td> <td><?= htmlspecialchars($mov['metodo_pago']) ?>< /td> <td> <?php if (!empty($mov['ruta_documento'])): ?> <a href="?download=<?= urlencode($mov['ruta_documento']) ?>" class="btn btn-sm btn-info"> <i class="fas fa-download"></i> </a> <?php endif; ?> </td> <td> <div clase="btn-group" rol="grupo"> <button tipo="botn" clase="btn btn-sm btn-primary" datos-bs-toggle="modal " data-bs-target="#movimientoModal" onclick="editarMovimiento(<?= htmlspecialchars(json_encode($mov)) ?>)"> <i class="fas fa-edit"></i> </button > <button type="button" class="btn btn-sm btn-danger" onclick="eliminarMovimiento(<?= $mov['id_movimiento'] ?>)"> <i class="fas fa-trash"> </i> </botn> </div> </td> </tr> <?php endforeach; ?> </tbody> </tabla> </div> </div> </div> </div > <!-- Modal para Nuevo/Editar Movimiento --> <div class="modal fade" id="movimientoModal" tabindex="-1" aria-labelledby="movimientoModalLabel" aria-hidden="true"> <div class=" modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="movimientoModalLabel">Nuevo Movimiento</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal -body"> <form id="movimientoForm" action="" mtodo="POST" enctype="multipart/form-data"> <input type="hidden" name="id_movimiento" id="id_movimiento"> <div clase = "fila g-3"> <div class="col-md-6"> <etiqueta class="form-label">Proveedor</label> <select name="id_proveedor" id="id_proveedor" class="form-select" require> <option value="">Seleccione un proveedor</option> <? php foreach ($proveedores como $proveedor):?> <option value="<?= $proveedor['id_proveedor'] ?>"> <?= htmlspecialchars($proveedor['nombre_empresa']) ?> </option> <?php endforeach; ?> </select> </div> <div class="col-md-6"> <label class="form-label">Fecha</label> <input type="date" name="fecha_movimiento" id ="fecha_movimiento" class="form-control" required> </div> <div class="col-md-6"> <label class="form-label">Tipo de movimiento</label> <select name= "tipo_movimiento" id="tipo_movimiento" class="form-select" required> <option value="Factura">Factura</option> <option value="Pago">Pago</option> <option value="Abono" >Abono</option> <option value="Otro">Otro</option> </select> </div> <div class="col-md-6"> <label class="form-label">Nmero de Documento</label> <input type="text" name="numero_documento" id="numero_documento" class="form-control"> </div> <div class="col-md-6"> <label class="form-label">Centro de Trabajo</label> <select name= "id_centro_trabajo" id="id_centro_trabajo" class="form-select" required> <option value="">Seleccione un centro</option> <?php foreach ($centros as $centro): ?> <option value=" <?= $centro['id'] ?>"> <?= htmlspecialchars($centro['nombre']) ?> </option> <?php endforeach; ?> </select> </div> <div clase="col-md-6"> <label clase="form-label">Importar</label> <input tipo="nmero" nombre="importar" id="importar" clase="form-control" paso ="0.01" requerido> </div> <div class="col-12"> <label class="form-label">Concepto</label> <textarea name="concepto" id="concepto" class="form-control" rows="3"></textarea> </div> <div class="col-md-6"> <label class="form-label">Estado de pago</label> <select name="estado_pago" id="estado_pago" class="form-select" requerido> <option value="Pendiente">Pendiente</option> <option value="Pagado">Pagado</option> <option value="Cancelado">Cancelado</option> </select> </div> <div class="col-md-6"> <label class="form-label">Mtodo de pago</label> <select name="metodo_pago" id="metodo_pago" class="form-select" requerido> <option value="Transferencia">Transferencia</option> <option value="Efectivo">Efectivo</option> <option value="Tarjeta">Tarjeta</option> <option value="Otro">Otro</option> </select> </div> <div class="col-12"> <label class="form-label">Documento</label> <input type="file" name="documento" id="documento" class="form-control"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button> <button type="button" class="btn btn-primary" onclick="guardarMovimiento()">Guardar</button> </div> </div> </div> </div> <!-- Scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script> <script> function editarMovimiento(movimiento) { document.getElementById('movimientoModalLabel').textContent = 'Editar Movimiento'; document.getElementById('id_movimiento').value = movimiento.id_movimiento; document.getElementById ('id_proveedor').value = movimiento.id_proveedor; document.getElementById('fecha_movimiento').value = movimiento.fecha_movimiento; document.getElementById('tipo_movimiento').value = movimiento.tipo_movimiento; document.getElementById('numero_documento').value = movimiento.numero_documento; id_centro_trabajo').valor = movimiento.id_centro_trabajo || document.getElementById('importe').value = movimiento.importe; document.getElementById('concepto').value = movimiento.concepto; document.getElementById('estado_pago').value = movimiento.estado_pago; document.getElementById('metodo_pago').value = movimiento.metodo_pago; } function guardarMovimiento() { if (validarFormulario()) { document.getElementById('movimientoForm').submit(); } } function validarFormulario() { const form = document.getElementById('movimientoForm'); if (!form.checkValidity()) { formulario.reportValidity(); devolver falso; } devuelve verdadero; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); formulario.mtodo = 'POST'; form.innerHTML = `<tipo de entrada="hidden" nombre="delete_id" valor="${id}">`; documento.body.appendChild(formulario); formulario.enviar(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data -bs-lo que sea')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>fecha_movimiento; document.getElementById('tipo_movimiento').value = movimiento.tipo_movimiento; document.getElementById('numero_documento').value = movimiento.numero_documento; document.getElementById('id_centro_trabajo').value = movimiento.id_centro_trabajo || ''; document.getElementById('importe').value = movimiento.importe; document.getElementById('concepto').value = movimiento.concepto; document.getElementById('estado_pago').value = movimiento.estado_pago; document.getElementById('metodo_pago').value = movimiento.metodo_pago; } function guardarMovimiento() { if (validarFormulario()) { document.getElementById('movimientoForm').submit(); } } function validarFormulario() { const form = document.getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" nombre="delete_id" valor="${id}">`; documento.body.appendChild(formulario); formulario.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data -bs-lo que sea')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>fecha_movimiento; document.getElementById('tipo_movimiento').value = movimiento.tipo_movimiento; document.getElementById('numero_documento').value = movimiento.numero_documento; document.getElementById('id_centro_trabajo').value = movimiento.id_centro_trabajo || ''; document.getElementById('importe').value = movimiento.importe; document.getElementById('concepto').value = movimiento.concepto; document.getElementById('estado_pago').value = movimiento.estado_pago; document.getElementById('metodo_pago').value = movimiento.metodo_pago; } function guardarMovimiento() { if (validarFormulario()) { document.getElementById('movimientoForm').submit(); } } function validarFormulario() { const form = document.getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" nombre="delete_id" valor="${id}">`; documento.body.appendChild(formulario); formulario.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data -bs-lo que sea')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" name="delete_id" value="${id}">`; document.body.appendChild(form); form.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data-bs-whatever')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" name="delete_id" value="${id}">`; document.body.appendChild(form); form.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data-bs-whatever')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>
Did this file decode correctly?
Original Code
<?php declare(strict_types=1); require_once 'config.php'; require_once 'access-control.php'; clase MovimientosProveedores { private PDO $db; private AccessControl $accessControl; private array $allowedFileTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'bmp', 'gif', 'png']; private const MAX_FILE_SIZE = 10485760; // 10MB private const UPLOAD_BASE_DIR = 'uploads/movimientos'; // Directorio base para las subidas public $error = null; public function getCentrosTrabajo(): array { try { if ($this->error) { throw new RuntimeException($this->error); } $stmt = $this->db->query("SELECT id, nombre FROM centros_trabajo WHERE id > 0 ORDER BY nombre"); if (!$stmt) { throw new RuntimeException("Error al obtener centros de trabajo: " . implode(", ", $this->db->errorInfo())); } return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { error_log("Error al obtener centros de trabajo: " . $e->getMessage()); return []; } } public function handleDownload(): void { if (!isset($_GET['download']) || empty($_GET['download'])) { return; } try { // Verificar que el archivo existe en la base de datos $stmt = $this->db->prepare("SELECT ruta_documento FROM movimientos_proveedores WHERE ruta_documento = ?"); if (!$stmt->execute([$_GET['download']])) { throw new RuntimeException("Error al verificar el archivo"); } $resultado = $stmt->fetch(PDO::FETCH_ASSOC); if (!$resultado) { throw new RuntimeException("Archivo no encontrado"); } $filePath = self::UPLOAD_BASE_DIR . '/' . $resultado['ruta_documento']; if (!file_exists($filePath)) { throw new RuntimeException("Archivo fsico no encontrado"); } // Configurar encabezados para la descarga header('Content-Type: application/octet-stream'); header('Content-Disposition: attached; filename="' . basename($result['ruta_documento']) . '"'); header('Content-Length: ' . filesize($filePath)); header('Cache-Control: must-revalidate'); header('Pragma: public'); // Leer y enviar el archivo readfile($filePath); exit; } catch (Exception $e) { error_log("Error en la descarga: " . $e->getMessage()); header("HTTP/1.1 404 Not Found"); echo "Error al descargar el archivo"; exit; } } // Modificar el constructor para manejar las descargas public function __construct() { try { $this->db = Database::getInstance()- >getConnection(); $this->accessControl = new AccessControl(); $this->accessControl->requireAccess(5); // Manejar descargas si se solicita $this->handleDownload(); (Excepcin $e) { $this->error = "Error de inicializacin: " . $e->getMessage(); error_log("Error de inicializacin MovimientosProveedores: " . $e->getMessage() } } funcin privada sanitizeInput(matriz $datos): matriz { $sanitizado = []; foreach ($datos como $clave => $valor) { if (is_string($valor)) { $desinfectado[$clave] = htmlspecialchars(trim($valor), ENT_QUOTES, 'UTF-8'); } de lo contrario { $sanitized[$clave] = $valor; } } devuelve $sanitized; } funcin privada validarArchivoUpload(matriz $archivo): cadena { cambiar ($file['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: throw new RuntimeException('No se seleccion ningn archivo.'); case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new RuntimeException('El archivo excede el tamao permitido. '); predeterminado: throw new RuntimeException('Error desconocido en la carga.'); } if ($file['size'] > self::MAX_FILE_SIZE) { throw new RuntimeException('El archivo excede el tamao mximo permitido (10MB) )'); } $fileExtension = strtolower(pathinfo($file['nombre'], PATHINFO_EXTENSION)); if (!in_array($fileExtension, $this->allowedFileTypes)) { throw new RuntimeException('Tipo de archivo no permitido. Solo se permite: ' . implode(', ', $this->allowedFileTypes)); } return $extensindearchivo; } funcin pblica getFilters(): matriz { $filtros = []; $valoresfiltro = []; $validFilters = [ 'id_proveedor' => '=', 'fecha_desde' => '>=', 'fecha_hasta' => '<=', 'tipo_movimiento' => '=', 'estado_pago' => '=' ]; foreach ($validFilters como $campo => $operador) { if (isset($_GET[$campo]) && !empty($_GET[$campo])) { $filtros[] = "$campo $operador ?"; $filterValues[] = $_GET[$campo]; } } return ['condiciones' => $filtros,'valores' => $filterValues]; } funcin pblica processFormSubmission(): ?string { if ($_SERVER['REQUEST_METHOD'] !== 'POST') { return null; } try { if ($this->error) { throw new RuntimeException($this->error); } $this->db->beginTransaction(); // Manejar la accin de eliminar mediante POST if (isset($_POST['delete_id'])) { $this->handleDelete((int)$_POST['delete_id']); $this->db->commit(); return null; } // Manejar creacin/actualizacin if (isset($_POST['id_movimiento']) && !empty($_POST['id_movimiento'])) { $this->handleCreateUpdate('update'); } else { $this->handleCreateUpdate('crear'); } $this->db->commit(); devolver nulo; } catch (Excepcin $e) { $this->db->rollBack(); error_log("Error en el procesamiento de formulario: " . $e->getMessage()); return $e->getMessage(); } } funcin privada handleCreateUpdate(string $action): void { // Validar campos obligatorios primero $requiredFields = ['id_proveedor', 'fecha_movimiento', 'tipo_movimiento', 'importe']; foreach ($requiredFields as $field) { if (empty($_POST[$field])) { throw new RuntimeException("El campo $field es obligatorio"); } } $data = $this->sanitizeInput([ 'id_proveedor' => $_POST['id_proveedor'], 'id_empleado' => $_POST['id_empleado'] ?? null, 'id_centro_trabajo' => $_POST['id_centro_trabajo'] ?? null, 'fecha_movimiento' => $_POST['fecha_movimiento'], 'tipo_movimiento' => $_POST['tipo_movimiento'], 'numero_documento' => $_POST['numero_documento'], 'concepto' => $_POST['concepto'], 'importe' => floatval($_POST['importe']), 'estado_pago' => $_POST['estado_pago'], 'metodo_pago' => $_POST['metodo_pago'], 'referencia_pago' => $_POST['referencia_pago'] ?? '', 'ruta_documento' => '', 'notas' => $_POST['notas'] ?? '' ]); // Manejar la carga del archivo if (isset($_FILES['documento']) && $_FILES['documento']['error'] !== UPLOAD_ERR_NO_FILE) { try { $fileExtension = $this->validateFileUpload($_FILES['documento']); // Crear estructura de directorio en base a fecha $date = new DateTime($_POST['fecha_movimiento']); $monthYear = $date->format('Ym'); // Formato: AAAA-MM $uploadDir = self::UPLOAD_BASE_DIR . '/' . $monthYear; // Crear directorios si no existen if (!file_exists(self::UPLOAD_BASE_DIR)) { mkdir(self::UPLOAD_BASE_DIR, 0755, true); } if (!file_exists($uploadDir)) { mkdir($uploadDir, 0755, true); } $fileName = $monthYear . '/' . uniqid() . '.' . $fileExtension; $filePath = self::UPLOAD_BASE_DIR . '/' . $fileName; if (!move_uploaded_file($_FILES['documento']['tmp_name'], $filePath)) { throw new RuntimeException("Error al mover el archivo subido"); } $data['ruta_documento'] = $fileName; } catch (Exception $e) { throw new RuntimeException("Error al subir el archivo: " . $e->getMessage()); } } if ($action === 'update') { if (!isset($_POST['id_movimiento']) || !is_numeric($_POST['id_movimiento'])) { throw new RuntimeException("ID de movimiento no vlido"); } $this->updateMovimiento((int)$_POST['id_movimiento'], $data); } else { $this->createMovimiento($data); } } private function createMovimiento(array $data): void { $columns = implode(', ', array_keys($data)); $placeholders = str_repeat('?,', count($data) - 1) . '?'; $sql = "INSERT INTO movimientos_proveedores ($columns) VALUES ($placeholders)"; $stmt = $this->db->prepare($sql); if (!$stmt->execute(array_values($data))) { throw new RuntimeException("Error al crear el movimiento: " . implode(", ", $stmt->errorInfo())); } } private function updateMovimiento(int $id, array $data): void { $sets = implode(' = ?, ', array_keys($data)) . ' = ?'; $sql = "UPDATE movimientos_proveedores SET $sets WHERE id_movimiento = ?"; $values = array_values($data); $values[] = $id; $stmt = $this->db->prepare($sql); if (!$stmt->execute($values)) { throw new RuntimeException("Error al actualizar el movimiento: " . implode(", ",$stmt->errorInfo())); } } funcin privada handleDelete(int $id): void { // Primero obtenemos la ruta del documento si existe $stmt = $this->db->prepare("SELECT ruta_documento FROM movimientos_proveedores WHERE id_movimiento = ?"); if (!$stmt->execute([$id])) { throw new RuntimeException("Error al obtener informacin del movimiento"); } $movimiento = $stmt->fetch(PDO::FETCH_ASSOC); // Elimina el registro $stmt = $this->db->prepare("BORRAR DE movimientos_proveedores WHERE id_movimiento = ?"); if (!$stmt->execute([$id])) { throw new RuntimeException("Error al eliminar el movimiento"); } // Si haba un documento asociado, eliminarlo del almacenamiento local if (!empty($movimiento['ruta_documento'])) { try { $filePath = self::UPLOAD_BASE_DIR . '/' . $movimiento['ruta_documento' ]; if (file_exists($filePath)) { unlink($filePath); // Intenta eliminar el directorio vaco $dirPath = dirname($filePath); if (is_dir($dirPath) && count(scandir($dirPath)) = = 2) { // Solo quedan . y .. rmdir($dirPath); } } } catch (Exception $e) { // Registra el error pero no detiene el proceso error_log("Error al eliminar archivo local: " . $e->obtenerMensaje()); } } } funcin pblica getEditItem(): ?array { if (!isset($_GET['editar']) || !is_numeric($_GET['editar'])) { return null; } $stmt = $this- >db->prepare("SELECT * FROM movimientos_proveedores WHERE id_movimiento = ?"); if (!$stmt->execute([$_GET['edit']])) { error_log("Error al obtener el elemento para editar: " . implode(", ", $stmt->errorInfo())); return null; } return $stmt->fetch(PDO::FETCH_ASSOC); } funcin pblica obtenerMovimientos(): array { try { if ($this- >error) { lanzar nueva RuntimeException($this->error); } $filtros = $this->getFilters(); $sql = "SELECT m.*, p.nombre as nombre_proveedor FROM movimientos_proveedores m LEFT JOIN proveedores p ON m.id_proveedor = p.id_proveedor"; if (!empty($filters['conditions'])) { $sql .= " WHERE " . implode('AND', $filtros['condiciones']); } $sql .= " ORDER BY fecha_movimiento DESC"; $stmt = $this->db->prepare($sql); if (!$stmt->execute($filters['values'])) { throw new RuntimeException("Error al obtener movimientos: " . implode(", ", $stmt->errorInfo())); } return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { error_log("Error al obtener movimientos: " . $e->getMessage()); return []; } } public function getProveedores(): array { try { if ($this->error) { throw new RuntimeException($this->error); } $stmt = $this->db->query("SELECT id_proveedor, nombre_empresa FROM proveedores ORDER BY nombre_empresa"); if (!$stmt) { throw new RuntimeException("Error al obtener proveedores: " . implode(", ", $this->db->errorInfo())); } return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { error_log("Error al obtener proveedores: " . $e->getMessage()); devolver []; } } } // Inicializacin y uso $errorMessage = null; $mensaje de xito = nulo; try { $movimientosHandler = new MovimientosProveedores(); // Si hay un error de inicializacin, mostrarlo if ($movimientosHandler->error) { throw new RuntimeException($movimientosHandler->error); } // Procesar el formulario si se envi if ($_SERVER['REQUEST_METHOD'] === 'POST') { $error = $movimientosHandler->processFormSubmission(); if ($error) { $mensajeerror = $error; } else { $successMessage = "Operacin realizada con xito"; // Redirigir solo si no hay errores header('Location: ' . $_SERVER['PHP_SELF'] . '?success=true'); salida; } } // Obtener datos para la vista $editItem = $movimientosHandler->getEditItem(); $movimientos = $movimientosHandler->getMovimientos(); $proveedores = $movimientosHandler->getProveedores(); $centros = $movimientosHandler->getCentrosTrabajo(); // Agrega esta lnea } catch (Exception $e) { error_log("Error crtico: " . $e->getMessage()); $errorMessage = "Error: ". $e->getMessage(); } // Mostrar mensajes de error o xito si existen if ($errorMessage) { echo '<div class="alert alert-danger">' . htmlspecialchars($errorMessage). '</div>'; } if ($successMessage || isset($_GET['success'])) { echo '<div class="alert alert-success">Operacin realizada con xito</div>'; } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Gestin de movimientos de proveedores</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"> </head> <body> <div class="container-fluid mt-4"> <div class="row"> <div class="col"> <div class="d-flex justify-content-between align-items-center mb-4"> <h2>Movimientos de proveedores</h2> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#movimientoModal"> <i class="fas fa-plus"></i> Nuevo Movimiento </button> </div> <!-- Filtros --> <div class="card mb-4"> <div class="card-body"> <form method="GET" class="row g-3"> <div class="col-md-3"> <label class="form-label">Proveedor</label> <select name="id_proveedor" class="form-select"> <option value="">Todos</option> <?php foreach ($proveedores como $proveedor): ?> <option value="<?= $proveedor['id_proveedor'] ?>" <?= isset($_GET['id_proveedor']) && $_GET['id_proveedor'] == $proveedor['id_proveedor'] ? 'selected' :'' ?>> <?= htmlspecialchars($proveedor['nombre_empresa']) ?> </option> <?php endforeach; ?> </select> </div> <div class="col-md-2"> <label class="form-label">Fecha desde</label> <input type="date" name="fecha_desde" clase="form-control" valor="<?= $_GET['fecha_desde'] ?? '' ?>"> </div> <div clase="col-md-2"> <label clase="formulario -label">Fecha hasta</label> <input type="date" name="fecha_hasta" class="form-control" value="<?= $_GET['fecha_hasta'] ?? '' ?>"> </div> <div class="col-md-2"> <label class="form-label">Tipo</label> <select name="tipo_movimiento" class="form-select"> <option value= "">Todos</option> <option value="Factura" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Factura' ? 'seleccionado' : '' ?>>Factura</option> <opcin valor="Pago" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Pago' ? 'seleccionado' : '' ?>>Pago</option> <opcin valor="Abono" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Abono' ? 'seleccionado' : '' ?>>Abono</option> <option value="Otro" <?= isset($_GET['tipo_movimiento']) && $_GET['tipo_movimiento'] == 'Otro' ? 'seleccionado':'' ?>>Otro</option> </select> </div> <div class="col-md-2"> <label class="form-label">Estado</label> <select name=" estado_pago" class="form-select"> <option value="">Todos</option> <option value="Pendiente" <?= isset($_GET['estado_pago']) && $_GET['estado_pago'] == 'Pendiente' ? 'seleccionado' : '' ?>>Pendiente</option> <opcin valor="Pagado" <?= isset($_GET['estado_pago']) && $_GET['estado_pago'] == 'Pagado' ? 'selected' : '' ?>>Pagado</option> <option value="Cancelado" <?= isset($_GET['estado_pago']) && $_GET['estado_pago'] == 'Cancelado' ? 'selected ' : '' ?>>Cancelado</option> </select> </div> <div class="col-md-1 d-flex align-items-end"> <button type="submit" class=" btn btn-primary">Filtrar</button> </div> </form> </div> </div> <?php if (isset($_GET['xito'])):?> <div class="alert alert-success alert-dismissible fade show" role="alert">Operacin realizada con xito <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php endif; ?> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead class="table-dark"> <tr> <th>ID</th> <th>Proveedor</th> <th>Empleado</th> <th>Centro</th> <th>Fecha</th> <th>Tipo</th> <th>Documento</th> <th>Concepto</th> <th>Importar</th> <th>Estado</th> <th>Mtodo Pago</th> <th>Documento</th> <th>Acciones</th> </tr> </thead> <tbody> <?php foreach ($movimientos as $mov): ?> <tr> <td><?= htmlspecialchars($mov['id_movimiento']) ?></td> <td><?= htmlspecialchars($mov['nombre_proveedor']) ?></td> <td><?= htmlspecialchars($mov['id_empleado']) ?></td> <td><?= htmlspecialchars($mov['id_centro_trabajo']) ?></td> <td><?= htmlspecialchars($mov['fecha_movimiento']) ?></td> <td><?= htmlspecialchars($mov['tipo_movimiento']) ?></td> <td><?= htmlspecialchars($mov['numero_documento']) ?></td> <td><?= htmlspecialchars($mov['concepto']) ?></td> <td><?= number_format($mov['importe'],2) ?> </td> <td><?= htmlspecialchars($mov['estado_pago']) ?></td> <td><?= htmlspecialchars($mov['metodo_pago']) ?>< /td> <td> <?php if (!empty($mov['ruta_documento'])): ?> <a href="?download=<?= urlencode($mov['ruta_documento']) ?>" class="btn btn-sm btn-info"> <i class="fas fa-download"></i> </a> <?php endif; ?> </td> <td> <div clase="btn-group" rol="grupo"> <button tipo="botn" clase="btn btn-sm btn-primary" datos-bs-toggle="modal " data-bs-target="#movimientoModal" onclick="editarMovimiento(<?= htmlspecialchars(json_encode($mov)) ?>)"> <i class="fas fa-edit"></i> </button > <button type="button" class="btn btn-sm btn-danger" onclick="eliminarMovimiento(<?= $mov['id_movimiento'] ?>)"> <i class="fas fa-trash"> </i> </botn> </div> </td> </tr> <?php endforeach; ?> </tbody> </tabla> </div> </div> </div> </div > <!-- Modal para Nuevo/Editar Movimiento --> <div class="modal fade" id="movimientoModal" tabindex="-1" aria-labelledby="movimientoModalLabel" aria-hidden="true"> <div class=" modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="movimientoModalLabel">Nuevo Movimiento</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal -body"> <form id="movimientoForm" action="" mtodo="POST" enctype="multipart/form-data"> <input type="hidden" name="id_movimiento" id="id_movimiento"> <div clase = "fila g-3"> <div class="col-md-6"> <etiqueta class="form-label">Proveedor</label> <select name="id_proveedor" id="id_proveedor" class="form-select" require> <option value="">Seleccione un proveedor</option> <? php foreach ($proveedores como $proveedor):?> <option value="<?= $proveedor['id_proveedor'] ?>"> <?= htmlspecialchars($proveedor['nombre_empresa']) ?> </option> <?php endforeach; ?> </select> </div> <div class="col-md-6"> <label class="form-label">Fecha</label> <input type="date" name="fecha_movimiento" id ="fecha_movimiento" class="form-control" required> </div> <div class="col-md-6"> <label class="form-label">Tipo de movimiento</label> <select name= "tipo_movimiento" id="tipo_movimiento" class="form-select" required> <option value="Factura">Factura</option> <option value="Pago">Pago</option> <option value="Abono" >Abono</option> <option value="Otro">Otro</option> </select> </div> <div class="col-md-6"> <label class="form-label">Nmero de Documento</label> <input type="text" name="numero_documento" id="numero_documento" class="form-control"> </div> <div class="col-md-6"> <label class="form-label">Centro de Trabajo</label> <select name= "id_centro_trabajo" id="id_centro_trabajo" class="form-select" required> <option value="">Seleccione un centro</option> <?php foreach ($centros as $centro): ?> <option value=" <?= $centro['id'] ?>"> <?= htmlspecialchars($centro['nombre']) ?> </option> <?php endforeach; ?> </select> </div> <div clase="col-md-6"> <label clase="form-label">Importar</label> <input tipo="nmero" nombre="importar" id="importar" clase="form-control" paso ="0.01" requerido> </div> <div class="col-12"> <label class="form-label">Concepto</label> <textarea name="concepto" id="concepto" class="form-control" rows="3"></textarea> </div> <div class="col-md-6"> <label class="form-label">Estado de pago</label> <select name="estado_pago" id="estado_pago" class="form-select" requerido> <option value="Pendiente">Pendiente</option> <option value="Pagado">Pagado</option> <option value="Cancelado">Cancelado</option> </select> </div> <div class="col-md-6"> <label class="form-label">Mtodo de pago</label> <select name="metodo_pago" id="metodo_pago" class="form-select" requerido> <option value="Transferencia">Transferencia</option> <option value="Efectivo">Efectivo</option> <option value="Tarjeta">Tarjeta</option> <option value="Otro">Otro</option> </select> </div> <div class="col-12"> <label class="form-label">Documento</label> <input type="file" name="documento" id="documento" class="form-control"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button> <button type="button" class="btn btn-primary" onclick="guardarMovimiento()">Guardar</button> </div> </div> </div> </div> <!-- Scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script> <script> function editarMovimiento(movimiento) { document.getElementById('movimientoModalLabel').textContent = 'Editar Movimiento'; document.getElementById('id_movimiento').value = movimiento.id_movimiento; document.getElementById ('id_proveedor').value = movimiento.id_proveedor; document.getElementById('fecha_movimiento').value = movimiento.fecha_movimiento; document.getElementById('tipo_movimiento').value = movimiento.tipo_movimiento; document.getElementById('numero_documento').value = movimiento.numero_documento; id_centro_trabajo').valor = movimiento.id_centro_trabajo || document.getElementById('importe').value = movimiento.importe; document.getElementById('concepto').value = movimiento.concepto; document.getElementById('estado_pago').value = movimiento.estado_pago; document.getElementById('metodo_pago').value = movimiento.metodo_pago; } function guardarMovimiento() { if (validarFormulario()) { document.getElementById('movimientoForm').submit(); } } function validarFormulario() { const form = document.getElementById('movimientoForm'); if (!form.checkValidity()) { formulario.reportValidity(); devolver falso; } devuelve verdadero; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); formulario.mtodo = 'POST'; form.innerHTML = `<tipo de entrada="hidden" nombre="delete_id" valor="${id}">`; documento.body.appendChild(formulario); formulario.enviar(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data -bs-lo que sea')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>fecha_movimiento; document.getElementById('tipo_movimiento').value = movimiento.tipo_movimiento; document.getElementById('numero_documento').value = movimiento.numero_documento; document.getElementById('id_centro_trabajo').value = movimiento.id_centro_trabajo || ''; document.getElementById('importe').value = movimiento.importe; document.getElementById('concepto').value = movimiento.concepto; document.getElementById('estado_pago').value = movimiento.estado_pago; document.getElementById('metodo_pago').value = movimiento.metodo_pago; } function guardarMovimiento() { if (validarFormulario()) { document.getElementById('movimientoForm').submit(); } } function validarFormulario() { const form = document.getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" nombre="delete_id" valor="${id}">`; documento.body.appendChild(formulario); formulario.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data -bs-lo que sea')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>fecha_movimiento; document.getElementById('tipo_movimiento').value = movimiento.tipo_movimiento; document.getElementById('numero_documento').value = movimiento.numero_documento; document.getElementById('id_centro_trabajo').value = movimiento.id_centro_trabajo || ''; document.getElementById('importe').value = movimiento.importe; document.getElementById('concepto').value = movimiento.concepto; document.getElementById('estado_pago').value = movimiento.estado_pago; document.getElementById('metodo_pago').value = movimiento.metodo_pago; } function guardarMovimiento() { if (validarFormulario()) { document.getElementById('movimientoForm').submit(); } } function validarFormulario() { const form = document.getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" nombre="delete_id" valor="${id}">`; documento.body.appendChild(formulario); formulario.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data -bs-lo que sea')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" name="delete_id" value="${id}">`; document.body.appendChild(form); form.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data-bs-whatever')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>getElementById('movimientoForm'); if (!form.checkValidity()) { form.reportValidity(); return false; } return true; } function eliminarMovimiento(id) { if (confirm('Est seguro de que desea eliminar este movimiento?')) { const form = document.createElement('form'); form.method = 'POST'; form.innerHTML = `<input type="hidden" name="delete_id" value="${id}">`; document.body.appendChild(form); form.submit(); } } // Limpiar el formulario cuando se abre el modal para nuevo movimiento document.getElementById('movimientoModal').addEventListener('show.bs.modal', function (event) { if (!event. relatedTarget.hasAttribute('data-bs-whatever')) { document.getElementById('movimientoModalLabel').textContent = 'Nuevo Movimiento'; document.getElementById('movimientoForm').reset(); document.getElementById('id_movimiento').value = ''; </script> </body> </html>
Function Calls
None |
Stats
MD5 | e1c81ce19fb80cbe926f96d0cc700326 |
Eval Count | 0 |
Decode Time | 100 ms |