Autosave: 20260212-154809

This commit is contained in:
Flatlogic Bot 2026-02-12 15:48:10 +00:00
parent 60510752fa
commit 7ba3e3fac5
12 changed files with 356 additions and 188 deletions

View File

@ -104,6 +104,17 @@ body {
body.sidebar-active .content {
margin-left: 260px;
}
.sidebar .nav {
display: flex;
overflow-x: auto;
white-space: nowrap;
-webkit-overflow-scrolling: touch; /* Smooth scrolling on iOS */
}
.sidebar .nav-item {
flex-basis: auto; /* Allow items to take their natural width */
}
}
@ -293,4 +304,26 @@ h1, .h1 {
.sidebar .submenu .nav-link.active {
color: #fff; /* White color for active sub-item */
font-weight: bold;
}
@media (max-width: 767px) {
.content {
padding: 15px;
}
.card-header, .card-body {
padding: 1rem;
}
h1, .h1 {
font-size: 1.75rem;
}
.table {
font-size: 0.9rem;
}
.table td, .table th {
padding: 0.5rem;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 328 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -0,0 +1,12 @@
CREATE TABLE IF NOT EXISTS `unidades_inventario` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`codigo_unico` VARCHAR(255) NOT NULL UNIQUE,
`producto_id` INT NOT NULL,
`estado` VARCHAR(50) NOT NULL DEFAULT 'Generado', -- Puede ser 'Generado', 'En Almacén', 'Vendido'
`fecha_creacion` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`fecha_ingreso` DATETIME DEFAULT NULL,
`fecha_salida` DATETIME DEFAULT NULL,
`pedido_id` INT DEFAULT NULL,
FOREIGN KEY (`producto_id`) REFERENCES `products`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`pedido_id`) REFERENCES `pedidos`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

97
generar_etiquetas.php Normal file
View File

@ -0,0 +1,97 @@
<?php
$pageTitle = "Generador de Etiquetas";
include 'layout_header.php';
include 'db/config.php';
// Fetch products for the dropdown
$products = [];
try {
$db = db();
$stmt = $db->query("SELECT id, nombre FROM products ORDER BY nombre ASC");
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$_SESSION['error_message'] = "Error al cargar los productos: " . $e->getMessage();
}
$generated_codes = [];
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$producto_id = $_POST['producto_id'] ?? null;
$cantidad = isset($_POST['cantidad']) ? (int)$_POST['cantidad'] : 0;
if ($producto_id && $cantidad > 0 && $cantidad <= 1000) {
$db = db();
try {
$db->beginTransaction();
// Prepare statement for insertion
$stmt = $db->prepare("INSERT INTO unidades_inventario (codigo_unico, producto_id) VALUES (?, ?)");
for ($i = 0; $i < $cantidad; $i++) {
// Generate a more robust unique code
$unique_code = 'FL-' . $producto_id . '-' . strtoupper(uniqid());
$stmt->execute([$unique_code, $producto_id]);
$generated_codes[] = $unique_code;
}
$db->commit();
$_SESSION['success_message'] = 'Se generaron ' . count($generated_codes) . ' códigos exitosamente.';
} catch (PDOException $e) {
$db->rollBack();
$_SESSION['error_message'] = 'Error al generar los códigos: ' . $e->getMessage();
}
} else {
$_SESSION['error_message'] = 'Por favor, seleccione un producto y especifique una cantidad válida (entre 1 y 1000).';
}
}
?>
<div class="card">
<div class="card-header">
<h3 class="card-title">Generar Nuevas Etiquetas de Inventario</h3>
</div>
<div class="card-body">
<form action="generar_etiquetas.php" method="POST">
<div class="row">
<div class="col-md-6 mb-3">
<label for="producto_id" class="form-label">Producto</label>
<select class="form-select" id="producto_id" name="producto_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="col-md-4 mb-3">
<label for="cantidad" class="form-label">Cantidad de Etiquetas</label>
<input type="number" class="form-control" id="cantidad" name="cantidad" min="1" max="1000" required>
</div>
<div class="col-md-2 mb-3 d-flex align-items-end">
<button type="submit" class="btn btn-primary w-100">Generar</button>
</div>
</div>
</form>
</div>
</div>
<?php if (!empty($generated_codes)): ?>
<div class="card mt-4">
<div class="card-header">
<h3 class="card-title">Códigos Generados</h3>
</div>
<div class="card-body">
<p>Guarda estos códigos para imprimirlos y pegarlos en tus paquetes.</p>
<textarea class="form-control" rows="10" readonly><?php echo implode("
", $generated_codes); ?></textarea>
<button class="btn btn-secondary mt-2" onclick="navigator.clipboard.writeText(this.previousElementSibling.value).then(() => alert('¡Códigos copiados!'));">
<i class="fas fa-copy"></i> Copiar Códigos
</button>
</div>
</div>
<?php endif; ?>
<?php include 'layout_footer.php'; ?>

View File

@ -97,6 +97,12 @@ $navItems = [
'text' => 'Inventario General',
'roles' => ['Administrador', 'admin', 'Control Logistico']
],
'generar_etiquetas' => [
'url' => 'generar_etiquetas.php',
'icon' => 'fa-barcode',
'text' => 'Etiquetas',
'roles' => ['Administrador', 'admin', 'Control Logistico']
],
'registro_entrada' => [
'url' => 'registro_entrada.php',
'icon' => 'fa-arrow-circle-down',

View File

@ -0,0 +1,88 @@
<?php
header('Content-Type: application/json');
require_once 'db/config.php';
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'message' => 'Acceso no autorizado.']);
exit();
}
$response = ['success' => false, 'message' => 'Petición inválida.'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$codigo_unico = filter_input(INPUT_POST, 'codigo_unico', FILTER_SANITIZE_STRING);
$sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT);
$movement_date = date('Y-m-d H:i:s');
if ($codigo_unico && $sede_id) {
try {
$pdo = db();
$pdo->beginTransaction();
$stmt_unidad = $pdo->prepare("
SELECT u.*, p.nombre as producto_nombre
FROM unidades_inventario u
JOIN products p ON u.producto_id = p.id
WHERE u.codigo_unico = :codigo_unico
");
$stmt_unidad->execute(['codigo_unico' => $codigo_unico]);
$unidad = $stmt_unidad->fetch(PDO::FETCH_ASSOC);
if (!$unidad) {
throw new Exception("El código de unidad '$codigo_unico' no existe.");
}
if ($unidad['estado'] !== 'En Almacén') {
throw new Exception("La unidad no está en el almacén. Estado actual: " . $unidad['estado']);
}
$update_unidad_stmt = $pdo->prepare("UPDATE unidades_inventario SET estado = 'Vendido', fecha_salida = :fecha_salida WHERE id = :id");
$update_unidad_stmt->execute(['fecha_salida' => $movement_date, 'id' => $unidad['id']]);
$product_id = $unidad['producto_id'];
$quantity = 1;
$stmt_stock = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id");
$stmt_stock->execute(['product_id' => $product_id, 'sede_id' => $sede_id]);
$existing_stock = $stmt_stock->fetch();
if ($existing_stock && $existing_stock['quantity'] > 0) {
$new_quantity = $existing_stock['quantity'] - $quantity;
$update_stock_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id");
$update_stock_stmt->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]);
} else {
if ($existing_stock) {
$update_stock_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = 0 WHERE id = :id");
$update_stock_stmt->execute(['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();
$response = ['success' => true, 'message' => 'Salida de "' . $unidad['producto_nombre'] . '" registrada.'];
} catch (Exception $e) {
$pdo->rollBack();
$response = ['success' => false, 'message' => $e->getMessage()];
}
} else {
$response = ['success' => false, 'message' => 'Faltan datos: código de unidad o sede.'];
}
}
echo json_encode($response);
?>

View File

@ -1,5 +1,5 @@
<?php
$pageTitle = "Agregar Producto al Inventario";
$pageTitle = "Registro de Entrada por Unidad";
require_once 'layout_header.php';
require_once 'db/config.php';
@ -8,31 +8,54 @@ $error = '';
// Lógica para manejar el envío del formulario
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$codigo_unico = filter_input(INPUT_POST, 'codigo_unico', FILTER_SANITIZE_STRING);
$sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT);
$quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT);
$movement_date = filter_input(INPUT_POST, 'movement_date');
$movement_date = date('Y-m-d H:i:s');
if ($product_id && $sede_id && $quantity && $movement_date) {
if ($codigo_unico && $sede_id) {
try {
$pdo = db();
$pdo->beginTransaction();
// 1. Actualizar o insertar en stock_sedes
$stmt = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id");
$stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id]);
$existing_stock = $stmt->fetch();
// 1. Buscar la unidad de inventario
$stmt_unidad = $pdo->prepare("SELECT * FROM unidades_inventario WHERE codigo_unico = :codigo_unico");
$stmt_unidad->execute(['codigo_unico' => $codigo_unico]);
$unidad = $stmt_unidad->fetch(PDO::FETCH_ASSOC);
if (!$unidad) {
throw new Exception("El código de unidad '$codigo_unico' no existe.");
}
if ($unidad['estado'] === 'En Almacén') {
throw new Exception("Esta unidad ya se encuentra en el almacén.");
}
if ($unidad['estado'] === 'Vendido') {
throw new Exception("Esta unidad ya fue vendida y no puede ser ingresada nuevamente.");
}
// 2. Actualizar el estado de la unidad
$update_unidad_stmt = $pdo->prepare("UPDATE unidades_inventario SET estado = 'En Almacén', fecha_ingreso = :fecha_ingreso WHERE id = :id");
$update_unidad_stmt->execute(['fecha_ingreso' => $movement_date, 'id' => $unidad['id']]);
$product_id = $unidad['producto_id'];
$quantity = 1; // Siempre es 1 para el inventario serializado
// 3. Actualizar o insertar en stock_sedes (reutilizando lógica anterior)
$stmt_stock = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id");
$stmt_stock->execute(['product_id' => $product_id, 'sede_id' => $sede_id]);
$existing_stock = $stmt_stock->fetch();
if ($existing_stock) {
$new_quantity = $existing_stock['quantity'] + $quantity;
$update_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id");
$update_stmt->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]);
$update_stock_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id");
$update_stock_stmt->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]);
} else {
$insert_stmt = $pdo->prepare("INSERT INTO stock_sedes (product_id, sede_id, quantity) VALUES (:product_id, :sede_id, :quantity)");
$insert_stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id, 'quantity' => $quantity]);
$insert_stock_stmt = $pdo->prepare("INSERT INTO stock_sedes (product_id, sede_id, quantity) VALUES (:product_id, :sede_id, :quantity)");
$insert_stock_stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id, 'quantity' => $quantity]);
}
// 2. Insertar en el historial de movimientos
// 4. Insertar en el historial de movimientos
$history_stmt = $pdo->prepare(
"INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date)
VALUES (:product_id, :sede_id, :quantity, 'entrada', :movement_date)"
@ -45,29 +68,25 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
]);
$pdo->commit();
$message = "¡Inventario actualizado y movimiento registrado correctamente!";
$message = "Unidad '$codigo_unico' registrada en el inventario correctamente.";
} catch (PDOException $e) {
} catch (Exception $e) {
$pdo->rollBack();
$error = "Error al actualizar el inventario: " . $e->getMessage();
$error = "Error: " . $e->getMessage();
}
} else {
$error = "Por favor, complete todos los campos del formulario, incluyendo la fecha.";
$error = "Por favor, escanee un código y seleccione una sede.";
}
}
// Obtener productos y sedes para los dropdowns
$products = [];
// Obtener sedes para el dropdown
$sedes = [];
try {
$pdo = db();
$products_stmt = $pdo->query("SELECT id, nombre FROM products ORDER BY nombre ASC");
$products = $products_stmt->fetchAll(PDO::FETCH_ASSOC);
$sedes_stmt = $pdo->query("SELECT id, nombre FROM sedes ORDER BY nombre ASC");
$sedes = $sedes_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error = "Error al cargar datos: " . $e->getMessage();
$error = "Error al cargar las sedes: " . $e->getMessage();
}
?>
@ -76,44 +95,28 @@ try {
<div class="col-lg-6 mx-auto">
<?php if ($message): ?>
<div class="alert alert-success" role="alert">
<?php echo htmlspecialchars($message); ?>
</div>
<div class="alert alert-success" role="alert" id="form-message"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger" role="alert">
<?php echo htmlspecialchars($error); ?>
</div>
<div class="alert alert-danger" role="alert" id="form-error"><?php echo htmlspecialchars($error); ?></div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<i class="fa fa-plus"></i> Registro de Entrada de Producto
<i class="fa fa-barcode"></i> Registro de Entrada por Unidad
</div>
<div class="card-body">
<form action="registro_entrada.php" method="post">
<form action="registro_entrada.php" method="post" id="entrada-form">
<div class="mb-3">
<label for="movement_date" class="form-label">Fecha de Entrada</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="producto" class="form-label">Producto</label>
<button type="button" class="btn btn-info btn-sm float-end" data-bs-toggle="modal" data-bs-target="#scannerModal">
<i class="fa fa-camera"></i> Escanear
</button>
<select class="form-select" id="producto" 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="cantidad" class="form-label">Cantidad</label>
<input type="number" class="form-control" id="cantidad" name="quantity" min="1" required>
<label for="codigo_unico" class="form-label">Código de Unidad</label>
<div class="input-group">
<input type="text" class="form-control" id="codigo_unico" name="codigo_unico" required autofocus>
<button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#scannerModal">
<i class="fa fa-camera"></i>
</button>
</div>
</div>
<div class="mb-3">
<label for="sede" class="form-label">Sede de Destino</label>
<select class="form-select" id="sede" name="sede_id" required>
@ -125,7 +128,7 @@ try {
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary w-100"> <i class="fa fa-plus-circle"></i> Agregar al Inventario</button>
<button type="submit" class="btn btn-primary w-100"> <i class="fa fa-plus-circle"></i> Registrar Entrada</button>
</form>
</div>
</div>
@ -138,7 +141,7 @@ try {
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="scannerModalLabel">Escanear Código de Barras</h5>
<h5 class="modal-title" id="scannerModalLabel">Escanear Código de Unidad</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
@ -154,74 +157,54 @@ try {
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
if (typeof bootstrap === 'undefined') {
console.error('Bootstrap no está cargado. El modal del escáner no funcionará.');
const codigoUnicoInput = document.getElementById('codigo_unico');
const form = document.getElementById('entrada-form');
if(codigoUnicoInput) {
codigoUnicoInput.focus();
}
if (form) {
codigoUnicoInput.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
form.submit();
}
});
}
if (typeof bootstrap === 'undefined' || typeof Html5Qrcode === 'undefined') {
console.error('Bootstrap o Html5Qrcode no están cargados.');
return;
}
const scannerModalElement = document.getElementById('scannerModal');
if (!scannerModalElement) {
console.error('El elemento del modal del escáner no se encontró.');
return;
}
if (!scannerModalElement) return;
const scannerModal = new bootstrap.Modal(scannerModalElement);
const html5QrCode = new Html5Qrcode("reader");
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
html5QrCode.stop().then((ignore) => {
console.log("QR Code scanning stopped.");
}).catch((err) => {
console.error("Failed to stop QR Code scanning.", err);
});
html5QrCode.stop().then(ignore => {}).catch(err => console.log("Failed to stop scanner"));
scannerModal.hide();
fetch(`get_product_details.php?id=${decodedText}`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.success && data.product) {
const productSelect = document.getElementById('producto');
productSelect.value = data.product.id;
const productName = data.product.nombre || 'desconocido';
alert(`Producto seleccionado: ${productName}`);
} else {
alert('Error: ' + (data.message || 'Producto no encontrado.'));
}
})
.catch(error => {
console.error('Error al buscar los detalles del producto:', error);
alert('Hubo un error al procesar el código de barras. Verifique la consola para más detalles.');
});
if(codigoUnicoInput) {
codigoUnicoInput.value = decodedText;
codigoUnicoInput.focus();
}
};
const config = { fps: 10, qrbox: { width: 250, height: 250 } };
scannerModalElement.addEventListener('shown.bs.modal', function () {
html5QrCode.start(
{ facingMode: "environment" },
config,
qrCodeSuccessCallback,
(errorMessage) => {
// console.log("QR Code no match.", errorMessage);
})
.catch((err) => {
console.error("No se pudo iniciar el escáner de QR.", err);
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback)
.catch(err => {
alert("Error al iniciar la cámara. Asegúrese de dar permisos.");
});
});
scannerModalElement.addEventListener('hidden.bs.modal', function () {
html5QrCode.stop().catch(err => {
// Ignorar error si el escáner ya estaba detenido
});
html5QrCode.stop().catch(err => {});
});
});
</script>

