Autosave: 20260212-121318
This commit is contained in:
parent
98f0c58027
commit
60510752fa
@ -3,51 +3,38 @@ header('Content-Type: application/json');
|
||||
require_once 'db/config.php';
|
||||
|
||||
$response = ['success' => false, 'message' => 'No se proporcionó un identificador de producto.'];
|
||||
|
||||
$pdo = db();
|
||||
$product = null;
|
||||
|
||||
// Handle search by SKU (barcode)
|
||||
// Universal search: treat any incoming ID as a potential SKU.
|
||||
$sku = '';
|
||||
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.';
|
||||
// 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
|
||||
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['sku'])) {
|
||||
$sku = trim($_GET['sku']);
|
||||
} elseif (isset($_GET['id'])) {
|
||||
$product_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
|
||||
if ($product_id) {
|
||||
try {
|
||||
$stmt = $pdo->prepare("SELECT id, nombre, sku FROM products WHERE id = :id");
|
||||
$stmt->execute(['id' => $product_id]);
|
||||
$product = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$product) {
|
||||
$response['message'] = 'Producto no encontrado con el ID proporcionado.';
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
error_log('Database Error: ' . $e->getMessage());
|
||||
$response['message'] = 'Error al consultar la base de datos.';
|
||||
$sku = trim($_GET['id']);
|
||||
}
|
||||
|
||||
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 proporcionado: ' . htmlspecialchars($sku);
|
||||
// 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);
|
||||
}
|
||||
} else {
|
||||
$response['message'] = 'ID de producto inválido.';
|
||||
} 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.';
|
||||
}
|
||||
|
||||
if ($product) {
|
||||
|
||||
@ -4,6 +4,7 @@ require_once 'layout_header.php';
|
||||
require_once 'db/config.php';
|
||||
|
||||
$error_page_load = '';
|
||||
$almacen_principal_id = null;
|
||||
|
||||
// Obtener sedes para el dropdown
|
||||
$sedes = [];
|
||||
@ -11,6 +12,15 @@ try {
|
||||
$pdo = db();
|
||||
$sedes_stmt = $pdo->query("SELECT id, nombre FROM sedes ORDER BY nombre ASC");
|
||||
$sedes = $sedes_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// Encontrar el ID de "ALMACEN PRINCIPAL" para usarlo en el script
|
||||
foreach ($sedes as $sede) {
|
||||
if (trim(strtolower($sede['nombre'])) === 'almacen principal') {
|
||||
$almacen_principal_id = $sede['id'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$error_page_load = "Error al cargar datos: " . $e->getMessage();
|
||||
}
|
||||
@ -34,17 +44,19 @@ try {
|
||||
<i class="fa fa-barcode"></i> Escanear Código de Barras
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="scan-form" onsubmit="return false;"> <!-- Evita el envío tradicional del formulario -->
|
||||
<form id="scan-form" onsubmit="return false;">
|
||||
<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>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
|
||||
<!-- El contenedor de la sede ahora tiene un ID para poder ocultarlo -->
|
||||
<div class="mb-3" id="sede-container">
|
||||
<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>
|
||||
<option value="<?php echo htmlspecialchars($sede['id']); ?>"><?php echo htmlspecialchars($sede['nombre']); ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
@ -54,7 +66,7 @@ try {
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control form-control-lg" id="barcode-input" placeholder="Escanee el producto aquí" autofocus>
|
||||
<button class="btn btn-outline-secondary" type="button" id="scan-camera-btn" data-bs-toggle="modal" data-bs-target="#camera-modal">
|
||||
<i class="fa fa-camera"></i> Escanear con Cámara
|
||||
<i class="fa fa-camera"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@ -62,236 +74,9 @@ try {
|
||||
</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>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', (event) => {
|
||||
if (typeof bootstrap === 'undefined') {
|
||||
console.error('Bootstrap no está cargado.');
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
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(success = true) {
|
||||
if (!audioContext) return;
|
||||
try {
|
||||
const oscillator = audioContext.createOscillator();
|
||||
const gainNode = audioContext.createGain();
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(audioContext.destination);
|
||||
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 sonido.", e);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Lógica principal del escáner ---
|
||||
barcodeInput.addEventListener('change', function() {
|
||||
const barcodeValue = this.value.trim();
|
||||
if (barcodeValue === '' || processing) {
|
||||
return;
|
||||
}
|
||||
|
||||
processing = true;
|
||||
this.disabled = true;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
cellStatus.innerHTML = `
|
||||
<button class="btn btn-success btn-sm aceptar-salida-btn" data-product-id="${data.product.id}">Aceptar</button>
|
||||
<button class="btn btn-danger btn-sm cancelar-salida-btn">Cancelar</button>
|
||||
`;
|
||||
playBeep(true);
|
||||
} else {
|
||||
throw new Error(data.message || 'Producto no encontrado.');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error en el proceso de escaneo:', error);
|
||||
showNotification(error.message, false);
|
||||
playBeep(false);
|
||||
cellProduct.textContent = 'Error de Búsqueda';
|
||||
cellStatus.innerHTML = `<span class="badge bg-danger" title="${error.message}">Fallo</span>`;
|
||||
})
|
||||
.finally(() => {
|
||||
this.value = '';
|
||||
this.disabled = false;
|
||||
processing = false;
|
||||
this.focus();
|
||||
});
|
||||
});
|
||||
|
||||
// --- Lógica para Aceptar o Cancelar la salida ---
|
||||
tableBody.addEventListener('click', function(event) {
|
||||
const button = event.target;
|
||||
|
||||
// --- Botón Cancelar ---
|
||||
if (button.classList.contains('cancelar-salida-btn')) {
|
||||
button.closest('tr').remove();
|
||||
return;
|
||||
}
|
||||
|
||||
// --- Botón Aceptar ---
|
||||
if (button.classList.contains('aceptar-salida-btn')) {
|
||||
const productId = button.dataset.productId;
|
||||
const sedeId = sedeSelect.value;
|
||||
const movementDate = dateInput.value;
|
||||
|
||||
if (!productId || !sedeId || !movementDate) {
|
||||
showNotification('Error interno: Faltan datos para registrar la salida.', false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Deshabilitar ambos botones para evitar doble clic
|
||||
button.parentElement.querySelectorAll('button').forEach(btn => btn.disabled = true);
|
||||
button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Registrando...';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('product_id', productId);
|
||||
formData.append('sede_id', sedeId);
|
||||
formData.append('movement_date', movementDate);
|
||||
|
||||
fetch('registrar_salida_api.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
showNotification(data.message, true);
|
||||
playBeep(true);
|
||||
button.parentElement.innerHTML = '<span class="badge bg-success">Salida Registrada</span>';
|
||||
} else {
|
||||
throw new Error(data.message || 'Error al registrar la salida.');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error en el registro:', error);
|
||||
showNotification(error.message, false);
|
||||
playBeep(false);
|
||||
// Reactivar botones en caso de error
|
||||
const originalButtons = `
|
||||
<button class="btn btn-success btn-sm aceptar-salida-btn" data-product-id="${productId}">Aceptar</button>
|
||||
<button class="btn btn-danger btn-sm cancelar-salida-btn">Cancelar</button>
|
||||
`;
|
||||
button.parentElement.innerHTML = originalButtons;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Asegurarse de que el campo de texto siempre tenga el foco
|
||||
barcodeInput.focus();
|
||||
document.body.addEventListener('click', (e) => {
|
||||
if (!['INPUT', 'SELECT', 'BUTTON', 'A'].includes(e.target.tagName) && !e.target.closest('button')) {
|
||||
barcodeInput.focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Modal para la cámara -->
|
||||
<div class="modal fade" id="camera-modal" tabindex="-1" aria-labelledby="camera-modal-label" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
@ -311,49 +96,213 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
||||
</div>
|
||||
|
||||
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', (event) => {
|
||||
const cameraModal = document.getElementById('camera-modal');
|
||||
// --- CONFIGURACIÓN INICIAL ---
|
||||
if (typeof bootstrap === 'undefined') {
|
||||
console.error('Bootstrap no está cargado.');
|
||||
return;
|
||||
}
|
||||
|
||||
const barcodeInput = document.getElementById('barcode-input');
|
||||
const sedeSelect = document.getElementById('sede');
|
||||
const dateInput = document.getElementById('movement_date');
|
||||
const sedeContainer = document.getElementById('sede-container');
|
||||
|
||||
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
|
||||
const almacenPrincipalId = '<?php echo $almacen_principal_id; ?>';
|
||||
|
||||
let processing = false;
|
||||
|
||||
// --- LÓGICA DE SONIDO (WEB AUDIO API) ---
|
||||
let audioCtx;
|
||||
|
||||
// Esta función inicializa y DESBLOQUEA el audio.
|
||||
// Debe ser llamada por una interacción directa del usuario (click o touch).
|
||||
function unlockAudio() {
|
||||
if (audioCtx) {
|
||||
if (audioCtx.state === 'suspended') {
|
||||
audioCtx.resume().then(() => {
|
||||
console.log("AudioContext reanudado exitosamente.");
|
||||
}).catch(e => console.error("Error al reanudar AudioContext:", e));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
// La primera vez, resume() es crucial para navegadores que inician en estado 'suspended'.
|
||||
audioCtx.resume().then(() => {
|
||||
console.log("AudioContext inicializado y desbloqueado.");
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Web Audio API no es soportada en este navegador.", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Asignamos la función de desbloqueo a los primeros eventos de interacción del usuario.
|
||||
// `{ once: true }` asegura que solo se ejecute una vez.
|
||||
document.body.addEventListener('click', unlockAudio, { once: true });
|
||||
document.body.addEventListener('touchstart', unlockAudio, { once: true });
|
||||
|
||||
function playBeep() {
|
||||
if (!audioCtx || audioCtx.state !== 'running') {
|
||||
console.warn("AudioContext no está listo o desbloqueado. No se puede reproducir sonido.");
|
||||
// Intento de último recurso (puede no funcionar si no es por gesto de usuario)
|
||||
unlockAudio();
|
||||
return;
|
||||
}
|
||||
|
||||
const oscillator = audioCtx.createOscillator();
|
||||
const gainNode = audioCtx.createGain();
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(audioCtx.destination);
|
||||
|
||||
gainNode.gain.value = 0.1; // Volumen bajo para no ser molesto
|
||||
oscillator.frequency.value = 880; // Frecuencia del tono (un La agudo)
|
||||
oscillator.type = 'sine'; // Tipo de onda
|
||||
|
||||
oscillator.start();
|
||||
setTimeout(() => {
|
||||
oscillator.stop();
|
||||
}, 150); // Duración del sonido en milisegundos
|
||||
}
|
||||
|
||||
|
||||
// --- LÓGICA PARA MÓVIL ---
|
||||
if (isMobile) {
|
||||
if(sedeContainer) {
|
||||
sedeContainer.style.display = 'none'; // Ocultar el selector de sede
|
||||
}
|
||||
if(sedeSelect && almacenPrincipalId) {
|
||||
sedeSelect.value = almacenPrincipalId; // Seleccionar ALMACEN PRINCIPAL por defecto
|
||||
}
|
||||
console.log('Modo móvil activado. Sede por defecto: ALMACEN PRINCIPAL');
|
||||
}
|
||||
|
||||
// --- INICIALIZACIÓN DE CÁMARA ---
|
||||
const cameraModal = document.getElementById('camera-modal');
|
||||
let html5QrCode;
|
||||
|
||||
function onScanSuccess(decodedText, decodedResult) {
|
||||
// `decodedText` es el SKU escaneado
|
||||
console.log(`Código escaneado: ${decodedText}`);
|
||||
|
||||
// Poner el valor en el input
|
||||
barcodeInput.value = decodedText;
|
||||
|
||||
// Disparar el evento change para que se procese como un escaneo manual
|
||||
const changeEvent = new Event('change');
|
||||
barcodeInput.dispatchEvent(changeEvent);
|
||||
|
||||
// Cerrar el modal
|
||||
const modal = bootstrap.Modal.getInstance(cameraModal);
|
||||
modal.hide();
|
||||
if(modal) modal.hide();
|
||||
}
|
||||
|
||||
function onScanFailure(error) {
|
||||
// No hacer nada, simplemente seguir escaneando
|
||||
}
|
||||
function onScanFailure(error) { /* No hacer nada */ }
|
||||
|
||||
cameraModal.addEventListener('shown.bs.modal', function () {
|
||||
html5QrCode = new Html5Qrcode("reader");
|
||||
const config = { fps: 10, qrbox: { width: 250, height: 250 } };
|
||||
html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess, onScanFailure)
|
||||
.catch(err => {
|
||||
console.error("No se pudo iniciar la cámara.", err);
|
||||
alert("Error al iniciar la cámara. Asegúrate de dar permisos y que no esté siendo usada por otra aplicación.");
|
||||
});
|
||||
.catch(err => alert("Error al iniciar la cámara. Asegúrate de dar permisos."));
|
||||
});
|
||||
|
||||
cameraModal.addEventListener('hidden.bs.modal', function () {
|
||||
if (html5QrCode) {
|
||||
html5QrCode.stop().then(ignore => {
|
||||
console.log("Cámara detenida.");
|
||||
}).catch(err => {
|
||||
console.error("No se pudo detener la cámara.", err);
|
||||
if (html5QrCode && html5QrCode.isScanning) {
|
||||
html5QrCode.stop().catch(err => console.error("No se pudo detener la cámara.", err));
|
||||
}
|
||||
});
|
||||
|
||||
// --- FUNCIONES DE AYUDA (Notificaciones) ---
|
||||
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 toast = new bootstrap.Toast(document.getElementById(toastId), { delay: 5000 });
|
||||
toast.show();
|
||||
document.getElementById(toastId).addEventListener('hidden.bs.toast', e => e.target.remove());
|
||||
}
|
||||
|
||||
// --- LÓGICA PRINCIPAL DEL ESCÁNER ---
|
||||
barcodeInput.addEventListener('change', function() {
|
||||
const barcodeValue = this.value.trim();
|
||||
if (barcodeValue === '' || processing) return;
|
||||
|
||||
processing = true;
|
||||
this.disabled = true;
|
||||
|
||||
const sedeId = sedeSelect.value;
|
||||
const movementDate = dateInput.value;
|
||||
|
||||
if (!sedeId || !movementDate) {
|
||||
showNotification("Por favor, seleccione una sede y una fecha.", false);
|
||||
this.value = '';
|
||||
this.disabled = false;
|
||||
processing = false;
|
||||
this.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`get_product_details.php?codigo_barras=${encodeURIComponent(barcodeValue)}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success && data.product) {
|
||||
playBeep(); // <-- LLAMADA AL SONIDO AQUÍ
|
||||
if (confirm(`¿Registrar salida de "${data.product.nombre}"?`)) {
|
||||
registerProductExit(data.product.id, sedeId, movementDate);
|
||||
} else {
|
||||
console.log('Salida cancelada por el usuario.');
|
||||
}
|
||||
} else {
|
||||
throw new Error(data.message || 'Producto no encontrado.');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
showNotification(error.message, false);
|
||||
})
|
||||
.finally(() => {
|
||||
this.value = '';
|
||||
this.disabled = false;
|
||||
processing = false;
|
||||
this.focus();
|
||||
});
|
||||
});
|
||||
|
||||
function registerProductExit(productId, sedeId, movementDate) {
|
||||
const formData = new FormData();
|
||||
formData.append('product_id', productId);
|
||||
formData.append('sede_id', sedeId);
|
||||
formData.append('movement_date', movementDate);
|
||||
|
||||
fetch('registrar_salida_api.php', {
|
||||
method: 'POST',
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
showNotification(data.message, true);
|
||||
} else {
|
||||
throw new Error(data.message || 'Error al registrar la salida.');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
showNotification(error.message, false);
|
||||
});
|
||||
}
|
||||
|
||||
// Mantener el foco en el input
|
||||
barcodeInput.focus();
|
||||
document.body.addEventListener('click', (e) => {
|
||||
// Si el clic no es en un input, select, botón o link, re-enfocar el campo de escaneo
|
||||
if (!['INPUT', 'SELECT', 'BUTTON', 'A'].includes(e.target.tagName) && !e.target.closest('button, a')) {
|
||||
barcodeInput.focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@ -1 +1,2 @@
|
||||
[2026-02-11 23:38:51] Intento fallido de búsqueda con SKU: 4
|
||||
[2026-02-12 00:29:21] Intento fallido de búsqueda con SKU: $
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user