34849-vm/registro_salida.php
2026-02-12 12:13:18 +00:00

311 lines
12 KiB
PHP

<?php
$pageTitle = "Registro de Salida de Producto";
require_once 'layout_header.php';
require_once 'db/config.php';
$error_page_load = '';
$almacen_principal_id = null;
// Obtener sedes para el dropdown
$sedes = [];
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();
}
?>
<div class="container mt-4">
<div class="row">
<div class="col-lg-6 mx-auto">
<!-- Contenedor para notificaciones (toasts) -->
<div id="notification-container" class="position-fixed top-0 end-0 p-3" style="z-index: 1100"></div>
<?php if (!empty($error_page_load)): ?>
<div class="alert alert-danger" role="alert">
<?php echo htmlspecialchars($error_page_load); ?>
</div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<i class="fa fa-barcode"></i> Escanear Código de Barras
</div>
<div class="card-body">
<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>
<!-- 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 echo htmlspecialchars($sede['nombre']); ?></option>
<?php endforeach; ?>
</select>
</div>
<hr>
<div class="mb-3">
<label for="barcode-input" class="form-label">Esperando código de barras...</label>
<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>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- 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">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="camera-modal-label">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" 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@2.3.8/html5-qrcode.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
// --- 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) {
barcodeInput.value = decodedText;
const changeEvent = new Event('change');
barcodeInput.dispatchEvent(changeEvent);
const modal = bootstrap.Modal.getInstance(cameraModal);
if(modal) modal.hide();
}
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 => alert("Error al iniciar la cámara. Asegúrate de dar permisos."));
});
cameraModal.addEventListener('hidden.bs.modal', function () {
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();
}
});
});
</script>
<?php require_once 'layout_footer.php'; ?>