317 lines
14 KiB
PHP
317 lines
14 KiB
PHP
<?php
|
|
$pageTitle = "Registro de Salida de Producto";
|
|
require_once 'layout_header.php';
|
|
require_once 'db/config.php';
|
|
|
|
$message = '';
|
|
$error = '';
|
|
|
|
// Lógica para manejar el envío del formulario (tanto normal como AJAX)
|
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
|
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
|
|
$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');
|
|
|
|
if ($product_id && $sede_id && $quantity && $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 suficiente 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 = "Por favor, complete todos los campos del formulario, incluyendo la fecha y la sede.";
|
|
}
|
|
|
|
// Si es una petición AJAX, devolvemos JSON y terminamos la ejecución
|
|
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
|
|
header('Content-Type: application/json');
|
|
if ($error) {
|
|
echo json_encode(['success' => false, 'message' => $error]);
|
|
} else {
|
|
echo json_encode(['success' => true, 'message' => $message]);
|
|
}
|
|
exit;
|
|
}
|
|
}
|
|
|
|
// Obtener productos y sedes para los dropdowns
|
|
$products = [];
|
|
$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();
|
|
}
|
|
?>
|
|
|
|
<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 ($message && empty($_SERVER['HTTP_X_REQUESTED_WITH'])): ?>
|
|
<div class="alert alert-success" role="alert">
|
|
<?php echo htmlspecialchars($message); ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
<?php if ($error && empty($_SERVER['HTTP_X_REQUESTED_WITH'])): ?>
|
|
<div class="alert alert-danger" role="alert">
|
|
<?php echo htmlspecialchars($error); ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
|
|
<div class="card">
|
|
<div class="card-header">
|
|
<i class="fa fa-minus"></i> Registro de Salida de Producto
|
|
</div>
|
|
<div class="card-body">
|
|
<form id="salida-form" action="registro_salida.php" method="post">
|
|
<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="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 a Retirar (manual)</label>
|
|
<input type="number" class="form-control" id="cantidad" name="quantity" min="1" required>
|
|
</div>
|
|
|
|
<button type="submit" class="btn btn-primary w-100"> <i class="fa fa-minus-circle"></i> Registrar Salida Manual</button>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Modal para el Escáner -->
|
|
<div class="modal fade" id="scannerModal" tabindex="-1" aria-labelledby="scannerModalLabel" aria-hidden="true">
|
|
<div class="modal-dialog">
|
|
<div class="modal-content">
|
|
<div class="modal-header">
|
|
<h5 class="modal-title" id="scannerModalLabel">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" style="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" type="text/javascript"></script>
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', (event) => {
|
|
if (typeof bootstrap === 'undefined') {
|
|
console.error('Bootstrap no está cargado.');
|
|
return;
|
|
}
|
|
|
|
let audioContext;
|
|
|
|
// --- 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() {
|
|
if (!audioContext) {
|
|
console.warn("AudioContext no inicializado. El sonido no se reproducirá.");
|
|
return;
|
|
}
|
|
try {
|
|
const oscillator = audioContext.createOscillator();
|
|
const gainNode = audioContext.createGain();
|
|
oscillator.connect(gainNode);
|
|
gainNode.connect(audioContext.destination);
|
|
oscillator.type = 'sine';
|
|
oscillator.frequency.setValueAtTime(880, audioContext.currentTime);
|
|
gainNode.gain.setValueAtTime(0.5, audioContext.currentTime);
|
|
oscillator.start();
|
|
oscillator.stop(audioContext.currentTime + 0.1);
|
|
} catch (e) {
|
|
console.error("Error al reproducir el sonido con Web Audio API.", e);
|
|
}
|
|
}
|
|
|
|
// --- Lógica del escáner ---
|
|
|
|
const scannerModalElement = document.getElementById('scannerModal');
|
|
if (!scannerModalElement) return;
|
|
|
|
const scannerModal = new bootstrap.Modal(scannerModalElement);
|
|
const html5QrCode = new Html5Qrcode("reader");
|
|
|
|
// Inicializar AudioContext con la interacción del usuario
|
|
document.querySelector('[data-bs-target="#scannerModal"]').addEventListener('click', () => {
|
|
if (!audioContext) {
|
|
try {
|
|
audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
|
console.log("AudioContext inicializado.");
|
|
} catch (e) {
|
|
console.error("Web Audio API no es soportada en este navegador.", e);
|
|
}
|
|
}
|
|
});
|
|
|
|
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
|
|
playBeep();
|
|
html5QrCode.stop().catch(err => {});
|
|
scannerModal.hide();
|
|
|
|
const sede_id = document.getElementById('sede').value;
|
|
const movement_date = document.getElementById('movement_date').value;
|
|
|
|
if (!sede_id) {
|
|
showNotification("Por favor, seleccione una sede de origen antes de escanear.", false);
|
|
return;
|
|
}
|
|
|
|
const cleanDecodedText = decodedText.trim();
|
|
fetch(`get_product_details.php?id=${cleanDecodedText}`)
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.success && data.product) {
|
|
const formData = new FormData();
|
|
formData.append('product_id', data.product.id);
|
|
formData.append('quantity', '1');
|
|
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 con el código escaneado.');
|
|
}
|
|
})
|
|
.then(response => response.json())
|
|
.then(result => {
|
|
showNotification(result.message, result.success);
|
|
})
|
|
.catch(error => {
|
|
console.error('Error en el proceso de escaneo y registro:', error);
|
|
showNotification(error.message, false);
|
|
});
|
|
};
|
|
|
|
const config = {
|
|
fps: 10,
|
|
qrbox: { width: 250, height: 250 },
|
|
experimentalFeatures: {
|
|
useBarCodeDetectorIfSupported: false
|
|
}
|
|
};
|
|
|
|
scannerModalElement.addEventListener('shown.bs.modal', function () {
|
|
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback, (errorMessage) => {})
|
|
.catch((err) => {
|
|
showNotification("Error al iniciar la cámara. Asegúrese de dar permisos.", false);
|
|
});
|
|
});
|
|
|
|
scannerModalElement.addEventListener('hidden.bs.modal', function () {
|
|
html5QrCode.stop().catch(err => {});
|
|
});
|
|
});
|
|
</script>
|
|
|
|
<?php require_once 'layout_footer.php'; ?>
|