File "registrar.php"
Full Path: C:/wamp64/www/loteo1/registrar.php
File size: 16.74 KB
MIME-type: text/x-php
Charset: utf-8
<?php
require_once 'connection.php';
// Crear tabla si no existe con TODOS los campos necesarios
$conn = connection();
// Primero verificar si la tabla existe y tiene todas las columnas
$check_table = "SHOW COLUMNS FROM entregas";
$result = $conn->query($check_table);
$existing_columns = [];
if ($result) {
while ($row = $result->fetch_assoc()) {
$existing_columns[] = $row['Field'];
}
}
// Si la tabla no existe, crearla
if (empty($existing_columns)) {
$sql = "CREATE TABLE entregas (
id INT AUTO_INCREMENT PRIMARY KEY,
fecha DATETIME NOT NULL,
proceso VARCHAR(20) NOT NULL,
item VARCHAR(50) NOT NULL,
descripcion TEXT NOT NULL,
cantidad INT NOT NULL,
area VARCHAR(50) NOT NULL,
observacion TEXT NOT NULL,
firma_entrega LONGTEXT NOT NULL,
firma_recibe LONGTEXT NOT NULL,
tipoMV VARCHAR(20) DEFAULT 'Entrega',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
$conn->query($sql);
} else {
// Si la tabla existe, agregar columnas faltantes
$required_columns = [
'item' => "ALTER TABLE entregas ADD COLUMN item VARCHAR(50) NOT NULL DEFAULT ''",
'descripcion' => "ALTER TABLE entregas ADD COLUMN descripcion TEXT NOT NULL",
'cantidad' => "ALTER TABLE entregas ADD COLUMN cantidad INT NOT NULL DEFAULT 0",
'area' => "ALTER TABLE entregas ADD COLUMN area VARCHAR(50) NOT NULL DEFAULT ''",
'observacion' => "ALTER TABLE entregas ADD COLUMN observacion TEXT NOT NULL",
'firma_entrega' => "ALTER TABLE entregas ADD COLUMN firma_entrega LONGTEXT NOT NULL",
'firma_recibe' => "ALTER TABLE entregas ADD COLUMN firma_recibe LONGTEXT NOT NULL",
'tipoMV' => "ALTER TABLE entregas ADD COLUMN tipoMV VARCHAR(20) DEFAULT 'Entrega'"
];
foreach ($required_columns as $column => $alter_sql) {
if (!in_array($column, $existing_columns)) {
$conn->query($alter_sql);
}
}
// Si existe la columna 'items' (campo JSON), eliminarla porque ya no la necesitamos
if (in_array('items', $existing_columns)) {
$conn->query("ALTER TABLE entregas DROP COLUMN items");
}
}
// Obtener los items de la tabla 'items' (Pollo) para la carga inicial
$items_iniciales = [];
$result_items = $conn->query("SELECT item, descripcion FROM items ORDER BY item");
if ($result_items) {
while ($row = $result_items->fetch_assoc()) {
$items_iniciales[] = $row;
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registrar Entrega</title>
<link rel="icon" type="image/png" href="img/icono.png">
<link rel="stylesheet" href="css/styles.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<script src="js/firmas.js"></script>
<style>
:root {
--primary-color: #2c3e50; /* Azul oscuro principal */
--secondary-color: #3498db; /* Azul brillante */
--accent-color: #e74c3c; /* Rojo para acciones importantes */
--success-color: #27ae60; /* Verde para acciones positivas */
--light-color: #ecf0f1; /* Fondo claro */
--dark-color: #2c3e50; /* Texto oscuro */
--border-color: #bdc3c7; /* Color para bordes */
}
.logo {
display: block;
margin: 0 auto 1.5rem;
max-width: 250px;
height: auto;
}
.copyright {
display: block; /* Cambiado de inline-block a block para mejor centrado */
margin: 0 auto; /* Esto centrará el elemento horizontalmente */
padding: 10px 25px;
color: black;
border-radius: 4px;
font-size: 14px;
font-weight: bold; /* Esto ya pone el texto en negrita */
text-align: center; /* Esto centra el texto dentro del elemento */
width: fit-content; /* Ajusta el ancho al contenido */
}
/* Contenedor de items */
.items-container {
margin-bottom: 20px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 5px;
border: 1px solid var(--border-color);
}
/* Fila de item */
.item-row {
display: flex;
margin-bottom: 10px;
align-items: center;
gap: 8px;
padding: 8px;
background-color: white;
border-radius: 4px;
border: 1px solid var(--border-color);
}
/* Select de items */
.item-select {
flex: 1;
min-width: 150px;
max-width: 200px;
padding: 8px 12px;
border: 1px solid var(--border-color);
border-radius: 4px;
background-color: white;
}
/* Campo de cantidad */
.item-cantidad {
flex: 0.3;
min-width: 80px;
max-width: 100px;
padding: 8px 12px;
border: 1px solid var(--border-color);
border-radius: 4px;
}
/* Ajustes para Select2 */
.select2-container--default .select2-selection--single {
height: 38px !important;
border: 1px solid var(--border-color) !important;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 36px !important;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
height: 36px !important;
}
/* Botones */
.btn-remove-item {
flex: 0.1;
min-width: 80px;
padding: 8px 12px;
background-color: var(--accent-color);
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
.btn-remove-item:hover {
background-color: #c0392b;
}
.btn-add-item {
padding: 8px 16px;
background-color: var(--success-color);
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-bottom: 15px;
font-weight: bold;
transition: background-color 0.3s;
}
.btn-add-item:hover {
background-color: #219653;
}
/* Ajustes generales para select2 dropdown */
.select2-dropdown {
border: 1px solid var(--border-color) !important;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.select2-results__option--highlighted {
background-color: var(--secondary-color) !important;
}
/* Media query corregido */
@media (max-width: 900px) and (min-width: 400px) {
/* Aquí puedes agregar estilos responsivos si los necesitas */
.item-row {
flex-wrap: wrap;
}
.item-select {
min-width: 100%;
max-width: 100%;
}
.item-cantidad {
max-width: 100%;
}
.btn-remove-item {
flex: 1;
}
}
</style>
</head>
<body>
<div class="container">
<img src="img/LOGO.png" alt="" width="37" height="37" class="logo" style="width: 250px; height: auto;" />
<h1>Registrar Nueva Entrega</h1>
<!-- Mensaje de éxito -->
<?php if(isset($_GET['success']) && $_GET['success'] == 1): ?>
<div class="alert success">
<strong>¡Registro exitoso!</strong> Se han guardado <?= $_GET['registros'] ?? 'los' ?> registros correctamente.
</div>
<?php endif; ?>
<!-- Mensaje de error (ya existía, pero se mejora) -->
<?php if(isset($_GET['error'])): ?>
<div class="alert error">
<strong>Error al registrar la entrega.</strong> Intente nuevamente.
<?php if(isset($_GET['message'])): ?>
<br><small>Detalle: <?= htmlspecialchars($_GET['message']) ?></small>
<?php endif; ?>
</div>
<?php endif; ?>
<form action="guardar.php" method="POST" id="formEntrega">
<div class="form-group">
<label for="fecha">Fecha:</label>
<input type="datetime-local" id="fecha" name="fecha" required value="<?= date('Y-m-d\TH:i') ?>">
</div>
<div class="form-group">
<label for="proceso">Tipo De Proceso:</label>
<select id="proceso" name="proceso" required>
<option value="">Seleccione...</option>
<option value="Pollo" selected>Pollo</option>
<option value="Pavo">Pavo</option>
</select>
</div>
<div>
<label>Ítems:</label>
<button type="button" id="btnAddItem" class="btn-add-item">+ Agregar Ítem</button>
<div class="items-container" id="itemsContainer">
<div class="item-row">
<select class="item-select form-control" name="items[]" required>
<option value="" selected hidden>Seleccione el Item</option>
</select>
<input type="number" class="item-cantidad" name="cantidades[]" required min="1" placeholder="Cantidad">
<button type="button" class="btn-remove-item" onclick="removeItem(this)">Eliminar</button>
</div>
</div>
</div>
<div class="form-group">
<label for="area">Área:</label>
<select id="area" name="area" required>
<option value="">Seleccione...</option>
<option value="Producción">Producción</option>
<option value="Marinado">Marinado</option>
<option value="Emp Viscera">Emp Viscera</option>
<option value="Emp Pollo">Emp Pollo</option>
<option value="Postproceso">Postproceso</option>
<option value="Pasta">Pasta</option>
<option value="Fileteo">Fileteo</option>
<option value="Evisceracion">Evisceracion</option>
<option value="Calidad">Calidad</option>
<option value="Logistica">Logística</option>
<option value="Almacen">Almacén</option>
<option value="Prod Pavo">Prod Pavo</option>
<option value="Fileteo Pavo">Fileteo Pavo</option>
<option value="Carnes Especiales Pavo">Carnes Especiales Pavo</option>
<option value="Posproceso Pavo">Posproceso Pavo</option>
<option value="Reproceso Pavo">Reproceso Pavo</option>
<option value="Marinado Pavo">Marinado Pavo</option>
</select>
</div>
<div class="form-group">
<label for="observacion">Observación:</label>
<textarea id="observacion" name="observacion" required></textarea>
</div>
<div class="form-group">
<label>Firma Quien Entrega:</label>
<div class="signature-container">
<canvas id="firmaEntregaCanvas"
data-input="firmaEntrega"
class="signature-pad"></canvas>
<button type="button" id="limpiarFirmaEntrega" class="btn-clear">Limpiar</button>
</div>
<input type="hidden" id="firmaEntrega" name="firma_entrega" required>
</div>
<div class="form-group">
<label>Firma Quien Recibe:</label>
<div class="signature-container">
<canvas id="firmaRecibeCanvas"
data-input="firmaRecibe"
class="signature-pad"></canvas>
<button type="button" id="limpiarFirmaRecibe" class="btn-clear">Limpiar</button>
</div>
<input type="hidden" id="firmaRecibe" name="firma_recibe" required>
</div>
<div class="form-actions">
<button type="submit" class="btn">Guardar Entrega</button>
<a href="index.php" class="btn btn-cancelar">Cancelar</a>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// Items iniciales (cargados desde PHP para Pollo)
let currentItems = <?php echo json_encode($items_iniciales); ?>;
// Función para llenar un select con los items actuales
function fillSelect(selectElement, items) {
// Guardar valor actual si existe
const currentVal = $(selectElement).val();
// Limpiar opciones (excepto la primera por defecto)
$(selectElement).empty().append('<option value="" selected hidden>Seleccione el Item</option>');
// Agregar nuevas opciones
items.forEach(item => {
const option = $('<option>', {
value: item.item,
text: item.item + ' - ' + item.descripcion,
'data-descripcion': item.descripcion
});
$(selectElement).append(option);
});
// Restaurar valor si aún existe en las nuevas opciones
if (currentVal && $(selectElement).find(`option[value="${currentVal}"]`).length) {
$(selectElement).val(currentVal);
}
}
// Función para actualizar todos los selects de items
function updateAllSelects(items) {
$('.item-select').each(function() {
fillSelect(this, items);
// Reinicializar Select2
if ($(this).data('select2')) {
$(this).select2('destroy');
}
$(this).select2({
theme: 'bootstrap-5',
width: '100%',
dropdownAutoWidth: true
});
});
}
$(document).ready(function() {
// Inicializar selects con los items actuales
updateAllSelects(currentItems);
// Evento cambio de proceso
$('#proceso').change(function() {
const proceso = $(this).val();
if (!proceso) return;
fetch('get_items.php?proceso=' + encodeURIComponent(proceso))
.then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
return;
}
currentItems = data; // Actualizar variable global
updateAllSelects(currentItems);
})
.catch(error => {
console.error('Error:', error);
alert('Error al cargar los items');
});
});
// Agregar nuevo ítem
$('#btnAddItem').click(function() {
const newRow = `
<div class="item-row">
<select class="item-select form-control" name="items[]" required>
<option value="" selected hidden>Seleccione el Item</option>
</select>
<input type="number" class="item-cantidad" name="cantidades[]" required min="1" placeholder="Cantidad">
<button type="button" class="btn-remove-item" onclick="removeItem(this)">Eliminar</button>
</div>
`;
$('#itemsContainer').append(newRow);
const newSelect = $('#itemsContainer .item-select').last();
fillSelect(newSelect, currentItems);
newSelect.select2({
theme: 'bootstrap-5',
width: '100%',
dropdownAutoWidth: true
});
});
});
// Función para eliminar un ítem
function removeItem(button) {
if ($('#itemsContainer .item-row').length > 1) {
$(button).closest('.item-row').remove();
} else {
alert('Debe haber al menos un ítem en la entrega.');
}
}
</script>
<div class="copyright">
© Avicampo <?php echo date('Y'); ?>
</div>
</body>
</html>