Autosave: 20260212-154809
This commit is contained in:
parent
60510752fa
commit
7ba3e3fac5
@ -104,6 +104,17 @@ body {
|
|||||||
body.sidebar-active .content {
|
body.sidebar-active .content {
|
||||||
margin-left: 260px;
|
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 */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -294,3 +305,25 @@ h1, .h1 {
|
|||||||
color: #fff; /* White color for active sub-item */
|
color: #fff; /* White color for active sub-item */
|
||||||
font-weight: bold;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
assets/uploads/vouchers/698de35a83aff-CAPTURA 3.png
Normal file
BIN
assets/uploads/vouchers/698de35a83aff-CAPTURA 3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 239 KiB |
BIN
assets/uploads/vouchers/698de4145d43c-CAPTURA 4.png
Normal file
BIN
assets/uploads/vouchers/698de4145d43c-CAPTURA 4.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 328 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
BIN
assets/uploads/vouchers/698ded43bcdce-ENTREGADO.png
Normal file
BIN
assets/uploads/vouchers/698ded43bcdce-ENTREGADO.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
12
db/migrations/062_create_unidades_inventario_table.sql
Normal file
12
db/migrations/062_create_unidades_inventario_table.sql
Normal 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
97
generar_etiquetas.php
Normal 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'; ?>
|
||||||
@ -97,6 +97,12 @@ $navItems = [
|
|||||||
'text' => 'Inventario General',
|
'text' => 'Inventario General',
|
||||||
'roles' => ['Administrador', 'admin', 'Control Logistico']
|
'roles' => ['Administrador', 'admin', 'Control Logistico']
|
||||||
],
|
],
|
||||||
|
'generar_etiquetas' => [
|
||||||
|
'url' => 'generar_etiquetas.php',
|
||||||
|
'icon' => 'fa-barcode',
|
||||||
|
'text' => 'Etiquetas',
|
||||||
|
'roles' => ['Administrador', 'admin', 'Control Logistico']
|
||||||
|
],
|
||||||
'registro_entrada' => [
|
'registro_entrada' => [
|
||||||
'url' => 'registro_entrada.php',
|
'url' => 'registro_entrada.php',
|
||||||
'icon' => 'fa-arrow-circle-down',
|
'icon' => 'fa-arrow-circle-down',
|
||||||
|
|||||||
88
registrar_salida_unidad_api.php
Normal file
88
registrar_salida_unidad_api.php
Normal 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);
|
||||||
|
?>
|
||||||
@ -1,5 +1,5 @@
|
|||||||
<?php
|
<?php
|
||||||
$pageTitle = "Agregar Producto al Inventario";
|
$pageTitle = "Registro de Entrada por Unidad";
|
||||||
require_once 'layout_header.php';
|
require_once 'layout_header.php';
|
||||||
require_once 'db/config.php';
|
require_once 'db/config.php';
|
||||||
|
|
||||||
@ -8,31 +8,54 @@ $error = '';
|
|||||||
|
|
||||||
// Lógica para manejar el envío del formulario
|
// Lógica para manejar el envío del formulario
|
||||||
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
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);
|
$sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT);
|
||||||
$quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT);
|
$movement_date = date('Y-m-d H:i:s');
|
||||||
$movement_date = filter_input(INPUT_POST, 'movement_date');
|
|
||||||
|
|
||||||
if ($product_id && $sede_id && $quantity && $movement_date) {
|
if ($codigo_unico && $sede_id) {
|
||||||
try {
|
try {
|
||||||
$pdo = db();
|
$pdo = db();
|
||||||
$pdo->beginTransaction();
|
$pdo->beginTransaction();
|
||||||
|
|
||||||
// 1. Actualizar o insertar en stock_sedes
|
// 1. Buscar la unidad de inventario
|
||||||
$stmt = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id");
|
$stmt_unidad = $pdo->prepare("SELECT * FROM unidades_inventario WHERE codigo_unico = :codigo_unico");
|
||||||
$stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id]);
|
$stmt_unidad->execute(['codigo_unico' => $codigo_unico]);
|
||||||
$existing_stock = $stmt->fetch();
|
$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) {
|
if ($existing_stock) {
|
||||||
$new_quantity = $existing_stock['quantity'] + $quantity;
|
$new_quantity = $existing_stock['quantity'] + $quantity;
|
||||||
$update_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id");
|
$update_stock_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->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]);
|
||||||
} else {
|
} else {
|
||||||
$insert_stmt = $pdo->prepare("INSERT INTO stock_sedes (product_id, sede_id, quantity) VALUES (:product_id, :sede_id, :quantity)");
|
$insert_stock_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->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(
|
$history_stmt = $pdo->prepare(
|
||||||
"INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date)
|
"INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date)
|
||||||
VALUES (:product_id, :sede_id, :quantity, 'entrada', :movement_date)"
|
VALUES (:product_id, :sede_id, :quantity, 'entrada', :movement_date)"
|
||||||
@ -45,29 +68,25 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
$pdo->commit();
|
$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();
|
$pdo->rollBack();
|
||||||
$error = "Error al actualizar el inventario: " . $e->getMessage();
|
$error = "Error: " . $e->getMessage();
|
||||||
}
|
}
|
||||||
} else {
|
} 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
|
// Obtener sedes para el dropdown
|
||||||
$products = [];
|
|
||||||
$sedes = [];
|
$sedes = [];
|
||||||
try {
|
try {
|
||||||
$pdo = db();
|
$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_stmt = $pdo->query("SELECT id, nombre FROM sedes ORDER BY nombre ASC");
|
||||||
$sedes = $sedes_stmt->fetchAll(PDO::FETCH_ASSOC);
|
$sedes = $sedes_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
} catch (PDOException $e) {
|
} 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">
|
<div class="col-lg-6 mx-auto">
|
||||||
|
|
||||||
<?php if ($message): ?>
|
<?php if ($message): ?>
|
||||||
<div class="alert alert-success" role="alert">
|
<div class="alert alert-success" role="alert" id="form-message"><?php echo htmlspecialchars($message); ?></div>
|
||||||
<?php echo htmlspecialchars($message); ?>
|
|
||||||
</div>
|
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
<?php if ($error): ?>
|
<?php if ($error): ?>
|
||||||
<div class="alert alert-danger" role="alert">
|
<div class="alert alert-danger" role="alert" id="form-error"><?php echo htmlspecialchars($error); ?></div>
|
||||||
<?php echo htmlspecialchars($error); ?>
|
|
||||||
</div>
|
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header">
|
<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>
|
||||||
<div class="card-body">
|
<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">
|
<div class="mb-3">
|
||||||
<label for="movement_date" class="form-label">Fecha de Entrada</label>
|
<label for="codigo_unico" class="form-label">Código de Unidad</label>
|
||||||
<input type="date" class="form-control" id="movement_date" name="movement_date" value="<?php echo date('Y-m-d'); ?>" required>
|
<div class="input-group">
|
||||||
</div>
|
<input type="text" class="form-control" id="codigo_unico" name="codigo_unico" required autofocus>
|
||||||
<div class="mb-3">
|
<button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#scannerModal">
|
||||||
<label for="producto" class="form-label">Producto</label>
|
<i class="fa fa-camera"></i>
|
||||||
<button type="button" class="btn btn-info btn-sm float-end" data-bs-toggle="modal" data-bs-target="#scannerModal">
|
</button>
|
||||||
<i class="fa fa-camera"></i> Escanear
|
</div>
|
||||||
</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>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="sede" class="form-label">Sede de Destino</label>
|
<label for="sede" class="form-label">Sede de Destino</label>
|
||||||
<select class="form-select" id="sede" name="sede_id" required>
|
<select class="form-select" id="sede" name="sede_id" required>
|
||||||
@ -125,7 +128,7 @@ try {
|
|||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</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>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -138,7 +141,7 @@ try {
|
|||||||
<div class="modal-dialog">
|
<div class="modal-dialog">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-header">
|
<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>
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
@ -154,74 +157,54 @@ try {
|
|||||||
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
|
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', (event) => {
|
document.addEventListener('DOMContentLoaded', (event) => {
|
||||||
if (typeof bootstrap === 'undefined') {
|
const codigoUnicoInput = document.getElementById('codigo_unico');
|
||||||
console.error('Bootstrap no está cargado. El modal del escáner no funcionará.');
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const scannerModalElement = document.getElementById('scannerModal');
|
const scannerModalElement = document.getElementById('scannerModal');
|
||||||
if (!scannerModalElement) {
|
if (!scannerModalElement) return;
|
||||||
console.error('El elemento del modal del escáner no se encontró.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const scannerModal = new bootstrap.Modal(scannerModalElement);
|
const scannerModal = new bootstrap.Modal(scannerModalElement);
|
||||||
const html5QrCode = new Html5Qrcode("reader");
|
const html5QrCode = new Html5Qrcode("reader");
|
||||||
|
|
||||||
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
|
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
|
||||||
html5QrCode.stop().then((ignore) => {
|
html5QrCode.stop().then(ignore => {}).catch(err => console.log("Failed to stop scanner"));
|
||||||
console.log("QR Code scanning stopped.");
|
|
||||||
}).catch((err) => {
|
|
||||||
console.error("Failed to stop QR Code scanning.", err);
|
|
||||||
});
|
|
||||||
|
|
||||||
scannerModal.hide();
|
scannerModal.hide();
|
||||||
|
|
||||||
fetch(`get_product_details.php?id=${decodedText}`)
|
if(codigoUnicoInput) {
|
||||||
.then(response => {
|
codigoUnicoInput.value = decodedText;
|
||||||
if (!response.ok) {
|
codigoUnicoInput.focus();
|
||||||
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 } };
|
const config = { fps: 10, qrbox: { width: 250, height: 250 } };
|
||||||
|
|
||||||
scannerModalElement.addEventListener('shown.bs.modal', function () {
|
scannerModalElement.addEventListener('shown.bs.modal', function () {
|
||||||
html5QrCode.start(
|
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback)
|
||||||
{ facingMode: "environment" },
|
.catch(err => {
|
||||||
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.");
|
alert("Error al iniciar la cámara. Asegúrese de dar permisos.");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
scannerModalElement.addEventListener('hidden.bs.modal', function () {
|
scannerModalElement.addEventListener('hidden.bs.modal', function () {
|
||||||
html5QrCode.stop().catch(err => {
|
html5QrCode.stop().catch(err => {});
|
||||||
// Ignorar error si el escáner ya estaba detenido
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@ -117,69 +117,39 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
|||||||
|
|
||||||
// --- LÓGICA DE SONIDO (WEB AUDIO API) ---
|
// --- LÓGICA DE SONIDO (WEB AUDIO API) ---
|
||||||
let audioCtx;
|
let audioCtx;
|
||||||
|
function wakeUpAudio() {
|
||||||
// Esta función inicializa y DESBLOQUEA el audio.
|
if (!audioCtx) {
|
||||||
// Debe ser llamada por una interacción directa del usuario (click o touch).
|
try {
|
||||||
function unlockAudio() {
|
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
||||||
if (audioCtx) {
|
} catch (e) { console.error("Web Audio API no es soportada.", e); return; }
|
||||||
if (audioCtx.state === 'suspended') {
|
|
||||||
audioCtx.resume().then(() => {
|
|
||||||
console.log("AudioContext reanudado exitosamente.");
|
|
||||||
}).catch(e => console.error("Error al reanudar AudioContext:", e));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
if (audioCtx.state === 'suspended') {
|
||||||
try {
|
audioCtx.resume();
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
document.body.addEventListener('click', wakeUpAudio, { once: true });
|
||||||
// Asignamos la función de desbloqueo a los primeros eventos de interacción del usuario.
|
document.body.addEventListener('touchstart', wakeUpAudio, { once: true });
|
||||||
// `{ once: true }` asegura que solo se ejecute una vez.
|
|
||||||
document.body.addEventListener('click', unlockAudio, { once: true });
|
|
||||||
document.body.addEventListener('touchstart', unlockAudio, { once: true });
|
|
||||||
|
|
||||||
function playBeep() {
|
function playBeep() {
|
||||||
if (!audioCtx || audioCtx.state !== 'running') {
|
if (!audioCtx || audioCtx.state !== 'running') {
|
||||||
console.warn("AudioContext no está listo o desbloqueado. No se puede reproducir sonido.");
|
wakeUpAudio();
|
||||||
// Intento de último recurso (puede no funcionar si no es por gesto de usuario)
|
if (!audioCtx || audioCtx.state !== 'running') return;
|
||||||
unlockAudio();
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const oscillator = audioCtx.createOscillator();
|
const oscillator = audioCtx.createOscillator();
|
||||||
const gainNode = audioCtx.createGain();
|
const gainNode = audioCtx.createGain();
|
||||||
|
|
||||||
oscillator.connect(gainNode);
|
oscillator.connect(gainNode);
|
||||||
gainNode.connect(audioCtx.destination);
|
gainNode.connect(audioCtx.destination);
|
||||||
|
gainNode.gain.value = 0.1;
|
||||||
gainNode.gain.value = 0.1; // Volumen bajo para no ser molesto
|
oscillator.frequency.value = 880;
|
||||||
oscillator.frequency.value = 880; // Frecuencia del tono (un La agudo)
|
oscillator.type = 'sine';
|
||||||
oscillator.type = 'sine'; // Tipo de onda
|
|
||||||
|
|
||||||
oscillator.start();
|
oscillator.start();
|
||||||
setTimeout(() => {
|
setTimeout(() => oscillator.stop(), 150);
|
||||||
oscillator.stop();
|
|
||||||
}, 150); // Duración del sonido en milisegundos
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// --- LÓGICA PARA MÓVIL ---
|
// --- LÓGICA PARA MÓVIL ---
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
if(sedeContainer) {
|
if(sedeContainer) sedeContainer.style.display = 'none';
|
||||||
sedeContainer.style.display = 'none'; // Ocultar el selector de sede
|
if(sedeSelect && almacenPrincipalId) sedeSelect.value = almacenPrincipalId;
|
||||||
}
|
|
||||||
if(sedeSelect && almacenPrincipalId) {
|
|
||||||
sedeSelect.value = almacenPrincipalId; // Seleccionar ALMACEN PRINCIPAL por defecto
|
|
||||||
}
|
|
||||||
console.log('Modo móvil activado. Sede por defecto: ALMACEN PRINCIPAL');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- INICIALIZACIÓN DE CÁMARA ---
|
// --- INICIALIZACIÓN DE CÁMARA ---
|
||||||
@ -187,6 +157,7 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
|||||||
let html5QrCode;
|
let html5QrCode;
|
||||||
|
|
||||||
function onScanSuccess(decodedText, decodedResult) {
|
function onScanSuccess(decodedText, decodedResult) {
|
||||||
|
playBeep();
|
||||||
barcodeInput.value = decodedText;
|
barcodeInput.value = decodedText;
|
||||||
const changeEvent = new Event('change');
|
const changeEvent = new Event('change');
|
||||||
barcodeInput.dispatchEvent(changeEvent);
|
barcodeInput.dispatchEvent(changeEvent);
|
||||||
@ -194,18 +165,17 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
|||||||
if(modal) modal.hide();
|
if(modal) modal.hide();
|
||||||
}
|
}
|
||||||
|
|
||||||
function onScanFailure(error) { /* No hacer nada */ }
|
|
||||||
|
|
||||||
cameraModal.addEventListener('shown.bs.modal', function () {
|
cameraModal.addEventListener('shown.bs.modal', function () {
|
||||||
|
wakeUpAudio();
|
||||||
html5QrCode = new Html5Qrcode("reader");
|
html5QrCode = new Html5Qrcode("reader");
|
||||||
const config = { fps: 10, qrbox: { width: 250, height: 250 } };
|
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."));
|
.catch(err => alert("Error al iniciar la cámara. Asegúrate de dar permisos."));
|
||||||
});
|
});
|
||||||
|
|
||||||
cameraModal.addEventListener('hidden.bs.modal', function () {
|
cameraModal.addEventListener('hidden.bs.modal', function () {
|
||||||
if (html5QrCode && html5QrCode.isScanning) {
|
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;
|
this.disabled = true;
|
||||||
|
|
||||||
const sedeId = sedeSelect.value;
|
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) {
|
if (!sedeId) {
|
||||||
showNotification("Por favor, seleccione una sede y una fecha.", false);
|
showNotification("Por favor, seleccione una sede de origen.", false);
|
||||||
this.value = '';
|
this.value = '';
|
||||||
this.disabled = false;
|
this.disabled = false;
|
||||||
processing = false;
|
processing = false;
|
||||||
@ -248,40 +218,12 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
|||||||
return;
|
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();
|
const formData = new FormData();
|
||||||
formData.append('product_id', productId);
|
formData.append('codigo_unico', barcodeValue);
|
||||||
formData.append('sede_id', sedeId);
|
formData.append('sede_id', sedeId);
|
||||||
formData.append('movement_date', movementDate);
|
|
||||||
|
|
||||||
fetch('registrar_salida_api.php', {
|
fetch('registrar_salida_unidad_api.php', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
||||||
body: formData
|
body: formData
|
||||||
})
|
})
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
@ -289,18 +231,23 @@ document.addEventListener('DOMContentLoaded', (event) => {
|
|||||||
if (data.success) {
|
if (data.success) {
|
||||||
showNotification(data.message, true);
|
showNotification(data.message, true);
|
||||||
} else {
|
} else {
|
||||||
throw new Error(data.message || 'Error al registrar la salida.');
|
throw new Error(data.message || 'Error desconocido al registrar la salida.');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
showNotification(error.message, false);
|
showNotification(error.message, false);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.value = '';
|
||||||
|
this.disabled = false;
|
||||||
|
processing = false;
|
||||||
|
this.focus();
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
|
||||||
// Mantener el foco en el input
|
// Mantener el foco en el input
|
||||||
barcodeInput.focus();
|
barcodeInput.focus();
|
||||||
document.body.addEventListener('click', (e) => {
|
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')) {
|
if (!['INPUT', 'SELECT', 'BUTTON', 'A'].includes(e.target.tagName) && !e.target.closest('button, a')) {
|
||||||
barcodeInput.focus();
|
barcodeInput.focus();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,2 +1,4 @@
|
|||||||
[2026-02-11 23:38:51] Intento fallido de búsqueda con SKU: 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 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:
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user