319 lines
13 KiB
PHP
319 lines
13 KiB
PHP
<?php
|
|
$pageTitle = "Registro de Salida de Producto";
|
|
require_once 'layout_header.php';
|
|
require_once 'db/config.php';
|
|
|
|
$message = '';
|
|
$error = '';
|
|
|
|
// Esta sección ahora solo se usará para las respuestas AJAX del escáner
|
|
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
|
|
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
|
|
$sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT);
|
|
$movement_date = filter_input(INPUT_POST, 'movement_date');
|
|
$quantity = 1; // Siempre es 1 al escanear
|
|
|
|
if ($product_id && $sede_id && $movement_date) {
|
|
try {
|
|
$pdo = db();
|
|
$pdo->beginTransaction();
|
|
|
|
$stmt = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id FOR UPDATE");
|
|
$stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id]);
|
|
$existing_stock = $stmt->fetch();
|
|
|
|
if ($existing_stock) {
|
|
$new_quantity = $existing_stock['quantity'] - $quantity;
|
|
if ($new_quantity < 0) {
|
|
$error = "No hay stock para registrar la salida. Stock actual: " . $existing_stock['quantity'];
|
|
$pdo->rollBack();
|
|
} else {
|
|
$update_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id");
|
|
$update_stmt->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]);
|
|
|
|
$history_stmt = $pdo->prepare(
|
|
"INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date)
|
|
VALUES (:product_id, :sede_id, :quantity, 'salida', :movement_date)"
|
|
);
|
|
$history_stmt->execute([
|
|
'product_id' => $product_id,
|
|
'sede_id' => $sede_id,
|
|
'quantity' => $quantity,
|
|
'movement_date' => $movement_date
|
|
]);
|
|
|
|
$pdo->commit();
|
|
$stmt_prod_name = $pdo->prepare("SELECT nombre FROM products WHERE id = :id");
|
|
$stmt_prod_name->execute(['id' => $product_id]);
|
|
$product_name = $stmt_prod_name->fetchColumn();
|
|
$message = "Salida de 1 unidad de '{$product_name}' registrada. Stock restante: {$new_quantity}.";
|
|
}
|
|
} else {
|
|
$error = "No hay stock registrado para este producto en la sede seleccionada.";
|
|
$pdo->rollBack();
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
if ($pdo && $pdo->inTransaction()) {
|
|
$pdo->rollBack();
|
|
}
|
|
$error = "Error al actualizar el inventario: " . $e->getMessage();
|
|
}
|
|
} else {
|
|
$error = "Faltan datos para registrar la salida (producto, sede o fecha).";
|
|
}
|
|
|
|
// Devolvemos JSON y terminamos la ejecución
|
|
header('Content-Type: application/json');
|
|
if ($error) {
|
|
echo json_encode(['success' => false, 'message' => $error]);
|
|
} else {
|
|
echo json_encode(['success' => true, 'message' => $message]);
|
|
}
|
|
exit;
|
|
}
|
|
|
|
// 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);
|
|
} 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;"> <!-- Evita el envío tradicional del formulario -->
|
|
<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">
|
|
<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 if (trim(strtolower($sede['nombre'])) === 'almacen principal') echo ' selected'; ?>><?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>
|
|
<input type="text" class="form-control form-control-lg" id="barcode-input" placeholder="Escanee el producto aquí" autofocus>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Tabla de productos escaneados -->
|
|
<div class="col-lg-6 mx-auto mt-4">
|
|
<div class="card">
|
|
<div class="card-header">
|
|
<i class="fa fa-check-circle"></i> Productos Registrados
|
|
</div>
|
|
<div class="card-body">
|
|
<div class="table-responsive">
|
|
<table class="table table-striped table-hover">
|
|
<thead>
|
|
<tr>
|
|
<th>Producto</th>
|
|
<th>SKU</th>
|
|
<th>Estado</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="scanned-products-tbody">
|
|
<!-- Las filas se añadirán aquí dinámicamente -->
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', (event) => {
|
|
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 tableBody = document.getElementById('scanned-products-tbody');
|
|
let audioContext;
|
|
let processing = false; // Flag para evitar escaneos múltiples
|
|
|
|
// --- Inicializar AudioContext ---
|
|
function initAudioContext() {
|
|
if (!audioContext) {
|
|
try {
|
|
audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
|
console.log("AudioContext inicializado.");
|
|
} catch (e) {
|
|
console.error("Web Audio API no es soportada.", e);
|
|
}
|
|
}
|
|
}
|
|
// El usuario debe interactuar con la página para iniciar el audio
|
|
document.body.addEventListener('click', initAudioContext, { once: true });
|
|
document.body.addEventListener('keydown', initAudioContext, { once: true });
|
|
|
|
|
|
// --- Funciones de ayuda ---
|
|
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 toastElement = document.getElementById(toastId);
|
|
const toast = new bootstrap.Toast(toastElement, { delay: 5000 });
|
|
toast.show();
|
|
toastElement.addEventListener('hidden.bs.toast', () => toastElement.remove());
|
|
}
|
|
|
|
function playBeep(success = true) {
|
|
if (!audioContext) return;
|
|
try {
|
|
const oscillator = audioContext.createOscillator();
|
|
const gainNode = audioContext.createGain();
|
|
oscillator.connect(gainNode);
|
|
gainNode.connect(audioContext.destination);
|
|
oscillator.type = success ? 'sine' : 'square';
|
|
oscillator.frequency.setValueAtTime(success ? 880 : 440, audioContext.currentTime);
|
|
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
|
|
oscillator.start();
|
|
oscillator.stop(audioContext.currentTime + 0.1);
|
|
} catch (e) {
|
|
console.error("Error al reproducir sonido.", e);
|
|
}
|
|
}
|
|
|
|
// --- Lógica principal del escáner ---
|
|
barcodeInput.addEventListener('change', function() {
|
|
const barcodeValue = this.value.trim();
|
|
if (barcodeValue === '' || processing) {
|
|
return;
|
|
}
|
|
|
|
processing = true;
|
|
this.disabled = true; // Bloquear input mientras se procesa
|
|
|
|
const sede_id = sedeSelect.value;
|
|
const movement_date = dateInput.value;
|
|
|
|
if (!sede_id || !movement_date) {
|
|
showNotification("Por favor, seleccione una sede y una fecha antes de escanear.", false);
|
|
playBeep(false);
|
|
this.value = '';
|
|
this.disabled = false;
|
|
processing = false;
|
|
this.focus();
|
|
return;
|
|
}
|
|
|
|
// Añadir fila a la tabla
|
|
const newRow = tableBody.insertRow(0);
|
|
const cellProduct = newRow.insertCell(0);
|
|
const cellSku = newRow.insertCell(1);
|
|
const cellStatus = newRow.insertCell(2);
|
|
|
|
cellProduct.textContent = 'Buscando...';
|
|
cellSku.textContent = barcodeValue;
|
|
cellStatus.innerHTML = '<span class="badge bg-warning text-dark">Procesando...</span>';
|
|
|
|
fetch(`get_product_details.php?codigo_barras=${encodeURIComponent(barcodeValue)}`)
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.success && data.product) {
|
|
cellProduct.textContent = data.product.nombre;
|
|
cellSku.textContent = data.product.sku;
|
|
|
|
const formData = new FormData();
|
|
formData.append('product_id', data.product.id);
|
|
formData.append('sede_id', sede_id);
|
|
formData.append('movement_date', movement_date);
|
|
|
|
return fetch('registro_salida.php', {
|
|
method: 'POST',
|
|
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
body: formData
|
|
});
|
|
} else {
|
|
throw new Error(data.message || 'Producto no encontrado.');
|
|
}
|
|
})
|
|
.then(response => response.json())
|
|
.then(result => {
|
|
showNotification(result.message, result.success);
|
|
if (result.success) {
|
|
playBeep(true);
|
|
cellStatus.innerHTML = '<span class="badge bg-success">Registrado</span>';
|
|
} else {
|
|
playBeep(false);
|
|
cellStatus.innerHTML = `<span class="badge bg-danger" title="${result.message}">Error</span>`;
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error en el proceso de escaneo:', error);
|
|
showNotification(error.message, false);
|
|
playBeep(false);
|
|
cellProduct.textContent = 'Error de Búsqueda';
|
|
cellStatus.innerHTML = `<span class="badge bg-danger" title="${error.message}">Fallo</span>`;
|
|
})
|
|
.finally(() => {
|
|
// Limpiar y re-enfocar el input para el siguiente escaneo
|
|
this.value = '';
|
|
this.disabled = false;
|
|
processing = false;
|
|
this.focus();
|
|
});
|
|
});
|
|
|
|
// Asegurarse de que el campo de texto siempre tenga el foco
|
|
barcodeInput.focus();
|
|
document.body.addEventListener('click', (e) => {
|
|
// Si el clic no es en un input o select, re-enfocar el campo de escaneo
|
|
if (!['INPUT', 'SELECT', 'BUTTON'].includes(e.target.tagName)) {
|
|
barcodeInput.focus();
|
|
}
|
|
});
|
|
});
|
|
</script>
|
|
|
|
<?php require_once 'layout_footer.php'; ?>
|