Autosave: 20260212-042541

This commit is contained in:
Flatlogic Bot 2026-02-12 04:25:41 +00:00
parent 697dbbf92b
commit f88375f643
2 changed files with 181 additions and 77 deletions

View File

@ -2,30 +2,54 @@
header('Content-Type: application/json'); header('Content-Type: application/json');
require_once 'db/config.php'; require_once 'db/config.php';
$response = ['success' => false, 'message' => 'ID de producto no proporcionado.']; $response = ['success' => false, 'message' => 'No se proporcionó un identificador de producto.'];
if (isset($_GET['id'])) { $pdo = db();
$product = null;
// Handle search by SKU (barcode)
if (isset($_GET['codigo_barras'])) {
$sku = trim($_GET['codigo_barras']);
if (!empty($sku)) {
try {
// Search by the 'sku' column
$stmt = $pdo->prepare("SELECT id, nombre, sku FROM products WHERE sku = :sku");
$stmt->execute(['sku' => $sku]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) {
$response['message'] = 'Producto no encontrado con el SKU/código de barras proporcionado.';
}
} catch (PDOException $e) {
// Don't expose detailed SQL errors to the client
error_log('Database Error: ' . $e->getMessage());
$response['message'] = 'Error al consultar la base de datos.';
}
} else {
$response['message'] = 'El SKU/código de barras no puede estar vacío.';
}
// Handle search by internal ID
} elseif (isset($_GET['id'])) {
$product_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); $product_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($product_id) { if ($product_id) {
try { try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id, nombre, sku FROM products WHERE id = :id"); $stmt = $pdo->prepare("SELECT id, nombre, sku FROM products WHERE id = :id");
$stmt->execute(['id' => $product_id]); $stmt->execute(['id' => $product_id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC); $product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) {
if ($product) { $response['message'] = 'Producto no encontrado con el ID proporcionado.';
$response = ['success' => true, 'product' => $product];
} else {
$response['message'] = 'Producto no encontrado.';
} }
} catch (PDOException $e) { } catch (PDOException $e) {
$response['message'] = 'Error en la base de datos: ' . $e->getMessage(); error_log('Database Error: ' . $e->getMessage());
$response['message'] = 'Error al consultar la base de datos.';
} }
} else { } else {
$response['message'] = 'ID de producto inválido.'; $response['message'] = 'ID de producto inválido.';
} }
} }
if ($product) {
$response = ['success' => true, 'product' => $product];
}
echo json_encode($response); echo json_encode($response);
?> ?>

View File