View File

@ -117,69 +117,39 @@ document.addEventListener('DOMContentLoaded', (event) => {
// --- LÓGICA DE SONIDO (WEB AUDIO API) ---
let audioCtx;
// Esta función inicializa y DESBLOQUEA el audio.
// Debe ser llamada por una interacción directa del usuario (click o touch).
function unlockAudio() {
if (audioCtx) {
if (audioCtx.state === 'suspended') {
audioCtx.resume().then(() => {
console.log("AudioContext reanudado exitosamente.");
}).catch(e => console.error("Error al reanudar AudioContext:", e));
}
return;
function wakeUpAudio() {
if (!audioCtx) {
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
} catch (e) { console.error("Web Audio API no es soportada.", e); return; }
}
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// La primera vez, resume() es crucial para navegadores que inician en estado 'suspended'.
audioCtx.resume().then(() => {
console.log("AudioContext inicializado y desbloqueado.");
});
} catch (e) {
console.error("Web Audio API no es soportada en este navegador.", e);
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
}
// Asignamos la función de desbloqueo a los primeros eventos de interacción del usuario.
// `{ once: true }` asegura que solo se ejecute una vez.
document.body.addEventListener('click', unlockAudio, { once: true });
document.body.addEventListener('touchstart', unlockAudio, { once: true });
document.body.addEventListener('click', wakeUpAudio, { once: true });
document.body.addEventListener('touchstart', wakeUpAudio, { once: true });
function playBeep() {
if (!audioCtx || audioCtx.state !== 'running') {
console.warn("AudioContext no está listo o desbloqueado. No se puede reproducir sonido.");
// Intento de último recurso (puede no funcionar si no es por gesto de usuario)
unlockAudio();
return;
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; // Volumen bajo para no ser molesto
oscillator.frequency.value = 880; // Frecuencia del tono (un La agudo)
oscillator.type = 'sine'; // Tipo de onda
gainNode.gain.value = 0.1;
oscillator.frequency.value = 880;
oscillator.type = 'sine';
oscillator.start();
setTimeout(() => {
oscillator.stop();
}, 150); // Duración del sonido en milisegundos
setTimeout(() => oscillator.stop(), 150);
}
// --- LÓGICA PARA MÓVIL ---
if (isMobile) {
if(sedeContainer) {
sedeContainer.style.display = 'none'; // Ocultar el selector de sede
}
if(sedeSelect && almacenPrincipalId) {
sedeSelect.value = almacenPrincipalId; // Seleccionar ALMACEN PRINCIPAL por defecto
}
console.log('Modo móvil activado. Sede por defecto: ALMACEN PRINCIPAL');
if(sedeContainer) sedeContainer.style.display = 'none';
if(sedeSelect && almacenPrincipalId) sedeSelect.value = almacenPrincipalId;
}
// --- INICIALIZACIÓN DE CÁMARA ---
@ -187,6 +157,7 @@ document.addEventListener('DOMContentLoaded', (event) => {
let html5QrCode;
function onScanSuccess(decodedText, decodedResult) {
playBeep();
barcodeInput.value = decodedText;
const changeEvent = new Event('change');
barcodeInput.dispatchEvent(changeEvent);
@ -194,18 +165,17 @@ document.addEventListener('DOMContentLoaded', (event) => {
if(modal) modal.hide();
}
function onScanFailure(error) { /* No hacer nada */ }
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, onScanFailure)
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 => console.error("No se pudo detener la cámara.", err));
html5QrCode.stop().catch(err => {});
}
});
@ -237,10 +207,10 @@ document.addEventListener('DOMContentLoaded', (event) => {
this.disabled = true;
const sedeId = sedeSelect.value;
const movementDate = dateInput.value;
const movementDate = dateInput.value; // Although not used by new API, good to have if needed later
if (!sedeId || !movementDate) {
showNotification("Por favor, seleccione una sede y una fecha.", false);
if (!sedeId) {
showNotification("Por favor, seleccione una sede de origen.", false);
this.value = '';
this.disabled = false;
processing = false;
@ -248,40 +218,12 @@ document.addEventListener('DOMContentLoaded', (event) => {
return;
}
fetch(`get_product_details.php?codigo_barras=${encodeURIComponent(barcodeValue)}`)
.then(response => response.json())
.then(data => {
if (data.success && data.product) {
playBeep(); // <-- LLAMADA AL SONIDO AQUÍ
if (confirm(`¿Registrar salida de "${data.product.nombre}"?`)) {
registerProductExit(data.product.id, sedeId, movementDate);
} else {
console.log('Salida cancelada por el usuario.');
}
} else {
throw new Error(data.message || 'Producto no encontrado.');
}
})
.catch(error => {
showNotification(error.message, false);
})
.finally(() => {
this.value = '';
this.disabled = false;
processing = false;
this.focus();
});
});
function registerProductExit(productId, sedeId, movementDate) {
const formData = new FormData();
formData.append('product_id', productId);
formData.append('codigo_unico', barcodeValue);
formData.append('sede_id', sedeId);
formData.append('movement_date', movementDate);
fetch('registrar_salida_api.php', {
fetch('registrar_salida_unidad_api.php', {
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body: formData
})
.then(response => response.json())
@ -289,18 +231,23 @@ document.addEventListener('DOMContentLoaded', (event) => {
if (data.success) {
showNotification(data.message, true);
} else {
throw new Error(data.message || 'Error al registrar la salida.');
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) => {
// Si el clic no es en un input, select, botón o link, re-enfocar el campo de escaneo
if (!['INPUT', 'SELECT', 'BUTTON', 'A'].includes(e.target.tagName) && !e.target.closest('button, a')) {
barcodeInput.focus();
}

View File

@ -1,2 +1,4 @@
[2026-02-11 23:38:51] Intento fallido de búsqueda con SKU: 4
[2026-02-12 00:29:21] Intento fallido de búsqueda con SKU: $
[2026-02-12 07:15:26] Intento fallido de búsqueda con SKU: .BX
[2026-02-12 07:17:16] Intento fallido de búsqueda con SKU: