Autosave: 20260203-162317
This commit is contained in:
parent
762a54dd3e
commit
5ebd11482d
Binary file not shown.
|
After Width: | Height: | Size: 75 KiB |
11
db/migrations/051_create_stock_movements_table.sql
Normal file
11
db/migrations/051_create_stock_movements_table.sql
Normal file
@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS `stock_movements` (
|
||||
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
||||
`product_id` INT NOT NULL,
|
||||
`sede_id` INT NOT NULL,
|
||||
`quantity` INT NOT NULL,
|
||||
`type` ENUM('entrada', 'salida') NOT NULL,
|
||||
`movement_date` DATE NOT NULL,
|
||||
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (`product_id`) REFERENCES `products`(`id`) ON DELETE CASCADE,
|
||||
FOREIGN KEY (`sede_id`) REFERENCES `sedes`(`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
1
db/migrations/052_add_sc_to_flujo_caja.sql
Normal file
1
db/migrations/052_add_sc_to_flujo_caja.sql
Normal file
@ -0,0 +1 @@
|
||||
ALTER TABLE flujo_caja ADD COLUMN sc DECIMAL(10, 2) DEFAULT 0.00;
|
||||
@ -10,9 +10,10 @@ ini_set('error_log', 'php-error.log');
|
||||
session_start();
|
||||
require_once 'db/config.php';
|
||||
|
||||
// Check if user is logged in and is an admin
|
||||
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'Administrador') {
|
||||
header('Location: pedidos.php');
|
||||
// Check if user is logged in and has an admin role
|
||||
$allowed_roles = ['Administrador', 'admin'];
|
||||
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], $allowed_roles)) {
|
||||
header('Location: dashboard.php?error=access_denied');
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
@ -12,7 +12,7 @@ $end_date = "$year-$month-$days_in_month";
|
||||
$columns = [
|
||||
'bcp_yape', 'b_nacion', 'interbank', 'bbva', 'otros_ingresos',
|
||||
'tu1', 'tu2', 'tu3', 'fl1', 'fl2', 'fl3',
|
||||
'rc_envio', 'rc_contraent'
|
||||
'rc_envio', 'rc_contraent', 'sc'
|
||||
];
|
||||
|
||||
// Fetch data from DB
|
||||
@ -112,6 +112,7 @@ foreach ($all_days_data as $day_data) {
|
||||
<th colspan="6" style="text-align: center;">Inversion Publicitaria</th>
|
||||
<th rowspan="2" style="vertical-align: middle; text-align: center;">RC ENVIO</th>
|
||||
<th rowspan="2" style="vertical-align: middle; text-align: center;">RC CONTRAENT</th>
|
||||
<th rowspan="2" style="vertical-align: middle; text-align: center;">Sc</th>
|
||||
<th rowspan="2" style="vertical-align: middle; text-align: center;">Total Ingresos</th>
|
||||
<th rowspan="2" style="vertical-align: middle; text-align: center;">Total Inversion Publicitaria</th>
|
||||
<th rowspan="2" style="vertical-align: middle; text-align: center;">Recaudo final</th>
|
||||
|
||||
@ -4,6 +4,14 @@ if (!isset($_SESSION['user_id'])) {
|
||||
header('Location: login.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
// Role check for inventory panel
|
||||
$userRole = $_SESSION['user_role'] ?? '';
|
||||
$allowedRoles = ['Administrador', 'admin', 'Control Logistico'];
|
||||
if (!in_array($userRole, $allowedRoles)) {
|
||||
header('Location: dashboard.php?error=access_denied');
|
||||
exit();
|
||||
}
|
||||
require_once 'layout_header.php';
|
||||
require_once 'db/config.php';
|
||||
|
||||
@ -25,7 +33,6 @@ try {
|
||||
$stock_stmt = $pdo->query("SELECT product_id, sede_id, quantity FROM stock_sedes");
|
||||
$stock_data = $stock_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// Procesar datos para la tabla
|
||||
$inventario = [];
|
||||
foreach ($products as $product) {
|
||||
$inventario[$product['id']] = [
|
||||
@ -42,33 +49,56 @@ try {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Datos para el gráfico circular (Distribución por Sede)
|
||||
// 3. Datos para gráficos
|
||||
$stock_por_sede_stmt = $pdo->query("
|
||||
SELECT s.nombre, SUM(ss.quantity) as total_stock
|
||||
FROM sedes s
|
||||
JOIN stock_sedes ss ON s.id = ss.sede_id
|
||||
GROUP BY s.nombre
|
||||
HAVING total_stock > 0
|
||||
ORDER BY s.nombre
|
||||
FROM sedes s JOIN stock_sedes ss ON s.id = ss.sede_id
|
||||
GROUP BY s.nombre HAVING total_stock > 0 ORDER BY s.nombre
|
||||
");
|
||||
$stock_por_sede = $stock_por_sede_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$sede_chart_labels = json_encode(array_column($stock_por_sede, 'nombre'));
|
||||
$sede_chart_data = json_encode(array_column($stock_por_sede, 'total_stock'));
|
||||
|
||||
$sede_chart_labels_array = array_column($stock_por_sede, 'nombre');
|
||||
$sede_chart_data_array = array_column($stock_por_sede, 'total_stock');
|
||||
|
||||
$colores_sedes = [];
|
||||
$colores_default = ['#FF6384', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'];
|
||||
$color_map = [
|
||||
'ALIDRV' => '#28a745', // Verde
|
||||
'Almacen Principal' => '#36A2EB' // Azul
|
||||
];
|
||||
$default_color_idx = 0;
|
||||
foreach ($sede_chart_labels_array as $label) {
|
||||
if (isset($color_map[$label])) {
|
||||
$colores_sedes[] = $color_map[$label];
|
||||
} else {
|
||||
$colores_sedes[] = $colores_default[$default_color_idx % count($colores_default)];
|
||||
$default_color_idx++;
|
||||
}
|
||||
}
|
||||
|
||||
$sede_chart_labels = json_encode($sede_chart_labels_array);
|
||||
$sede_chart_data = json_encode($sede_chart_data_array);
|
||||
$sede_chart_colors = json_encode($colores_sedes);
|
||||
|
||||
// 4. Datos para el gráfico de barras (Stock por Producto)
|
||||
$stock_por_producto_stmt = $pdo->query("
|
||||
SELECT p.nombre, SUM(ss.quantity) as total_stock
|
||||
FROM products p
|
||||
JOIN stock_sedes ss ON p.id = ss.product_id
|
||||
GROUP BY p.nombre
|
||||
HAVING total_stock > 0
|
||||
ORDER BY total_stock DESC
|
||||
LIMIT 15
|
||||
FROM products p JOIN stock_sedes ss ON p.id = ss.product_id
|
||||
GROUP BY p.nombre HAVING total_stock > 0 ORDER BY total_stock DESC LIMIT 15
|
||||
");
|
||||
$stock_por_producto = $stock_por_producto_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$producto_chart_labels = json_encode(array_column($stock_por_producto, 'nombre'));
|
||||
$producto_chart_data = json_encode(array_column($stock_por_producto, 'total_stock'));
|
||||
|
||||
// 4. Datos para el historial de movimientos (últimos 50)
|
||||
$movements_stmt = $pdo->query("
|
||||
SELECT sm.movement_date, p.nombre as product_name, s.nombre as sede_name, sm.quantity, sm.type
|
||||
FROM stock_movements sm
|
||||
JOIN products p ON sm.product_id = p.id
|
||||
JOIN sedes s ON sm.sede_id = s.id
|
||||
ORDER BY sm.created_at DESC
|
||||
LIMIT 50
|
||||
");
|
||||
$movements = $movements_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
} catch (PDOException $e) {
|
||||
echo "<div class='alert alert-danger'>Error al conectar o consultar la base de datos: " . $e->getMessage() . "</div>";
|
||||
@ -78,7 +108,13 @@ try {
|
||||
?>
|
||||
|
||||
<div class="container-fluid mt-4">
|
||||
<h1 class="mb-4">Dashboard de Inventario</h1>
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1>Dashboard de Inventario</h1>
|
||||
<div>
|
||||
<a href="registro_entrada.php" class="btn btn-success"><i class="fa fa-plus"></i> Registrar Entrada</a>
|
||||
<a href="registro_salida.php" class="btn btn-danger"><i class="fa fa-minus"></i> Registrar Salida</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tarjetas de Resumen -->
|
||||
<div class="row mb-4">
|
||||
@ -112,9 +148,7 @@ try {
|
||||
<div class="row mb-4">
|
||||
<div class="col-lg-6 mb-4">
|
||||
<div class="card h-100">
|
||||
<div class="card-header">
|
||||
<h5 class="m-0">Distribución por Sede</h5>
|
||||
</div>
|
||||
<div class="card-header"><h5 class="m-0">Distribución por Sede</h5></div>
|
||||
<div class="card-body d-flex justify-content-center align-items-center">
|
||||
<canvas id="distribucionSedeChart" style="max-height: 300px;"></canvas>
|
||||
</div>
|
||||
@ -122,22 +156,15 @@ try {
|
||||
</div>
|
||||
<div class="col-lg-6 mb-4">
|
||||
<div class="card h-100">
|
||||
<div class="card-header">
|
||||
<h5 class="m-0">Top 15 Productos con Más Stock</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<canvas id="stockProductoChart"></canvas>
|
||||
</div>
|
||||
<div class="card-header"><h5 class="m-0">Top 15 Productos con Más Stock</h5></div>
|
||||
<div class="card-body"><canvas id="stockProductoChart"></canvas></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Tabla de Inventario Detallado -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="m-0">Inventario por Sede</h5>
|
||||
</div>
|
||||
<div class="card mb-4">
|
||||
<div class="card-header"><h5 class="m-0">Inventario por Sede</h5></div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-bordered table-hover">
|
||||
@ -152,9 +179,7 @@ try {
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (empty($inventario)): ?>
|
||||
<tr>
|
||||
<td colspan="<?php echo count($sedes) + 2; ?>" class="text-center">No hay productos para mostrar.</td>
|
||||
</tr>
|
||||
<tr><td colspan="<?php echo count($sedes) + 2; ?>" class="text-center">No hay productos.</td></tr>
|
||||
<?php else: ?>
|
||||
<?php foreach ($inventario as $datos_producto): ?>
|
||||
<tr>
|
||||
@ -171,90 +196,78 @@ try {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Historial de Movimientos -->
|
||||
<div class="card">
|
||||
<div class="card-header"><h5 class="m-0">Historial de Movimientos Recientes</h5></div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-hover">
|
||||
<thead class="thead-light">
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Producto</th>
|
||||
<th>Sede</th>
|
||||
<th class="text-center">Cantidad</th>
|
||||
<th class="text-center">Tipo</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (empty($movements)): ?>
|
||||
<tr><td colspan="5" class="text-center">No hay movimientos registrados.</td></tr>
|
||||
<?php else: ?>
|
||||
<?php foreach ($movements as $mov): ?>
|
||||
<tr>
|
||||
<td><?php echo htmlspecialchars(date("d/m/Y", strtotime($mov['movement_date']))); ?></td>
|
||||
<td><?php echo htmlspecialchars($mov['product_name']); ?></td>
|
||||
<td><?php echo htmlspecialchars($mov['sede_name']); ?></td>
|
||||
<td class="text-center"><?php echo htmlspecialchars($mov['quantity']); ?></td>
|
||||
<td class="text-center">
|
||||
<?php if ($mov['type'] == 'entrada'): ?>
|
||||
<span class="badge bg-success">Entrada</span>
|
||||
<?php else: ?>
|
||||
<span class="badge bg-danger">Salida</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Incluir Chart.js -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
// --- Gráfico 1: Distribución por Sede (Circular) ---
|
||||
const sedeLabels = <?php echo $sede_chart_labels; ?>;
|
||||
const sedeData = <?php echo $sede_chart_data; ?>;
|
||||
|
||||
const sedeColors = <?php echo $sede_chart_colors; ?>;
|
||||
if (sedeLabels.length > 0) {
|
||||
const defaultColors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'];
|
||||
const alidrvColor = '#28a745'; // Verde
|
||||
|
||||
const backgroundColors = sedeLabels.map((label, index) => {
|
||||
if (label.toLowerCase() === 'alidrv') {
|
||||
return alidrvColor;
|
||||
}
|
||||
return defaultColors[index % defaultColors.length];
|
||||
});
|
||||
|
||||
const ctxSede = document.getElementById('distribucionSedeChart').getContext('2d');
|
||||
new Chart(ctxSede, {
|
||||
type: 'pie',
|
||||
data: {
|
||||
labels: sedeLabels,
|
||||
datasets: [{
|
||||
label: 'Stock',
|
||||
data: sedeData,
|
||||
backgroundColor: backgroundColors,
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'bottom',
|
||||
}
|
||||
}
|
||||
}
|
||||
data: { labels: sedeLabels, datasets: [{ label: 'Stock', data: sedeData, backgroundColor: sedeColors }] },
|
||||
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } }
|
||||
});
|
||||
}
|
||||
|
||||
// --- Gráfico 2: Stock por Producto (Barras) ---
|
||||
const productoLabels = <?php echo $producto_chart_labels; ?>;
|
||||
const productoData = <?php echo $producto_chart_data; ?>;
|
||||
|
||||
if (productoLabels.length > 0) {
|
||||
const ctxProducto = document.getElementById('stockProductoChart').getContext('2d');
|
||||
new Chart(ctxProducto, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: productoLabels,
|
||||
datasets: [{
|
||||
label: 'Cantidad en Stock',
|
||||
data: productoData,
|
||||
backgroundColor: 'rgba(54, 162, 235, 0.6)',
|
||||
borderColor: 'rgba(54, 162, 235, 1)',
|
||||
borderWidth: 1
|
||||
}]
|
||||
},
|
||||
data: { labels: productoLabels, datasets: [{ label: 'Cantidad en Stock', data: productoData, backgroundColor: 'rgba(54, 162, 235, 0.6)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1 }] },
|
||||
options: {
|
||||
indexAxis: 'y', // Hace que el gráfico sea horizontal
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Stock por Producto'
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true
|
||||
}
|
||||
}
|
||||
indexAxis: 'y', responsive: true, plugins: { legend: { display: false }, title: { display: true, text: 'Stock por Producto' } },
|
||||
scales: { x: { beginAtZero: true } }
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
|
||||
@ -176,16 +176,7 @@ include 'layout_header.php';
|
||||
<td><?php echo htmlspecialchars($pedido['monto_total']); ?></td>
|
||||
<td><?php echo htmlspecialchars($pedido['monto_debe']); ?></td>
|
||||
<td class="editable" data-id="<?php echo $pedido['id']; ?>" data-field="codigo_rastreo"><?php echo htmlspecialchars($pedido['codigo_rastreo'] ?? 'N/A'); ?></td>
|
||||
<td class="editable" data-id="<?php echo $pedido['id']; ?>" data-field="codigo_tracking">
|
||||
<?php
|
||||
$tracking = htmlspecialchars($pedido['codigo_tracking'] ?? 'N/A');
|
||||
echo $tracking;
|
||||
if ($tracking !== 'N/A' && !empty($tracking)) {
|
||||
$tracking_url = 'https://shalom.com.pe/rastrea?guia=' . urlencode($tracking);
|
||||
echo ' <a href="' . $tracking_url . '" target="_blank" class="btn btn-sm btn-outline-info p-1" title="Rastrear en Shalom">🔎</a>';
|
||||
}
|
||||
?>
|
||||
</td>
|
||||
<td class="editable" data-id="<?php echo $pedido['id']; ?>" data-field="codigo_tracking"><?php echo htmlspecialchars($pedido['codigo_tracking'] ?? 'N/A'); ?></td>
|
||||
<td class="editable" data-id="<?php echo $pedido['id']; ?>" data-field="clave"><?php echo htmlspecialchars($pedido['clave'] ?? 'N/A'); ?></td>
|
||||
<td><span class="badge" style="<?php echo getStatusStyle($pedido['estado']); ?>"><?php echo ($pedido['estado'] == 'Gestion') ? 'GESTIONES ⚙️' : htmlspecialchars($pedido['estado']); ?></span></td>
|
||||
<?php if ($user_role !== 'Asesor'): ?><td><?php echo htmlspecialchars($pedido['asesor_nombre'] ?? 'N/A'); ?></td><?php endif; ?>
|
||||
|
||||
@ -11,56 +11,64 @@ 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) {
|
||||
if ($product_id && $sede_id && $quantity && $movement_date) {
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8", DB_USER, DB_PASS);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
|
||||
// Verificar si ya existe un registro para este producto en esta sede
|
||||
// 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();
|
||||
|
||||
if ($existing_stock) {
|
||||
// Si existe, actualizar la cantidad
|
||||
$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']]);
|
||||
} else {
|
||||
// Si no existe, insertar un nuevo registro
|
||||
$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]);
|
||||
}
|
||||
|
||||
$message = "¡Inventario actualizado correctamente!";
|
||||
// 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, 'entrada', :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!";
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$pdo->rollBack();
|
||||
$error = "Error al actualizar el inventario: " . $e->getMessage();
|
||||
}
|
||||
} else {
|
||||
$error = "Por favor, complete todos los campos del formulario.";
|
||||
$error = "Por favor, complete todos los campos del formulario, incluyendo la fecha.";
|
||||
}
|
||||
}
|
||||
|
||||
// Obtener productos y sedes de la base de datos para los dropdowns
|
||||
// Obtener productos y sedes para los dropdowns
|
||||
$products = [];
|
||||
$sedes = [];
|
||||
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8", DB_USER, DB_PASS);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
$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">
|
||||
@ -84,6 +92,10 @@ try {
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form action="registro_entrada.php" method="post">
|
||||
<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>
|
||||
<select class="form-select" id="producto" name="product_id" required>
|
||||
@ -118,4 +130,4 @@ try {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
|
||||
@ -11,58 +11,71 @@ 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) {
|
||||
if ($product_id && $sede_id && $quantity && $movement_date) {
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8", DB_USER, DB_PASS);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
|
||||
// Verificar si ya existe un registro para este producto en esta sede
|
||||
// 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) {
|
||||
// Si existe, actualizar la cantidad
|
||||
$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']]);
|
||||
$message = "¡Inventario actualizado correctamente!";
|
||||
|
||||
// 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 {
|
||||
// Si no existe, no se puede dar salida
|
||||
$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.";
|
||||
$error = "Por favor, complete todos los campos del formulario, incluyendo la fecha.";
|
||||
}
|
||||
}
|
||||
|
||||
// Obtener productos y sedes de la base de datos para los dropdowns
|
||||
// Obtener productos y sedes para los dropdowns
|
||||
$products = [];
|
||||
$sedes = [];
|
||||
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8", DB_USER, DB_PASS);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
$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">
|
||||
@ -86,6 +99,10 @@ try {
|
||||
</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>
|
||||
<select class="form-select" id="producto" name="product_id" required>
|
||||
@ -120,4 +137,4 @@ try {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
<?php require_once 'layout_footer.php'; ?>
|
||||
|
||||
@ -12,7 +12,7 @@ if ($data) {
|
||||
$allowed_columns = [
|
||||
'bcp_yape', 'b_nacion', 'interbank', 'bbva', 'otros_ingresos',
|
||||
'tu1', 'tu2', 'tu3', 'fl1', 'fl2', 'fl3',
|
||||
'rc_envio', 'rc_contraent', 'total_inversion_publicitaria'
|
||||
'rc_envio', 'rc_contraent', 'sc', 'total_inversion_publicitaria'
|
||||
];
|
||||
|
||||
if (in_array($columna, $allowed_columns)) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user