236 lines
9.9 KiB
PHP
236 lines
9.9 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
|
|
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();
|
|
|
|
// 1. Verificar y actualizar stock 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();
|
|
|
|
if ($existing_stock) {
|
|
$new_quantity = $existing_stock['quantity'] - $quantity;
|
|
if ($new_quantity < 0) {
|
|
$error = "No hay suficiente stock para registrar la salida.";
|
|
$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']]);
|
|
|
|
// 2. 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, 'salida', :movement_date)"
|
|
);
|
|
$history_stmt->execute([
|
|
'product_id' => $product_id,
|
|
'sede_id' => $sede_id,
|
|
'quantity' => $quantity,
|
|
'movement_date' => $movement_date
|
|
]);
|
|
|
|
$pdo->commit();
|
|
$message = "¡Inventario actualizado y movimiento registrado correctamente!";
|
|
}
|
|
} else {
|
|
$error = "No hay stock registrado para este producto en la sede seleccionada.";
|
|
$pdo->rollBack();
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
if ($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.";
|
|
}
|
|
}
|
|
|
|
// 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">
|
|
|
|
<?php if ($message): ?>
|
|
<div class="alert alert-success" role="alert">
|
|
<?php echo htmlspecialchars($message); ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
<?php if ($error): ?>
|
|
<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 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="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</label>
|
|
<input type="number" class="form-control" id="cantidad" name="quantity" min="1" 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 echo htmlspecialchars($sede['nombre']); ?>
|
|
</option>
|
|
<?php endforeach; ?>
|
|
</select>
|
|
</div>
|
|
<button type="submit" class="btn btn-primary w-100"> <i class="fa fa-minus-circle"></i> Registrar Salida</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. El modal del escáner no funcionará.');
|
|
return;
|
|
}
|
|
|
|
const scannerModalElement = document.getElementById('scannerModal');
|
|
if (!scannerModalElement) {
|
|
console.error('El elemento del modal del escáner no se encontró.');
|
|
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);
|
|
});
|
|
|
|
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.');
|
|
});
|
|
};
|
|
|
|
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);
|
|
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
|
|
});
|
|
});
|
|
});
|
|
</script>
|
|
|
|
<?php require_once 'layout_footer.php'; ?>
|