34849-vm/registro_salida.php
2026-02-12 15:48:10 +00:00

258 lines
10 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;
function wakeUpAudio() {
if (!audioCtx) {
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
} catch (e) { console.error("Web Audio API no es soportada.", e); return; }
}
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
}
document.body.addEventListener('click', wakeUpAudio, { once: true });
document.body.addEventListener('touchstart', wakeUpAudio, { once: true });
function playBeep() {
if (!audioCtx || audioCtx.state !== 'running') {
wakeUpAudio();
if (!audioCtx || audioCtx.state !== 'running') return;
}
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
gainNode.gain.value = 0.1;
oscillator.frequency.value = 880;
oscillator.type = 'sine';
oscillator.start();
setTimeout(() => oscillator.stop(), 150);
}
// --- LÓGICA PARA MÓVIL ---
if (isMobile) {
if(sedeContainer) sedeContainer.style.display = 'none';
if(sedeSelect && almacenPrincipalId) sedeSelect.value = almacenPrincipalId;
}
// --- INICIALIZACIÓN DE CÁMARA ---
const cameraModal = document.getElementById('camera-modal');
let html5QrCode;
function onScanSuccess(decodedText, decodedResult) {
playBeep();
barcodeInput.value = decodedText;
const changeEvent = new Event('change');
barcodeInput.dispatchEvent(changeEvent);
const modal = bootstrap.Modal.getInstance(cameraModal);
if(modal) modal.hide();
}
cameraModal.addEventListener('shown.bs.modal', function () {
wakeUpAudio();
html5QrCode = new Html5Qrcode("reader");
const config = { fps: 10, qrbox: { width: 250, height: 250 } };
html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess, (e)=>{})
.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 => {});
}
});
// --- 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; // Although not used by new API, good to have if needed later
if (!sedeId) {
showNotification("Por favor, seleccione una sede de origen.", false);
this.value = '';
this.disabled = false;
processing = false;
this.focus();
return;
}
const formData = new FormData();
formData.append('codigo_unico', barcodeValue);
formData.append('sede_id', sedeId);
fetch('registrar_salida_unidad_api.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showNotification(data.message, true);
} else {
throw new Error(data.message || 'Error desconocido al registrar la salida.');
}
})
.catch(error => {
showNotification(error.message, false);
})
.finally(() => {
this.value = '';
this.disabled = false;
processing = false;
this.focus();
});
});
// Mantener el foco en el input
barcodeInput.focus();
document.body.addEventListener('click', (e) => {
if (!['INPUT', 'SELECT', 'BUTTON', 'A'].includes(e.target.tagName) && !e.target.closest('button, a')) {
barcodeInput.focus();
}
});
});
</script>
<?php require_once 'layout_footer.php'; ?>