212 lines
8.7 KiB
PHP
212 lines
8.7 KiB
PHP
<?php
|
|
$pageTitle = "Registro de Entrada por Unidad";
|
|
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") {
|
|
$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();
|
|
|
|
// 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_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_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]);
|
|
}
|
|
|
|
// 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)"
|
|
);
|
|
$history_stmt->execute([
|
|
'product_id' => $product_id,
|
|
'sede_id' => $sede_id,
|
|
'quantity' => $quantity,
|
|
'movement_date' => $movement_date
|
|
]);
|
|
|
|
$pdo->commit();
|
|
$message = "Unidad '$codigo_unico' registrada en el inventario correctamente.";
|
|
|
|
} catch (Exception $e) {
|
|
$pdo->rollBack();
|
|
$error = "Error: " . $e->getMessage();
|
|
}
|
|
} else {
|
|
$error = "Por favor, escanee un código y seleccione una sede.";
|
|
}
|
|
}
|
|
|
|
// 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 = "Error al cargar las sedes: " . $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" id="form-message"><?php echo htmlspecialchars($message); ?></div>
|
|
<?php endif; ?>
|
|
<?php if ($error): ?>
|
|
<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-barcode"></i> Registro de Entrada por Unidad
|
|
</div>
|
|
<div class="card-body">
|
|
<form action="registro_entrada.php" method="post" id="entrada-form">
|
|
<div class="mb-3">
|
|
<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>
|
|
<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-plus-circle"></i> Registrar Entrada</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 Unidad</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) => {
|
|
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) return;
|
|
|
|
const scannerModal = new bootstrap.Modal(scannerModalElement);
|
|
const html5QrCode = new Html5Qrcode("reader");
|
|
|
|
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
|
|
html5QrCode.stop().then(ignore => {}).catch(err => console.log("Failed to stop scanner"));
|
|
scannerModal.hide();
|
|
|
|
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)
|
|
.catch(err => {
|
|
alert("Error al iniciar la cámara. Asegúrese de dar permisos.");
|
|
});
|
|
});
|
|
|
|
scannerModalElement.addEventListener('hidden.bs.modal', function () {
|
|
html5QrCode.stop().catch(err => {});
|
|
});
|
|
});
|
|
</script>
|
|
|
|
<?php require_once 'layout_footer.php'; ?>
|