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

366 lines
16 KiB
PHP

<?php
$pageTitle = "Registro de Salida";
require_once 'layout_header.php';
require_once 'db/config.php';
$error_page_load = '';
$sedes = [];
$products = [];
$almacen_principal_id = null;
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);
// Encontrar el ID de "ALMACEN PRINCIPAL" para la lógica móvil
foreach ($sedes as $sede) {
if (trim(strtolower($sede['nombre'])) === 'almacen principal') {
$almacen_principal_id = $sede['id'];
break;
}
}
// Obtener productos
$products_stmt = $pdo->query("SELECT id, nombre, sku 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-out"></i> <?php echo $pageTitle; ?>
</div>
<div class="card-body">
<!-- Pestañas de Navegación -->
<ul class="nav nav-tabs" id="exitTabs" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="barcode-exit-tab" data-bs-toggle="tab" data-bs-target="#barcode-exit" type="button" role="tab" aria-controls="barcode-exit" 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-exit-tab" data-bs-toggle="tab" data-bs-target="#manual-exit" type="button" role="tab" aria-controls="manual-exit" 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="exitTabsContent">
<!-- Pestaña 1: Salida por Código de Barras -->
<div class="tab-pane fade show active" id="barcode-exit" role="tabpanel" aria-labelledby="barcode-exit-tab">
<form id="scan-form" onsubmit="return false;" class="mt-3">
<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" id="sede-container">
<label for="sede-barcode" class="form-label">Sede de Origen</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>
</form>
</div>
<!-- Pestaña 2: Salida Manual por Cantidad -->
<div class="tab-pane fade" id="manual-exit" role="tabpanel" aria-labelledby="manual-exit-tab">
<form id="manual-exit-form" onsubmit="return false;" class="mt-3">
<div class="mb-3">
<label for="manual_sede" class="form-label">Sede de Origen</label>
<select class="form-select" id="manual_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>
<div class="mb-3">
<label for="manual_product" class="form-label">Producto</label>
<select class="form-select" id="manual_product" 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']) . ' (' . htmlspecialchars($product['sku'] ?: 'Sin SKU') . ')'; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label for="manual_quantity" class="form-label">Cantidad a Retirar</label>
<input type="number" class="form-control" id="manual_quantity" name="quantity" min="1" placeholder="Escriba la cantidad" required>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-warning"><i class="fa fa-minus-circle"></i> Registrar Salida 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 dateInput = document.getElementById('movement_date');
const sedeContainer = document.getElementById('sede-container');
const manualExitForm = document.getElementById('manual-exit-form');
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 ---
let audioCtx;
function wakeUpAudio() {
if (!audioCtx) {
try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch (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());
}
// --- LÓGICA PARA MÓVIL (SOLO PESTAÑA CÓDIGO DE BARRAS) ---
if (isMobile && almacenPrincipalId) {
if(sedeContainer) sedeContainer.style.display = 'none';
if(sedeBarcodeSelect) sedeBarcodeSelect.value = almacenPrincipalId;
}
// --- PESTAÑA: CÓDIGO DE BARRAS ---
// ** Lógica 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 => {});
}
});
// ** Lógica del Escáner **
barcodeInput.addEventListener('change', function() {
const barcodeValue = this.value.trim();
if (barcodeValue === '' || processing) return;
processing = true;
this.disabled = true;
const sedeId = sedeBarcodeSelect.value;
if (!sedeId) {
showNotification("Por favor, seleccione una sede de origen.", false);
playBeep(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.');
}
})
.catch(error => {
showNotification(error.message, false);
playBeep(false);
})
.finally(() => {
this.value = '';
this.disabled = false;
processing = false;
this.focus();
});
});
// --- PESTAÑA: SALIDA MANUAL ---
if (manualExitForm) {
manualExitForm.addEventListener('submit', function(e) {
e.preventDefault();
if (processing) return;
const formData = new FormData(this);
const sedeId = formData.get('sede_id');
const productId = formData.get('product_id');
const quantity = formData.get('quantity');
if (!sedeId || !productId || !quantity || parseInt(quantity, 10) <= 0) {
showNotification("Todos los campos son obligatorios y la cantidad debe ser positiva.", false);
playBeep(false);
return;
}
if (!confirm(`¿Está seguro de que desea retirar ${quantity} unidad(es) de este producto? Esta acción ajustará el inventario.`)) {
return;
}
processing = true;
fetch('registrar_salida_manual_api.php', { method: 'POST', body: formData })
.then(response => response.json())
.then(data => {
if (data.success) {
showNotification(data.message, true);
playBeep(true);
manualExitForm.reset();
} else {
throw new Error(data.message || 'Error desconocido.');
}
})
.catch(error => {
showNotification(error.message, false);
playBeep(false);
})
.finally(() => {
processing = false;
});
});
}
// --- LÓGICA DE PESTAÑAS ---
const tabs = new bootstrap.Tab(document.getElementById('barcode-exit-tab'));
tabs.show();
document.getElementById('barcode-exit-tab').addEventListener('shown.bs.tab', function () {
barcodeInput.focus();
});
document.getElementById('manual-exit-tab').addEventListener('shown.bs.tab', function () {
document.getElementById('manual_sede').focus();
});
document.body.addEventListener('click', (e) => {
const activeTab = document.querySelector('.tab-pane.active');
if (activeTab && activeTab.id === 'barcode-exit') {
if (!e.target.closest('input, button, select, .modal')) {
barcodeInput.focus();
}
}
});
});
</script>
<?php require_once 'layout_footer.php'; ?>