@ -6,7 +6,7 @@ require_once 'db/config.php';
$message = ''; $message = '';
$error = ''; $error = '';
// Lógica para manejar el envío del formulario // Lógica para manejar el envío del formulario (tanto normal como AJAX)
if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT); $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT); $sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT);
@ -18,21 +18,19 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
$pdo = db(); $pdo = db();
$pdo->beginTransaction(); $pdo->beginTransaction();
// 1. Verificar y actualizar stock en stock_sedes $stmt = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id FOR UPDATE");
$stmt = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id");
$stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id]); $stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id]);
$existing_stock = $stmt->fetch(); $existing_stock = $stmt->fetch();
if ($existing_stock) { if ($existing_stock) {
$new_quantity = $existing_stock['quantity'] - $quantity; $new_quantity = $existing_stock['quantity'] - $quantity;
if ($new_quantity < 0) { if ($new_quantity < 0) {
$error = "No hay suficiente stock para registrar la salida."; $error = "No hay suficiente stock para registrar la salida. Stock actual: " . $existing_stock['quantity'];
$pdo->rollBack(); $pdo->rollBack();
} else { } else {
$update_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id"); $update_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id");
$update_stmt->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]); $update_stmt->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]);
// 2. Insertar en el historial de movimientos
$history_stmt = $pdo->prepare( $history_stmt = $pdo->prepare(
"INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date) "INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date)
VALUES (:product_id, :sede_id, :quantity, 'salida', :movement_date)" VALUES (:product_id, :sede_id, :quantity, 'salida', :movement_date)"
@ -45,7 +43,10 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
]); ]);
$pdo->commit(); $pdo->commit();
$message = "¡Inventario actualizado y movimiento registrado correctamente!"; $stmt_prod_name = $pdo->prepare("SELECT nombre FROM products WHERE id = :id");
$stmt_prod_name->execute(['id' => $product_id]);
$product_name = $stmt_prod_name->fetchColumn();
$message = "Salida de 1 unidad de '{$product_name}' registrada. Stock restante: {$new_quantity}.";
} }
} else { } else {
$error = "No hay stock registrado para este producto en la sede seleccionada."; $error = "No hay stock registrado para este producto en la sede seleccionada.";
@ -53,13 +54,24 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
} }
} catch (PDOException $e) { } catch (PDOException $e) {
if ($pdo->inTransaction()) { if ($pdo && $pdo->inTransaction()) {
$pdo->rollBack(); $pdo->rollBack();
} }
$error = "Error al actualizar el inventario: " . $e->getMessage(); $error = "Error al actualizar el inventario: " . $e->getMessage();
} }
} else { } else {
$error = "Por favor, complete todos los campos del formulario, incluyendo la fecha."; $error = "Por favor, complete todos los campos del formulario, incluyendo la fecha y la sede.";
}
// Si es una petición AJAX, devolvemos JSON y terminamos la ejecución
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
header('Content-Type: application/json');
if ($error) {
echo json_encode(['success' => false, 'message' => $error]);
} else {
echo json_encode(['success' => true, 'message' => $message]);
}
exit;
} }
} }
@ -82,12 +94,15 @@ try {
<div class="row"> <div class="row">
<div class="col-lg-6 mx-auto"> <div class="col-lg-6 mx-auto">
<?php if ($message): ?> <!-- Contenedor para notificaciones (toasts) -->
<div id="notification-container" class="position-fixed top-0 end-0 p-3" style="z-index: 1100"></div>
<?php if ($message && empty($_SERVER['HTTP_X_REQUESTED_WITH'])): ?>
<div class="alert alert-success" role="alert"> <div class="alert alert-success" role="alert">
<?php echo htmlspecialchars($message); ?> <?php echo htmlspecialchars($message); ?>
</div> </div>
<?php endif; ?> <?php endif; ?>
<?php if ($error): ?> <?php if ($error && empty($_SERVER['HTTP_X_REQUESTED_WITH'])): ?>
<div class="alert alert-danger" role="alert"> <div class="alert alert-danger" role="alert">
<?php echo htmlspecialchars($error); ?> <?php echo htmlspecialchars($error); ?>
</div> </div>
@ -98,11 +113,21 @@ try {
<i class="fa fa-minus"></i> Registro de Salida de Producto <i class="fa fa-minus"></i> Registro de Salida de Producto
</div> </div>
<div class="card-body"> <div class="card-body">
<form action="registro_salida.php" method="post"> <form id="salida-form" action="registro_salida.php" method="post">
<div class="mb-3"> <div class="mb-3">
<label for="movement_date" class="form-label">Fecha de Salida</label> <label for="movement_date" class="form-label">Fecha de Salida</label>
<input type="date" class="form-control" id="movement_date" name="movement_date" value="<?php echo date('Y-m-d'); ?>" required> <input type="date" class="form-control" id="movement_date" name="movement_date" value="<?php echo date('Y-m-d'); ?>" required>
</div> </div>
<div class="mb-3">
<label for="sede" class="form-label">Sede de Origen</label>
<select class="form-select" id="sede" name="sede_id" required>
<option value="">Seleccione una sede</option>
<?php foreach ($sedes as $sede): ?>
<option value="<?php echo htmlspecialchars($sede['id']); ?>"<?php if (trim(strtolower($sede['nombre'])) === 'almacen principal') echo ' selected'; ?>><?php echo htmlspecialchars($sede['nombre']); ?></option>
<?php endforeach; ?>
</select>
</div>
<hr>
<div class="mb-3"> <div class="mb-3">
<label for="producto" class="form-label">Producto</label> <label for="producto" class="form-label">Producto</label>
<button type="button" class="btn btn-info btn-sm float-end" data-bs-toggle="modal" data-bs-target="#scannerModal"> <button type="button" class="btn btn-info btn-sm float-end" data-bs-toggle="modal" data-bs-target="#scannerModal">
@ -111,28 +136,16 @@ try {
<select class="form-select" id="producto" name="product_id" required> <select class="form-select" id="producto" name="product_id" required>
<option value="">Seleccione un producto</option> <option value="">Seleccione un producto</option>
<?php foreach ($products as $product): ?> <?php foreach ($products as $product): ?>
<option value="<?php echo htmlspecialchars($product['id']); ?>"> <option value="<?php echo htmlspecialchars($product['id']); ?>"><?php echo htmlspecialchars($product['nombre']); ?></option>
<?php echo htmlspecialchars($product['nombre']); ?>
</option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="cantidad" class="form-label">Cantidad a Retirar</label> <label for="cantidad" class="form-label">Cantidad a Retirar (manual)</label>
<input type="number" class="form-control" id="cantidad" name="quantity" min="1" required> <input type="number" class="form-control" id="cantidad" name="quantity" min="1" required>
</div> </div>
<div class="mb-3">
<label for="sede" class="form-label">Sede de Origen</label> <button type="submit" class="btn btn-primary w-100"> <i class="fa fa-minus-circle"></i> Registrar Salida Manual</button>
<select class="form-select" id="sede" name="sede_id" required>
<option value="">Seleccione una sede</option>
<?php foreach ($sedes as $sede): ?>
<option value="<?php echo htmlspecialchars($sede['id']); ?>">
<?php echo htmlspecialchars($sede['nombre']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary w-100"> <i class="fa fa-minus-circle"></i> Registrar Salida</button>
</form> </form>
</div> </div>
</div> </div>
@ -162,75 +175,142 @@ try {
<script> <script>
document.addEventListener('DOMContentLoaded', (event) => { document.addEventListener('DOMContentLoaded', (event) => {
if (typeof bootstrap === 'undefined') { if (typeof bootstrap === 'undefined') {
console.error('Bootstrap no está cargado. El modal del escáner no funcionará.'); console.error('Bootstrap no está cargado.');
return; return;
} }
const scannerModalElement = document.getElementById('scannerModal'); let audioContext;
if (!scannerModalElement) {
console.error('El elemento del modal del escáner no se encontró.'); // --- Funciones de ayuda ---
return;
function showNotification(message, isSuccess) {
const container = document.getElementById('notification-container');
if (!container) return;
const toastId = 'toast-' + Date.now();
const toastHTML = `
<div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header ${isSuccess ? 'bg-success text-white' : 'bg-danger text-white'}">
<strong class="me-auto">${isSuccess ? 'Éxito' : 'Error'}</strong>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
${message}
</div>
</div>
`;
container.insertAdjacentHTML('beforeend', toastHTML);
const toastElement = document.getElementById(toastId);
const toast = new bootstrap.Toast(toastElement, { delay: 5000 });
toast.show();
toastElement.addEventListener('hidden.bs.toast', () => {
toastElement.remove();
});
} }
function playBeep() {
if (!audioContext) {
console.warn("AudioContext no inicializado. El sonido no se reproducirá.");
return;
}
try {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(880, audioContext.currentTime);
gainNode.gain.setValueAtTime(0.5, audioContext.currentTime);
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.1);
} catch (e) {
console.error("Error al reproducir el sonido con Web Audio API.", e);
}
}
// --- Lógica del escáner ---
const scannerModalElement = document.getElementById('scannerModal');
if (!scannerModalElement) return;
const scannerModal = new bootstrap.Modal(scannerModalElement); const scannerModal = new bootstrap.Modal(scannerModalElement);
const html5QrCode = new Html5Qrcode("reader"); const html5QrCode = new Html5Qrcode("reader");
const qrCodeSuccessCallback = (decodedText, decodedResult) => { // Inicializar AudioContext con la interacción del usuario
html5QrCode.stop().then((ignore) => { document.querySelector('[data-bs-target="#scannerModal"]').addEventListener('click', () => {
console.log("QR Code scanning stopped."); if (!audioContext) {
}).catch((err) => { try {
console.error("Failed to stop QR Code scanning.", err); audioContext = new (window.AudioContext || window.webkitAudioContext)();
}); console.log("AudioContext inicializado.");
} catch (e) {
console.error("Web Audio API no es soportada en este navegador.", e);
}
}
});
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
playBeep();
html5QrCode.stop().catch(err => {});
scannerModal.hide(); scannerModal.hide();
fetch(`get_product_details.php?id=${decodedText}`) const sede_id = document.getElementById('sede').value;
.then(response => { const movement_date = document.getElementById('movement_date').value;
if (!response.ok) {
throw new Error('Network response was not ok'); if (!sede_id) {
} showNotification("Por favor, seleccione una sede de origen antes de escanear.", false);
return response.json(); return;
}) }
const cleanDecodedText = decodedText.trim();
fetch(`get_product_details.php?id=${cleanDecodedText}`)
.then(response => response.json())
.then(data => { .then(data => {
if (data.success && data.product) { if (data.success && data.product) {
const productSelect = document.getElementById('producto'); const formData = new FormData();
productSelect.value = data.product.id; formData.append('product_id', data.product.id);
formData.append('quantity', '1');
const productName = data.product.nombre || 'desconocido'; formData.append('sede_id', sede_id);
alert(`Producto seleccionado: ${productName}`); formData.append('movement_date', movement_date);
return fetch('registro_salida.php', {
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body: formData
});
} else { } else {
alert('Error: ' + (data.message || 'Producto no encontrado.')); throw new Error(data.message || 'Producto no encontrado con el código escaneado.');
} }
}) })
.then(response => response.json())
.then(result => {
showNotification(result.message, result.success);
})
.catch(error => { .catch(error => {
console.error('Error al buscar los detalles del producto:', error); console.error('Error en el proceso de escaneo y registro:', error);
alert('Hubo un error al procesar el código de barras. Verifique la consola para más detalles.'); showNotification(error.message, false);
}); });
}; };
const config = { fps: 10, qrbox: { width: 250, height: 250 } }; const config = {
fps: 10,
qrbox: { width: 250, height: 250 },
experimentalFeatures: {
useBarCodeDetectorIfSupported: false
}
};
scannerModalElement.addEventListener('shown.bs.modal', function () { scannerModalElement.addEventListener('shown.bs.modal', function () {
html5QrCode.start( html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback, (errorMessage) => {})
{ facingMode: "environment" },
config,
qrCodeSuccessCallback,
(errorMessage) => {
// console.log("QR Code no match.", errorMessage);
})
.catch((err) => { .catch((err) => {
console.error("No se pudo iniciar el escáner de QR.", err); showNotification("Error al iniciar la cámara. Asegúrese de dar permisos.", false);
alert("Error al iniciar la cámara. Asegúrese de dar permisos.");
}); });
}); });
scannerModalElement.addEventListener('hidden.bs.modal', function () { scannerModalElement.addEventListener('hidden.bs.modal', function () {
html5QrCode.stop().catch(err => { html5QrCode.stop().catch(err => {});
// Ignorar error si el escáner ya estaba detenido
});
}); });
}); });
</script> </script>
<?php require_once 'layout_footer.php'; ?> <?php require_once 'layout_footer.php'; ?>