34849-vm/registro_entrada.php
2026-02-17 03:13:39 +00:00

369 lines
16 KiB
PHP

<?php
$pageTitle = "Registro de Entrada";
require_once 'layout_header.php';
require_once 'db/config.php';
$error_page_load = '';
$sedes = [];
$products = [];
try {
$pdo = db();
// Obtener sedes
$sedes_stmt = $pdo->query("SELECT id, nombre FROM sedes ORDER BY nombre ASC");
$sedes = $sedes_stmt->fetchAll(PDO::FETCH_ASSOC);
// Obtener productos
$products_stmt = $pdo->query("SELECT id, nombre FROM products ORDER BY nombre ASC");
$products = $products_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error_page_load = "Error al cargar datos iniciales: " . $e->getMessage();
}
?>
<div class="container mt-4">
<div class="row">
<div class="col-lg-8 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-sign-in"></i> <?php echo $pageTitle; ?>
</div>
<div class="card-body">
<!-- Pestañas de Navegación -->
<ul class="nav nav-tabs" id="entryTabs" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="barcode-tab" data-bs-toggle="tab" data-bs-target="#barcode-entry" type="button" role="tab" aria-controls="barcode-entry" aria-selected="true">
<i class="fa fa-barcode"></i> Por Código de Barras
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="manual-tab" data-bs-toggle="tab" data-bs-target="#manual-entry" type="button" role="tab" aria-controls="manual-entry" aria-selected="false">
<i class="fa fa-edit"></i> Manual por Cantidad
</button>
</li>
</ul>
<!-- Contenido de las Pestañas -->
<div class="tab-content" id="entryTabsContent">
<!-- Pestaña 1: Entrada por Código de Barras -->
<div class="tab-pane fade show active" id="barcode-entry" role="tabpanel" aria-labelledby="barcode-tab">
<form id="scan-form" onsubmit="return false;" class="mt-3">
<div class="mb-3">
<label for="sede-barcode" class="form-label">Sede de Destino</label>
<select class="form-select" id="sede-barcode" 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" data-bs-toggle="modal" data-bs-target="#camera-modal">
<i class="fa fa-camera"></i>
</button>
</div>
</div>
<div id="scanned-product-info" class="mt-3" style="display: none;">
<p><strong>Producto escaneado:</strong> <span id="scanned-code"></span></p>
<div class="d-grid gap-2">
<button type="button" id="accept-btn" class="btn btn-success"> <i class="fa fa-check-circle"></i> Aceptar y Registrar</button>
<button type="button" id="cancel-btn" class="btn btn-danger"> <i class="fa fa-times-circle"></i> Cancelar</button>
</div>
</div>
</form>
</div>
<!-- Pestaña 2: Entrada Manual por Cantidad -->
<div class="tab-pane fade" id="manual-entry" role="tabpanel" aria-labelledby="manual-tab">
<form id="manual-entry-form" class="mt-3">
<div class="mb-3">
<label for="sede-manual" class="form-label">Sede de Destino</label>
<select class="form-select" id="sede-manual" 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>
<div class="mb-3">
<label for="product-manual" class="form-label">Producto</label>
<select class="form-select" id="product-manual" 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>
</div>
<div class="mb-3">
<label for="quantity-manual" class="form-label">Cantidad a Ingresar</label>
<input type="number" class="form-control" id="quantity-manual" name="cantidad" min="1" required>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary"><i class="fa fa-plus-circle"></i> Registrar Entrada Manual</button>
</div>
</form>
</div>
</div>
</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 GENERAL ---
if (typeof bootstrap === 'undefined') {
console.error('Bootstrap no está cargado.');
return;
}
const barcodeInput = document.getElementById('barcode-input');
const sedeBarcodeSelect = document.getElementById('sede-barcode');
const scannedProductInfo = document.getElementById('scanned-product-info');
const scannedCodeSpan = document.getElementById('scanned-code');
const acceptBtn = document.getElementById('accept-btn');
const cancelBtn = document.getElementById('cancel-btn');
const manualForm = document.getElementById('manual-entry-form');
let processing = false;
let lastScannedCode = null;
// --- 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(success = true) {
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 = success ? 880 : 440;
oscillator.type = success ? 'sine' : 'square';
oscillator.start();
setTimeout(() => oscillator.stop(), 150);
}
// --- 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());
}
// --- PESTAÑA: CÓDIGO DE BARRAS ---
// ** Lógica de Cámara **
const cameraModal = document.getElementById('camera-modal');
let html5QrCode;
function onScanSuccess(decodedText, decodedResult) {
const modal = bootstrap.Modal.getInstance(cameraModal);
if(modal) modal.hide();
barcodeInput.value = decodedText;
const changeEvent = new Event('change');
barcodeInput.dispatchEvent(changeEvent);
}
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 => {});
}
});
// ** Lógica del Escáner **
function resetScanner() {
lastScannedCode = null;
barcodeInput.value = '';
barcodeInput.disabled = false;
scannedProductInfo.style.display = 'none';
processing = false;
barcodeInput.focus();
}
barcodeInput.addEventListener('change', function() {
const barcodeValue = this.value.trim();
if (barcodeValue === '') return;
playBeep();
lastScannedCode = barcodeValue;
scannedCodeSpan.textContent = barcodeValue;
scannedProductInfo.style.display = 'block';
this.disabled = true;
acceptBtn.focus();
});
cancelBtn.addEventListener('click', resetScanner);
acceptBtn.addEventListener('click', function() {
if (processing || !lastScannedCode) return;
processing = true;
const sedeId = sedeBarcodeSelect.value;
if (!sedeId) {
showNotification("Por favor, seleccione una sede de destino.", false);
playBeep(false);
processing = false;
return;
}
const formData = new FormData();
formData.append('codigo_unico', lastScannedCode);
formData.append('sede_id', sedeId);
fetch('registrar_entrada_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.');
}
})
.catch(error => {
showNotification(error.message, false);
playBeep(false);
})
.finally(() => {
resetScanner();
});
});
// --- PESTAÑA: ENTRADA MANUAL ---
manualForm.addEventListener('submit', function(e) {
e.preventDefault();
if (processing) return;
processing = true;
const formData = new FormData(this);
const sedeId = formData.get('sede_id');
const productId = formData.get('product_id');
const cantidad = formData.get('cantidad');
if (!sedeId || !productId || !cantidad || cantidad < 1) {
showNotification("Todos los campos son obligatorios y la cantidad debe ser mayor a cero.", false);
playBeep(false);
processing = false;
return;
}
fetch('registrar_entrada_manual_api.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showNotification(data.message, true);
playBeep(true);
manualForm.reset();
} else {
throw new Error(data.message || 'Error desconocido al registrar la entrada.');
}
})
.catch(error => {
showNotification(error.message, false);
playBeep(false);
})
.finally(() => {
processing = false;
});
});
// --- LÓGICA DE PESTAÑAS ---
const tabs = new bootstrap.Tab(document.getElementById('barcode-tab'));
tabs.show();
// Auto-focus en el input correcto al cambiar de pestaña
document.getElementById('barcode-tab').addEventListener('shown.bs.tab', function () {
barcodeInput.focus();
});
document.getElementById('manual-tab').addEventListener('shown.bs.tab', function () {
document.getElementById('sede-manual').focus();
});
// Mantener el foco en el input principal de la pestaña de código de barras
document.body.addEventListener('click', (e) => {
const activeTab = document.querySelector('.tab-pane.active');
if (activeTab && activeTab.id === 'barcode-entry') {
if (!e.target.closest('input, button, select, .modal')) {
barcodeInput.focus();
}
}
});
});
</script>
<?php require_once 'layout_footer.php'; ?>