519 lines
24 KiB
PHP
519 lines
24 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);
|
|
|
|
// Si viene de un borrador
|
|
$borrador = null;
|
|
if (isset($_GET['borrador_id'])) {
|
|
$stmt_borrador = $pdo->prepare("SELECT * FROM ingreso_borrador WHERE id = ?");
|
|
$stmt_borrador->execute([$_GET['borrador_id']]);
|
|
$borrador = $stmt_borrador->fetch(PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
// --- Lógica para el Historial de Entradas ---
|
|
$fecha_filtro = $_GET['fecha'] ?? '';
|
|
$where_clause = " WHERE sm.type = 'entrada' ";
|
|
$params = [];
|
|
|
|
if (!empty($fecha_filtro)) {
|
|
$where_clause .= " AND DATE(sm.movement_date) = :fecha ";
|
|
$params[':fecha'] = $fecha_filtro;
|
|
$limit = 500;
|
|
} else {
|
|
$limit = 50;
|
|
}
|
|
|
|
$query = "
|
|
SELECT sm.movement_date, p.nombre as product_name, s.nombre as sede_name, sm.quantity, sm.type, sm.codigo_unico, sm.metodo_registro
|
|
FROM stock_movements sm
|
|
JOIN products p ON sm.product_id = p.id
|
|
JOIN sedes s ON sm.sede_id = s.id
|
|
$where_clause
|
|
ORDER BY sm.created_at DESC
|
|
LIMIT $limit
|
|
";
|
|
|
|
$movements_stmt = $pdo->prepare($query);
|
|
$movements_stmt->execute($params);
|
|
$movements = $movements_stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
|
|
// --- Resumen de Entradas de Hoy ---
|
|
$hoy = date('Y-m-d');
|
|
$resumen_entradas_stmt = $pdo->prepare("
|
|
SELECT p.nombre, SUM(sm.quantity) as total_entrada
|
|
FROM stock_movements sm
|
|
JOIN products p ON sm.product_id = p.id
|
|
WHERE sm.type = 'entrada' AND DATE(sm.movement_date) = :hoy
|
|
GROUP BY p.nombre
|
|
ORDER BY total_entrada DESC
|
|
");
|
|
$resumen_entradas_stmt->execute([':hoy' => $hoy]);
|
|
$resumen_entradas = $resumen_entradas_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 <?php echo !$borrador ? 'active' : ''; ?>" id="barcode-tab" data-bs-toggle="tab" data-bs-target="#barcode-entry" type="button" role="tab" aria-controls="barcode-entry" aria-selected="<?php echo !$borrador ? 'true' : 'false'; ?>">
|
|
<i class="fa fa-barcode"></i> Por Código de Barras
|
|
</button>
|
|
</li>
|
|
<li class="nav-item" role="presentation">
|
|
<button class="nav-link <?php echo $borrador ? 'active' : ''; ?>" id="manual-tab" data-bs-toggle="tab" data-bs-target="#manual-entry" type="button" role="tab" aria-controls="manual-entry" aria-selected="<?php echo $borrador ? 'true' : '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 <?php echo !$borrador ? 'show active' : ''; ?>" id="barcode-entry" role="tabpanel" aria-labelledby="barcode-tab">
|
|
<form id="scan-form" onsubmit="return false;" class="mt-3">
|
|
<?php if ($borrador): ?>
|
|
<div class="alert alert-info">
|
|
<i class="fas fa-info-circle me-2"></i>
|
|
Registrando mercadería desde el borrador: <strong><?php echo htmlspecialchars($borrador['nombre_producto']); ?></strong>
|
|
<input type="hidden" id="borrador_id_barcode" value="<?php echo $borrador['id']; ?>">
|
|
</div>
|
|
<?php endif; ?>
|
|
<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>
|
|
</form>
|
|
</div>
|
|
|
|
<!-- Pestaña 2: Entrada Manual por Cantidad -->
|
|
<div class="tab-pane fade <?php echo $borrador ? 'show active' : ''; ?>" id="manual-entry" role="tabpanel" aria-labelledby="manual-tab">
|
|
<form id="manual-entry-form" class="mt-3">
|
|
<?php if ($borrador): ?>
|
|
<div class="alert alert-info">
|
|
<i class="fas fa-info-circle me-2"></i>
|
|
Registrando mercadería desde el borrador: <strong><?php echo htmlspecialchars($borrador['nombre_producto']); ?></strong>
|
|
<input type="hidden" name="borrador_id" value="<?php echo $borrador['id']; ?>">
|
|
</div>
|
|
<?php endif; ?>
|
|
<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 ($borrador && $borrador['product_id'] == $product['id']) ? 'selected' : ''; ?>>
|
|
<?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" value="<?php echo $borrador ? ($borrador['cantidad_recibida'] ?? $borrador['cantidad_esperada']) : ''; ?>" 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>
|
|
|
|
<!-- Resumen de Entradas de Hoy -->
|
|
<div class="row mt-4" id="resumen-hoy-container">
|
|
<div class="col-lg-10 mx-auto">
|
|
<div class="card border-success shadow-sm">
|
|
<div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
|
|
<h5 class="m-0"><i class="fa fa-list-alt"></i> Resumen de Entradas de Hoy (<?php echo date("d/m/Y"); ?>)</h5>
|
|
<span class="badge bg-white text-success"><?php echo count($resumen_entradas); ?> Productos</span>
|
|
</div>
|
|
<div class="card-body">
|
|
<?php if (empty($resumen_entradas)): ?>
|
|
<p class="text-muted mb-0 text-center">No se han registrado entradas el día de hoy.</p>
|
|
<?php else: ?>
|
|
<div class="row">
|
|
<?php foreach ($resumen_entradas as $res): ?>
|
|
<div class="col-md-4 col-sm-6 mb-2">
|
|
<div class="p-2 border rounded bg-light d-flex justify-content-between align-items-center">
|
|
<span class="text-truncate me-2" title="<?php echo htmlspecialchars($res['nombre']); ?>">
|
|
<?php echo htmlspecialchars($res['nombre']); ?>
|
|
</span>
|
|
<span class="badge bg-success fs-6"><?php echo $res['total_entrada']; ?></span>
|
|
</div>
|
|
</div>
|
|
<?php endforeach; ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Historial de Entradas -->
|
|
<div class="row mt-4" id="historial-container">
|
|
<div class="col-lg-10 mx-auto">
|
|
<div class="card">
|
|
<div class="card-header d-flex justify-content-between align-items-center">
|
|
<h5 class="m-0"><i class="fa fa-history"></i> Historial de Entradas <?php echo !empty($fecha_filtro) ? "del " . date("d/m/Y", strtotime($fecha_filtro)) : "Recientes"; ?></h5>
|
|
<form action="" method="GET" class="d-flex align-items-center" id="filter-form">
|
|
<label for="fecha" class="me-2 mb-0 d-none d-md-block">Filtrar por día:</label>
|
|
<input type="date" name="fecha" id="fecha" class="form-control form-control-sm me-2" value="<?php echo htmlspecialchars($fecha_filtro); ?>">
|
|
<button type="submit" class="btn btn-sm btn-primary">Filtrar</button>
|
|
<?php if (!empty($fecha_filtro)): ?>
|
|
<a href="registro_entrada.php" class="btn btn-sm btn-secondary ms-2">Limpiar</a>
|
|
<?php endif; ?>
|
|
</form>
|
|
</div>
|
|
<div class="card-body">
|
|
<div class="table-responsive">
|
|
<table class="table table-striped table-hover">
|
|
<thead class="thead-light">
|
|
<tr>
|
|
<th>Fecha</th>
|
|
<th>Producto</th>
|
|
<th>Sede</th>
|
|
<th class="text-center">Cantidad</th>
|
|
<th class="text-center">Código</th>
|
|
<th class="text-center">Método</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
<?php if (empty($movements)): ?>
|
|
<tr><td colspan="6" class="text-center">No hay entradas registradas.</td></tr>
|
|
<?php else: ?>
|
|
<?php foreach ($movements as $mov): ?>
|
|
<tr>
|
|
<td><?php echo htmlspecialchars(date("d/m/Y", strtotime($mov['movement_date']))); ?></td>
|
|
<td><?php echo htmlspecialchars($mov['product_name']); ?></td>
|
|
<td><?php echo htmlspecialchars($mov['sede_name']); ?></td>
|
|
<td class="text-center"><?php echo htmlspecialchars($mov['quantity']); ?></td>
|
|
<td class="text-center">
|
|
<small class="text-muted"><?php echo htmlspecialchars($mov['codigo_unico'] ?? '-'); ?></small>
|
|
</td>
|
|
<td class="text-center">
|
|
<small class="text-muted"><?php echo htmlspecialchars($mov['metodo_registro'] ?? 'Manual'); ?></small>
|
|
</td>
|
|
</tr>
|
|
<?php endforeach; ?>
|
|
<?php endif; ?>
|
|
</tbody>
|
|
</table>
|
|
</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 manualForm = document.getElementById('manual-entry-form');
|
|
|
|
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(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());
|
|
}
|
|
|
|
// --- ACTUALIZACIÓN EN TIEMPO REAL ---
|
|
function refreshHistoryAndSummary() {
|
|
const currentUrl = window.location.href;
|
|
fetch(currentUrl)
|
|
.then(response => response.text())
|
|
.then(html => {
|
|
const parser = new DOMParser();
|
|
const doc = parser.parseFromString(html, 'text/html');
|
|
|
|
const newSummary = doc.getElementById('resumen-hoy-container');
|
|
const newHistory = doc.getElementById('historial-container');
|
|
|
|
if (newSummary) {
|
|
document.getElementById('resumen-hoy-container').innerHTML = newSummary.innerHTML;
|
|
}
|
|
if (newHistory) {
|
|
document.getElementById('historial-container').innerHTML = newHistory.innerHTML;
|
|
}
|
|
})
|
|
.catch(error => console.error('Error al actualizar el historial:', error));
|
|
}
|
|
|
|
// --- 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 **
|
|
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 destino.", 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);
|
|
const borradorId = document.getElementById('borrador_id_barcode')?.value;
|
|
if (borradorId) formData.append('borrador_id', borradorId);
|
|
|
|
fetch('registrar_entrada_api.php', { method: 'POST', body: formData })
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.success) {
|
|
showNotification(data.message, true);
|
|
playBeep(true);
|
|
refreshHistoryAndSummary();
|
|
} 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: 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();
|
|
refreshHistoryAndSummary();
|
|
} 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'; ?>
|