Autosave: 20260212-044617
This commit is contained in:
parent
f88375f643
commit
b390ef6318
1
db/migrations/061_add_sku_to_products.sql
Normal file
1
db/migrations/061_add_sku_to_products.sql
Normal file
@ -0,0 +1 @@
|
||||
ALTER TABLE products ADD COLUMN sku VARCHAR(100) NULL UNIQUE;
|
||||
@ -18,6 +18,9 @@ if (isset($_GET['codigo_barras'])) {
|
||||
$product = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$product) {
|
||||
$response['message'] = 'Producto no encontrado con el SKU/código de barras proporcionado.';
|
||||
// Log the failed SKU attempt to a file
|
||||
$log_message = date('[Y-m-d H:i:s]') . " Intento fallido de búsqueda con SKU: " . $sku . PHP_EOL;
|
||||
file_put_contents('sku_failures.log', $log_message, FILE_APPEND);
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
// Don't expose detailed SQL errors to the client
|
||||
|
||||
@ -6,14 +6,14 @@ require_once 'db/config.php';
|
||||
$message = '';
|
||||
$error = '';
|
||||
|
||||
// Lógica para manejar el envío del formulario (tanto normal como AJAX)
|
||||
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||
// Esta sección ahora solo se usará para las respuestas AJAX del escáner
|
||||
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
|
||||
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
|
||||
$sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT);
|
||||
$quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT);
|
||||
$movement_date = filter_input(INPUT_POST, 'movement_date');
|
||||
$quantity = 1; // Siempre es 1 al escanear
|
||||
|
||||
if ($product_id && $sede_id && $quantity && $movement_date) {
|
||||
if ($product_id && $sede_id && $movement_date) {
|
||||
try {
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
@ -25,7 +25,7 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||
if ($existing_stock) {
|
||||
$new_quantity = $existing_stock['quantity'] - $quantity;
|
||||
if ($new_quantity < 0) {
|
||||
$error = "No hay suficiente stock para registrar la salida. Stock actual: " . $existing_stock['quantity'];
|
||||
$error = "No hay stock para registrar la salida. Stock actual: " . $existing_stock['quantity'];
|
||||
$pdo->rollBack();
|
||||
} else {
|
||||
$update_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id");
|
||||
@ -60,33 +60,27 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||
$error = "Error al actualizar el inventario: " . $e->getMessage();
|
||||
}
|
||||
} else {
|
||||
$error = "Por favor, complete todos los campos del formulario, incluyendo la fecha y la sede.";
|
||||
$error = "Faltan datos para registrar la salida (producto, sede o fecha).";
|
||||
}
|
||||
|
||||
// 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;
|
||||
// Devolvemos JSON y terminamos la ejecución
|
||||
header('Content-Type: application/json');
|
||||
if ($error) {
|
||||
echo json_encode(['success' => false, 'message' => $error]);
|
||||
} else {
|
||||
echo json_encode(['success' => true, 'message' => $message]);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
|
||||
// Obtener productos y sedes para los dropdowns
|
||||
$products = [];
|
||||
// Obtener sedes para el dropdown
|
||||
$sedes = [];
|
||||
try {
|
||||
$pdo = db();
|
||||
$products_stmt = $pdo->query("SELECT id, nombre FROM products ORDER BY nombre ASC");
|
||||
$products = $products_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$sedes_stmt = $pdo->query("SELECT id, nombre FROM sedes ORDER BY nombre ASC");
|
||||
$sedes = $sedes_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $e) {
|
||||
$error = "Error al cargar datos: " . $e->getMessage();
|
||||
$error_page_load = "Error al cargar datos: " . $e->getMessage();
|
||||
}
|
||||
?>
|
||||
|
||||
@ -97,23 +91,18 @@ try {
|
||||
<!-- 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">
|
||||
<?php echo htmlspecialchars($message); ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if ($error && empty($_SERVER['HTTP_X_REQUESTED_WITH'])): ?>
|
||||
<?php if (!empty($error_page_load)): ?>
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<?php echo htmlspecialchars($error); ?>
|
||||
<?php echo htmlspecialchars($error_page_load); ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<i class="fa fa-minus"></i> Registro de Salida de Producto
|
||||
<i class="fa fa-barcode"></i> Escanear Código de Barras
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="salida-form" action="registro_salida.php" method="post">
|
||||
<form id="scan-form" onsubmit="return false;"> <!-- Evita el envío tradicional del formulario -->
|
||||
<div class="mb-3">
|
||||
<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>
|
||||
@ -129,49 +118,42 @@ try {
|
||||
</div>
|
||||
<hr>
|
||||
<div class="mb-3">
|
||||
<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">
|
||||
<i class="fa fa-camera"></i> Escanear
|
||||
</button>
|
||||
<select class="form-select" id="producto" name="product_id" required>
|
||||
<option value="">Seleccione un producto</option>
|
||||
<?php foreach ($products as $product): ?>
|
||||
<option value="<?php echo htmlspecialchars($product['id']); ?>"><?php echo htmlspecialchars($product['nombre']); ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<label for="barcode-input" class="form-label">Esperando código de barras...</label>
|
||||
<input type="text" class="form-control form-control-lg" id="barcode-input" placeholder="Escanee el producto aquí" autofocus>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="cantidad" class="form-label">Cantidad a Retirar (manual)</label>
|
||||
<input type="number" class="form-control" id="cantidad" name="quantity" min="1" required>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary w-100"> <i class="fa fa-minus-circle"></i> Registrar Salida Manual</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabla de productos escaneados -->
|
||||
<div class="col-lg-6 mx-auto mt-4">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<i class="fa fa-check-circle"></i> Productos Registrados
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Producto</th>
|
||||
<th>SKU</th>
|
||||
<th>Estado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="scanned-products-tbody">
|
||||
<!-- Las filas se añadirán aquí dinámicamente -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal para el Escáner -->
|
||||
<div class="modal fade" id="scannerModal" tabindex="-1" aria-labelledby="scannerModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="scannerModalLabel">Escanear Código de Barras</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="reader" style="width: 100%;"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', (event) => {
|
||||
if (typeof bootstrap === 'undefined') {
|
||||
@ -179,10 +161,30 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const barcodeInput = document.getElementById('barcode-input');
|
||||
const sedeSelect = document.getElementById('sede');
|
||||
const dateInput = document.getElementById('movement_date');
|
||||
const tableBody = document.getElementById('scanned-products-tbody');
|
||||
let audioContext;
|
||||
let processing = false; // Flag para evitar escaneos múltiples
|
||||
|
||||
// --- Inicializar AudioContext ---
|
||||
function initAudioContext() {
|
||||
if (!audioContext) {
|
||||
try {
|
||||
audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
||||
console.log("AudioContext inicializado.");
|
||||
} catch (e) {
|
||||
console.error("Web Audio API no es soportada.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
// El usuario debe interactuar con la página para iniciar el audio
|
||||
document.body.addEventListener('click', initAudioContext, { once: true });
|
||||
document.body.addEventListener('keydown', initAudioContext, { once: true });
|
||||
|
||||
|
||||
// --- Funciones de ayuda ---
|
||||
|
||||
function showNotification(message, isSuccess) {
|
||||
const container = document.getElementById('notification-container');
|
||||
if (!container) return;
|
||||
@ -194,9 +196,7 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
||||
<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 class="toast-body">${message}</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML('beforeend', toastHTML);
|
||||
@ -204,72 +204,68 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
||||
const toastElement = document.getElementById(toastId);
|
||||
const toast = new bootstrap.Toast(toastElement, { delay: 5000 });
|
||||
toast.show();
|
||||
toastElement.addEventListener('hidden.bs.toast', () => {
|
||||
toastElement.remove();
|
||||
});
|
||||
toastElement.addEventListener('hidden.bs.toast', () => toastElement.remove());
|
||||
}
|
||||
|
||||
function playBeep() {
|
||||
if (!audioContext) {
|
||||
console.warn("AudioContext no inicializado. El sonido no se reproducirá.");
|
||||
return;
|
||||
}
|
||||
function playBeep(success = true) {
|
||||
if (!audioContext) 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.type = success ? 'sine' : 'square';
|
||||
oscillator.frequency.setValueAtTime(success ? 880 : 440, audioContext.currentTime);
|
||||
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
|
||||
oscillator.start();
|
||||
oscillator.stop(audioContext.currentTime + 0.1);
|
||||
} catch (e) {
|
||||
console.error("Error al reproducir el sonido con Web Audio API.", e);
|
||||
console.error("Error al reproducir sonido.", e);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Lógica del escáner ---
|
||||
|
||||
const scannerModalElement = document.getElementById('scannerModal');
|
||||
if (!scannerModalElement) return;
|
||||
|
||||
const scannerModal = new bootstrap.Modal(scannerModalElement);
|
||||
const html5QrCode = new Html5Qrcode("reader");
|
||||
|
||||
// Inicializar AudioContext con la interacción del usuario
|
||||
document.querySelector('[data-bs-target="#scannerModal"]').addEventListener('click', () => {
|
||||
if (!audioContext) {
|
||||
try {
|
||||
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();
|
||||
|
||||
const sede_id = document.getElementById('sede').value;
|
||||
const movement_date = document.getElementById('movement_date').value;
|
||||
|
||||
if (!sede_id) {
|
||||
showNotification("Por favor, seleccione una sede de origen antes de escanear.", false);
|
||||
// --- Lógica principal del escáner ---
|
||||
barcodeInput.addEventListener('change', function() {
|
||||
const barcodeValue = this.value.trim();
|
||||
if (barcodeValue === '' || processing) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cleanDecodedText = decodedText.trim();
|
||||
fetch(`get_product_details.php?id=${cleanDecodedText}`)
|
||||
processing = true;
|
||||
this.disabled = true; // Bloquear input mientras se procesa
|
||||
|
||||
const sede_id = sedeSelect.value;
|
||||
const movement_date = dateInput.value;
|
||||
|
||||
if (!sede_id || !movement_date) {
|
||||
showNotification("Por favor, seleccione una sede y una fecha antes de escanear.", false);
|
||||
playBeep(false);
|
||||
this.value = '';
|
||||
this.disabled = false;
|
||||
processing = false;
|
||||
this.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
// Añadir fila a la tabla
|
||||
const newRow = tableBody.insertRow(0);
|
||||
const cellProduct = newRow.insertCell(0);
|
||||
const cellSku = newRow.insertCell(1);
|
||||
const cellStatus = newRow.insertCell(2);
|
||||
|
||||
cellProduct.textContent = 'Buscando...';
|
||||
cellSku.textContent = barcodeValue;
|
||||
cellStatus.innerHTML = '<span class="badge bg-warning text-dark">Procesando...</span>';
|
||||
|
||||
fetch(`get_product_details.php?codigo_barras=${encodeURIComponent(barcodeValue)}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success && data.product) {
|
||||
cellProduct.textContent = data.product.nombre;
|
||||
cellSku.textContent = data.product.sku;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('product_id', data.product.id);
|
||||
formData.append('quantity', '1');
|
||||
formData.append('sede_id', sede_id);
|
||||
formData.append('movement_date', movement_date);
|
||||
|
||||
@ -279,38 +275,45 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
||||
body: formData
|
||||
});
|
||||
} else {
|
||||
throw new Error(data.message || 'Producto no encontrado con el código escaneado.');
|
||||
throw new Error(data.message || 'Producto no encontrado.');
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(result => {
|
||||
showNotification(result.message, result.success);
|
||||
if (result.success) {
|
||||
playBeep(true);
|
||||
cellStatus.innerHTML = '<span class="badge bg-success">Registrado</span>';
|
||||
} else {
|
||||
playBeep(false);
|
||||
cellStatus.innerHTML = `<span class="badge bg-danger" title="${result.message}">Error</span>`;
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error en el proceso de escaneo y registro:', error);
|
||||
console.error('Error en el proceso de escaneo:', error);
|
||||
showNotification(error.message, false);
|
||||
});
|
||||
};
|
||||
|
||||
const config = {
|
||||
fps: 10,
|
||||
qrbox: { width: 250, height: 250 },
|
||||
experimentalFeatures: {
|
||||
useBarCodeDetectorIfSupported: false
|
||||
}
|
||||
};
|
||||
|
||||
scannerModalElement.addEventListener('shown.bs.modal', function () {
|
||||
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback, (errorMessage) => {})
|
||||
.catch((err) => {
|
||||
showNotification("Error al iniciar la cámara. Asegúrese de dar permisos.", false);
|
||||
playBeep(false);
|
||||
cellProduct.textContent = 'Error de Búsqueda';
|
||||
cellStatus.innerHTML = `<span class="badge bg-danger" title="${error.message}">Fallo</span>`;
|
||||
})
|
||||
.finally(() => {
|
||||
// Limpiar y re-enfocar el input para el siguiente escaneo
|
||||
this.value = '';
|
||||
this.disabled = false;
|
||||
processing = false;
|
||||
this.focus();
|
||||
});
|
||||
});
|
||||
|
||||
scannerModalElement.addEventListener('hidden.bs.modal', function () {
|
||||
html5QrCode.stop().catch(err => {});
|
||||
// Asegurarse de que el campo de texto siempre tenga el foco
|
||||
barcodeInput.focus();
|
||||
document.body.addEventListener('click', (e) => {
|
||||
// Si el clic no es en un input o select, re-enfocar el campo de escaneo
|
||||
if (!['INPUT', 'SELECT', 'BUTTON'].includes(e.target.tagName)) {
|
||||
barcodeInput.focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
1
sku_failures.log
Normal file
1
sku_failures.log
Normal file
@ -0,0 +1 @@
|
||||
[2026-02-11 23:38:51] Intento fallido de búsqueda con SKU: 4
|
||||
Loading…
x
Reference in New Issue
Block a user