Productos frecuenes

This commit is contained in:
2025-07-16 12:43:21 -06:00
parent 8a3e174894
commit cf86fc21cd
10 changed files with 981 additions and 624 deletions

View File

@@ -1,23 +1,12 @@
<!-- views/productos_frecuentes/alta.php -->
<?php
include __DIR__ . '/../partials/sidebar_importador.php';
// Opciones de Vinculación y Criterio Preferencia
$vinculaciones = [
'0' => 'No existe',
'1' => 'Existe, no afecta',
'2' => 'Existe y afecta'
];
$criterios = [
'A' => 'Criterio A',
'B' => 'Criterio B',
'C' => 'Criterio C',
'D' => 'Criterio D',
'E' => 'Criterio E',
'F' => 'Criterio F'
];
$vinculaciones = [ '0' => 'No existe', '1' => 'Existe, no afecta', '2' => 'Existe y afecta' ];
$criterios = [ 'A' => 'Criterio A', 'B' => 'Criterio B', 'C' => 'Criterio C', 'D' => 'Criterio D', 'E' => 'Criterio E', 'F' => 'Criterio F' ];
// Proveedores, unidades y países se cargan por AJAX
?>
<!DOCTYPE html>
<html lang="es">
<head>
@@ -48,9 +37,8 @@
.card-hover:hover { transform: translateY(-8px) scale(1.02); box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15) !important; }
.btn-pulse { animation: pulse 2s infinite; }
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
.fade-in-up { animation: fadeInUp 0.8s ease-out; }
@keyframes fadeInUp {
@@ -137,27 +125,28 @@
<form id="altaProductoFrecuenteForm" action="/IMPORTADORES/productos_frecuentes/guardar" method="POST">
<div class="row g-3 form-group-animated">
<!-- Sinónimo, Fracción, NICO -->
<div class="col-md-4 form-group-animated">
<div class="col-md-6 form-group-animated">
<label for="sinonimo" class="form-label">Sinónimo *</label>
<input type="text" id="sinonimo" name="sinonimo" class="form-control" required>
</div>
<div class="col-md-4 form-group-animated">
<label for="fraccion" class="form-label">Fracción *</label>
<input type="text" id="fraccion" name="fraccion" class="form-control" required>
<input type="text" id="fraccion" name="fraccion" class="form-control" maxlegth="8" required>
</div>
<div class="col-md-4 form-group-animated">
<div class="col-md-2 form-group-animated">
<label for="nico" class="form-label">NICO *</label>
<input type="text" id="nico" name="nico" class="form-control" required>
<input type="text" id="nico" name="nico" class="form-control" maxlength="2" required>
</div>
<!-- Número de Parte / Proveedor -->
<div class="col-md-6 form-group-animated">
<label for="numero_parte" class="form-label">Número de Parte</label>
<input type="text" id="numero_parte" name="numero_parte" class="form-control">
<div class="col-md-5 form-group-animated">
<label for="numero_parte" class="form-label">Número de Parte *</label>
<input type="text" id="numero_parte" name="numero_parte" class="form-control" required>
</div>
<div class="col-md-6">
<label for="proveedor" class="form-label">Proveedor *</label>
<select id="proveedor" name="proveedor" class="form-select searchable" required>
<div class="col-md-3"></div>
<div class="col-md-4">
<label for="proveedor" class="form-label">Proveedor</label>
<select id="proveedor" name="proveedor" class="form-select searchable">
<option value="">Cargando proveedores…</option>
</select>
</div>
@@ -169,35 +158,42 @@
</div>
<!-- País Origen/Destino -->
<div class="col-md-4">
<label for="pais_origen_destino" class="form-label">País Origen/Destino</label>
<select id="pais_origen_destino" name="pais_origen_destino" class="form-select searchable" required>
<div class="col-md-3">
<label for="pais_origen_destino" class="form-label">País Origen/Destino *</label>
<select id="pais_origen_destino" name="pais_origen_destino" class="form-select searchable">
<option value="">Cargando países…</option>
</select>
</div>
<!-- País Comprador/Vendedor -->
<div class="col-md-4">
<label for="pais_comprador_vendedor" class="form-label">País Comprador/Vendedor</label>
<select id="pais_comprador_vendedor" name="pais_comprador_vendedor" class="form-select searchable" required>
<div class="col-md-3">
<label for="pais_comprador_vendedor" class="form-label">País Comprador/Vendedor *</label>
<select id="pais_comprador_vendedor" name="pais_comprador_vendedor" class="form-select searchable">
<option value="">Cargando países…</option>
</select>
</div>
<!-- Uso de la Mercancía -->
<div class="col-md-4 form-group-animated">
<div class="col-md-3 form-group-animated">
<label for="uso_mercancia" class="form-label">Uso de la Mercancía</label>
<input type="text" id="uso_mercancia" name="uso_mercancia" class="form-control">
</div>
<!-- Estado de la Mercancia -->
<div class="col-md-3 form-group-animated">
<label for="estado_mercancia" class="form-label">Estado de la Mercancía</label>
<input type="text" id="estado_mercancia" name="estado_mercancia" class="form-control">
</div>
<!-- Unidad de Medida -->
<div class="col-md-4">
<div class="col-md-3">
<label for="umc_id" class="form-label">Unidad de Medida *</label>
<select id="umc_id" name="umc_id" class="form-select searchable" required>
<select id="umc_id" name="umc_id" class="form-select searchable">
<option value="">Cargando unidades…</option>
</select>
</div>
<!-- Vinculación -->
<div class="col-md-4">
<div class="col-md-3">
<label for="vinculacion" class="form-label">Vinculación</label>
<select id="vinculacion" name="vinculacion" class="form-select searchable">
<option value="">-- Selecciona --</option>
@@ -208,7 +204,7 @@
</div>
<!-- Preferencia (fijas) -->
<div class="col-md-4">
<div class="col-md-3">
<label for="preferencia" class="form-label">Preferencia</label>
<select id="preferencia" name="preferencia" class="form-select searchable">
<option value="">-- Selecciona --</option>
@@ -220,8 +216,8 @@
</select>
</div>
<!-- Criterio Preferencia / Tipo Mercancía -->
<div class="col-md-6">
<!-- Criterio Preferencia -->
<div class="col-md-3">
<label for="criterio_preferencia" class="form-label">Criterio Preferencia</label>
<!-- Agrega `disabled` al select de criterio -->
<select id="criterio_preferencia" name="criterio_preferencia" class="form-select searchable" disabled>
@@ -231,18 +227,27 @@
<?php endforeach; ?>
</select>
</div>
<div class="col-md-6 form-group-animated">
<!-- Tipo Mercancía -->
<div class="col-md-5 form-group-animated">
<label for="tipo_mercancia" class="form-label">Tipo de Mercancía</label>
<input type="text" id="tipo_mercancia" name="tipo_mercancia" class="form-control">
</div>
<div class="col-md-2"></div>
<!-- Checkboxes -->
<div class="col-md-3 form-group-animated">
<div class="form-check mt-2">
<input class="form-check-input" type="checkbox" id="certificado_origen" name="certificado_origen" value="1">
<label class="form-check-label" for="certificado_origen">Certificado de Origen</label>
</div>
<!-- Certificado de Origen -->
<div class="col-md-5 form-group-animated">
<label for="certificado_origen" class="form-label">Certificado de Origen</label>
<input type="text" id="certificado_origen" name="certificado_origen" class="form-control">
</div>
<!-- Observaciones -->
<div class="col-12 form-group-animated">
<label for="observaciones" class="form-label">Observaciones</label>
<textarea id="observaciones" name="observaciones" class="form-control" rows="2"></textarea>
</div>
<!-- Checkbox -->
<div class="col-md-3 form-group-animated">
<div class="form-check mt-2">
<input class="form-check-input" type="checkbox" id="documento_en_original" name="documento_en_original" value="1">
@@ -251,9 +256,9 @@
</div>
<!-- Ocultos -->
<input type="hidden" name="id_importador" value="<?= $_SESSION['usuario_id'] ?>">
<input type="hidden" name="status" value="1">
<input type="hidden" name="frecuencia_uso" value="1">
<input type="hidden" name="id_importador" value="<?= $_SESSION['usuario_id'] ?>">
<input type="hidden" name="status" value="1">
<input type="hidden" name="frecuencia_uso" value="1">
<!-- Botones -->
<div class="col-12 text-end mt-4 form-group-animated">
@@ -272,6 +277,88 @@
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/js/select2.min.js"></script>
<script>
document.getElementById('altaProductoFrecuenteForm').addEventListener('submit', function(e) {
e.preventDefault();
const sinonimo = document.getElementById('sinonimo').value.trim();
const fraccion = document.getElementById('fraccion').value.trim();
const nico = document.getElementById('nico').value.trim();
const numero_parte = document.getElementById('numero_parte').value.trim();
const pais_o_d = document.getElementById('pais_origen_destino').value;
const pais_c_v = document.getElementById('pais_comprador_vendedor').value;
const unidad_medida = document.getElementById('umc_id').value;
const soloNumRegex = /^[0-9]+$/;
if (!sinonimo) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa el sinónimo.', confirmButtonColor: '#dc3545' });
return document.getElementById('sinonimo').focus();
}
if (!fraccion) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa la fracción.', confirmButtonColor: '#dc3545' });
return document.getElementById('fraccion').focus();
}
if (!soloNumRegex.test(fraccion)) {
Swal.fire({ icon: 'error', title: 'Fracción inválida', text: 'La fracción solo puede contener números', confirmButtonColor: '#dc3545' });
document.getElementById('fraccion').focus();
return;
}
if (!nico) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa el NICO.', confirmButtonColor: '#dc3545' });
return document.getElementById('nico').focus();
}
if (!soloNumRegex.test(nico)) {
Swal.fire({ icon: 'error', title: 'NICO inválido', text: 'El NICO solo puede contener números', confirmButtonColor: '#dc3545' });
document.getElementById('nico').focus();
return;
}
if (!numero_parte) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa el número de parte.', confirmButtonColor: '#dc3545' });
return document.getElementById('numero_parte').focus();
}
// Función helper para hacer focus en elementos con Choices.js
function focusChoicesElement(selectId) {
const choicesContainer = document.querySelector(`#${selectId}`).parentElement.querySelector('.choices');
if (choicesContainer) {
choicesContainer.focus();
}
}
// En tu validación del submit:
if (!pais_o_d) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor selecciona el país de origen.', confirmButtonColor: '#dc3545' });
focusChoicesElement('pais_origen_destino');
return;
}
if (!pais_c_v) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor selecciona el país de destino.', confirmButtonColor: '#dc3545' });
focusChoicesElement('pais_comprador_vendedor');
return;
}
if (!unidad_medida) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor selecciona la unidad de medida.', confirmButtonColor: '#dc3545' });
focusChoicesElement('umc_id');
return;
}
// Obtener todos los inputs y selects para validación
const inputs = document.querySelectorAll('#altaProductoFrecuenteForm input[required], #altaProductoFrecuenteForm select[required]');
let isValid = true;
inputs.forEach(input => {
if (!input.checkValidity()) {
input.classList.add('shake');
isValid = false;
}
});
if (isValid) {
// Si pasa la validación, enviamos el formulario manualmente
this.submit();
}
});
document.addEventListener('DOMContentLoaded', () => {
function fetchJsonOrThrow(url) {
return fetch(url)
@@ -368,7 +455,7 @@
// Script para manejar las animaciones de validación
document.addEventListener('DOMContentLoaded', function() {
const inputs = document.querySelectorAll('input.form-control, select.form_select');
const inputs = document.querySelectorAll('input.form-control, select.form_select');
const selects = document.querySelectorAll('select.form_select');
inputs.forEach(input => {
@@ -412,19 +499,6 @@
}
}
}
// Validación del formulario
document.getElementById('altaProductoFrecuenteForm').addEventListener('submit', function(e) {
e.preventDefault();
let isValid = true;
inputs.forEach(input => {
if (!input.checkValidity()) {
input.classList.add('shake');
isValid = false;
}
});
});
});
</script>

View File

@@ -1,22 +1,13 @@
<!-- views/productos_frecuentes/editar.php -->
<?php
include __DIR__ . '/../partials/sidebar_importador.php';
$vinculaciones = [
'0' => 'No existe',
'1' => 'Existe, no afecta',
'2' => 'Existe y afecta'
];
$criterios = [
'A' => 'Criterio A',
'B' => 'Criterio B',
'C' => 'Criterio C',
'D' => 'Criterio D',
'E' => 'Criterio E',
'F' => 'Criterio F'
];
// Opciones de Vinculación y Criterio Preferencia
$vinculaciones = [ '0' => 'No existe', '1' => 'Existe, no afecta', '2' => 'Existe y afecta' ];
$criterios = [ 'A' => 'Criterio A', 'B' => 'Criterio B', 'C' => 'Criterio C', 'D' => 'Criterio D', 'E' => 'Criterio E', 'F' => 'Criterio F' ];
// Proveedores, unidades y países se cargan por AJAX
// $producto proviene del controlador
?>
<!DOCTYPE html>
<html lang="es">
<head>
@@ -41,9 +32,8 @@
.card-hover:hover { transform: translateY(-8px) scale(1.02); box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15) !important; }
.btn-pulse { animation: pulse 2s infinite; }
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
.fade-in-up { animation: fadeInUp 0.8s ease-out; }
@keyframes fadeInUp {
@@ -63,6 +53,51 @@
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent); transition: left 0.5s; }
.btn-animated:hover::before { left: 100%; }
.form-label { font-weight: 500; }
/* ========== ANIMACIONES PARA INPUTS TEXTO ========== */
.form-control:not(.no-animation) { transition: all 0.3s ease; border: 2px solid #dee2e6; position: relative; }
.form-control:not(.no-animation):focus { border-color: #0d6efd; box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25), 0 0 20px rgba(13, 110, 253, 0.3); transform: translateY(-2px); }
.form-control:not(.no-animation):not(:placeholder-shown) { /*border-color: #198754; background-color: #f8fff9;*/ }
.form-control:not(.no-animation).shake { animation: shake 0.5s ease-in-out; }
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
/* Floating labels para inputs texto */
.form-floating-custom { position: relative; margin-bottom: 1.5rem; }
.form-floating-custom .form-control { padding: 1rem 0.75rem 0.5rem 0.75rem; height: auto; }
.form-floating-custom .form-label { position: absolute; top: 0.75rem; left: 0.75rem; transition: all 0.3s ease; pointer-events: none; color: #6c757d; z-index: 2; }
.form-floating-custom .form-control:focus ~ .form-label,
.form-floating-custom .form-control:not(:placeholder-shown) ~ .form-label { top: 0.25rem; font-size: 0.75rem; color: #0d6efd; font-weight: 600; }
.input-pulse:hover:not(.no-animation) { animation: inputPulse 0.6s ease-in-out; }
@keyframes inputPulse {
0% { transform: scale(1); }
50% { transform: scale(1.02); }
100% { transform: scale(1); }
}
.input-gradient:not(.no-animation) { position: relative; overflow: hidden; }
.input-gradient:not(.no-animation)::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%;
background: linear-gradient(90deg, transparent, rgba(13, 110, 253, 0.3), transparent); transition: left 0.5s; pointer-events: none; z-index: 1; }
.input-gradient:not(.no-animation):focus::before { left: 100%; }
.form-control.valid:not(.no-animation) { /*border-color: #198754; background: linear-gradient(45deg, #fff, #f8fff9);*/ animation: successGlow 1s ease-in-out; }
@keyframes successGlow {
0% { box-shadow: 0 0 5px rgba(25, 135, 84, 0.5); }
50% { box-shadow: 0 0 20px rgba(25, 135, 84, 0.8); }
100% { box-shadow: 0 0 5px rgba(25, 135, 84, 0.5); }
}
/* Animación para los campos del formulario */
.form-group-animated { opacity: 0; transform: translateY(20px); animation: slideUp 0.6s ease-out forwards; }
.form-group-animated:nth-child(1) { animation-delay: 0.1s; }
.form-group-animated:nth-child(2) { animation-delay: 0.2s; }
.form-group-animated:nth-child(3) { animation-delay: 0.3s; }
.form-group-animated:nth-child(4) { animation-delay: 0.4s; }
.form-group-animated:nth-child(5) { animation-delay: 0.5s; }
.form-group-animated:nth-child(6) { animation-delay: 0.6s; }
.form-group-animated:nth-child(7) { animation-delay: 0.7s; }
.form-group-animated:nth-child(8) { animation-delay: 0.8s; }
.form-group-animated:nth-child(9) { animation-delay: 0.9s; }
.form-group-animated:nth-child(10) { animation-delay: 1.0s; }
@keyframes slideUp { to { opacity: 1; transform: translateY(0); } }
</style>
</head>
<body>
@@ -82,65 +117,74 @@
<div class="card p-4 shadow-sm bg-white card-hover position-relative h-auto">
<form id="editarProductoFrecuenteForm" action="/IMPORTADORES/productos_frecuentes/actualizar" method="POST">
<input type="hidden" name="id_producto_frecuente" value="<?= htmlspecialchars($producto['id_producto_frecuente']) ?>">
<div class="row g-3">
<div class="col-md-4">
<label for="sinonimo" class="form-label">Sinónimo *</label>
<div class="row g-3 form-group-animated">
<div class="col-md-6 form-group-animated">
<label for="sinonimo" class="form-label">Sinónimo</label>
<input type="text" id="sinonimo" name="sinonimo" class="form-control"
value="<?= htmlspecialchars($producto['sinonimo']) ?>" required>
value="<?= htmlspecialchars($producto['sinonimo']) ?>">
</div>
<div class="col-md-4">
<label for="fraccion" class="form-label">Fracción *</label>
<input type="text" id="fraccion" name="fraccion" class="form-control"
value="<?= htmlspecialchars($producto['fraccion']) ?>" required>
<div class="col-md-4 form-group-animated">
<label for="fraccion" class="form-label">Fracción</label>
<input type="text" id="fraccion" name="fraccion" class="form-control" maxlegth="8"
value="<?= htmlspecialchars($producto['fraccion']) ?>">
</div>
<div class="col-md-4">
<label for="nico" class="form-label">NICO *</label>
<input type="text" id="nico" name="nico" class="form-control"
value="<?= htmlspecialchars($producto['nico']) ?>" required>
<div class="col-md-2 form-group-animated">
<label for="nico" class="form-label">NICO</label>
<input type="text" id="nico" name="nico" class="form-control" maxlength="2"
value="<?= htmlspecialchars($producto['nico']) ?>">
</div>
<div class="col-md-6">
<div class="col-md-5 form-group-animated">
<label for="numero_parte" class="form-label">Número de Parte</label>
<input type="text" id="numero_parte" name="numero_parte" class="form-control"
<input type="text" id="numero_parte" name="numero_parte" class="form-control"
value="<?= htmlspecialchars($producto['numero_parte']) ?>">
</div>
<div class="col-md-6">
<label for="proveedor" class="form-label">Proveedor *</label>
<select id="proveedor" name="proveedor" class="form-select searchable" required>
<div class="col-md-3"></div>
<div class="col-md-4">
<label for="proveedor" class="form-label">Proveedor</label>
<select id="proveedor" name="proveedor" class="form-select searchable">
<option value="">Cargando proveedores…</option>
</select>
</div>
<div class="col-12">
<div class="col-12 form-group-animated">
<label for="descripcion" class="form-label">Descripción</label>
<textarea id="descripcion" name="descripcion" class="form-control" rows="2"><?= htmlspecialchars($producto['descripcion']) ?></textarea>
</div>
<div class="col-md-4">
<div class="col-md-3">
<label for="pais_origen_destino" class="form-label">País Origen/Destino</label>
<select id="pais_origen_destino" name="pais_origen_destino" class="form-select searchable" required>
<select id="pais_origen_destino" name="pais_origen_destino" class="form-select searchable">
<option value="">Cargando países…</option>
</select>
</div>
<div class="col-md-4">
<div class="col-md-3">
<label for="pais_comprador_vendedor" class="form-label">País Comprador/Vendedor</label>
<select id="pais_comprador_vendedor" name="pais_comprador_vendedor" class="form-select searchable" required>
<select id="pais_comprador_vendedor" name="pais_comprador_vendedor" class="form-select searchable">
<option value="">Cargando países…</option>
</select>
</div>
<div class="col-md-4">
<div class="col-md-3 form-group-animated">
<label for="uso_mercancia" class="form-label">Uso de la Mercancía</label>
<input type="text" id="uso_mercancia" name="uso_mercancia" class="form-control"
value="<?= htmlspecialchars($producto['uso_mercancia']) ?>">
</div>
<div class="col-md-4">
<label for="umc_id" class="form-label">Unidad de Medida *</label>
<select id="umc_id" name="umc_id" class="form-select searchable" required>
<div class="col-md-3 form-group-animated">
<label for="estado_mercancia" class="form-label">Estado de la Mercancía</label>
<input type="text" id="estado_mercancia" name="estado_mercancia" class="form-control"
value="<?= htmlspecialchars($producto['estado_mercancia']) ?>">
</div>
<div class="col-md-3">
<label for="umc_id" class="form-label">Unidad de Medida</label>
<select id="umc_id" name="umc_id" class="form-select searchable">
<option value="">Cargando unidades…</option>
</select>
</div>
<div class="col-md-4">
<div class="col-md-3">
<label for="vinculacion" class="form-label">Vinculación</label>
<select id="vinculacion" name="vinculacion" class="form-select searchable">
<option value="">-- Selecciona --</option>
@@ -151,7 +195,8 @@
<?php endforeach; ?>
</select>
</div>
<div class="col-md-4">
<div class="col-md-3">
<label for="preferencia" class="form-label">Preferencia</label>
<select id="preferencia" name="preferencia" class="form-select searchable">
<option value="">-- Selecciona --</option>
@@ -161,7 +206,7 @@
</select>
</div>
<div class="col-md-6">
<div class="col-md-3">
<label for="criterio_preferencia" class="form-label">Criterio Preferencia</label>
<select id="criterio_preferencia" name="criterio_preferencia" class="form-select searchable" disabled>
<option value="">-- Selecciona --</option>
@@ -172,20 +217,26 @@
<?php endforeach; ?>
</select>
</div>
<div class="col-md-6">
<div class="col-md-5 form-group-animated">
<label for="tipo_mercancia" class="form-label">Tipo de Mercancía</label>
<input type="text" id="tipo_mercancia" name="tipo_mercancia" class="form-control"
value="<?= htmlspecialchars($producto['tipo_mercancia']) ?>">
</div>
<div class="col-md-2"></div>
<div class="col-md-3">
<div class="form-check mt-2">
<input class="form-check-input" type="checkbox" id="certificado_origen" name="certificado_origen" value="1"
<?= $producto['certificado_origen']?'checked':'' ?>>
<label class="form-check-label" for="certificado_origen">Certificado de Origen</label>
</div>
<div class="col-md-5 form-group-animated">
<label for="certificado_origen" class="form-label">Certificado de Origen</label>
<input type="text" id="certificado_origen" name="certificado_origen" class="form-control"
value="<?= htmlspecialchars($producto['certificado_origen']) ?>">
</div>
<div class="col-md-3">
<div class="col-12 form-group-animated">
<label for="observaciones" class="form-label">Observaciones</label>
<textarea id="observaciones" name="observaciones" class="form-control" rows="2"><?= htmlspecialchars($producto['observaciones']) ?></textarea>
</div>
<div class="col-md-3 form-group-animated">
<div class="form-check mt-2">
<input class="form-check-input" type="checkbox" id="documento_en_original" name="documento_en_original" value="1"
<?= $producto['documento_en_original']?'checked':'' ?>>
@@ -194,7 +245,7 @@
</div>
</div>
<div class="mt-4 text-end">
<div class="col-12 mt-4 text-end form-group-animated">
<button type="submit" class="btn btn-primary mt-auto w-auto btn-animated">Actualizar</button>
<a href="/IMPORTADORES/productos_frecuentes" class="btn btn-secondary ms-2 mt-auto w-auto btn-animated">Cancelar</a>
</div>
@@ -206,118 +257,200 @@
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
// Helper para fetch + validación JSON
function fetchJsonOrThrow(url) {
return fetch(url)
.then(resp => {
if (!resp.ok) throw new Error(`HTTP ${resp.status} en ${url}`);
return resp.text();
})
.then(txt => {
try {
return JSON.parse(txt);
} catch (e) {
console.error(`Respuesta no-JSON en ${url}:`, txt);
throw e;
document.getElementById('editarProductoFrecuenteForm').addEventListener('submit', function(e) {
e.preventDefault();
const sinonimo = document.getElementById('sinonimo').value.trim();
const fraccion = document.getElementById('fraccion').value.trim();
const nico = document.getElementById('nico').value.trim();
const numero_parte = document.getElementById('numero_parte').value.trim();
const pais_o_d = document.getElementById('pais_origen_destino').value;
const pais_c_v = document.getElementById('pais_comprador_vendedor').value;
const unidad_medida = document.getElementById('umc_id').value;
const soloNumRegex = /^[0-9]+$/;
if (!sinonimo) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa el sinónimo.', confirmButtonColor: '#dc3545' });
return document.getElementById('sinonimo').focus();
}
if (!fraccion) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa la fracción.', confirmButtonColor: '#dc3545' });
return document.getElementById('fraccion').focus();
}
if (!soloNumRegex.test(fraccion)) {
Swal.fire({ icon: 'error', title: 'Fracción inválida', text: 'La fracción solo puede contener números', confirmButtonColor: '#dc3545' });
document.getElementById('fraccion').focus();
return;
}
if (!nico) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa el NICO.', confirmButtonColor: '#dc3545' });
return document.getElementById('nico').focus();
}
if (!soloNumRegex.test(nico)) {
Swal.fire({ icon: 'error', title: 'NICO inválido', text: 'El NICO solo puede contener números', confirmButtonColor: '#dc3545' });
document.getElementById('nico').focus();
return;
}
if (!numero_parte) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor ingresa el número de parte.', confirmButtonColor: '#dc3545' });
return document.getElementById('numero_parte').focus();
}
// Función helper para hacer focus en elementos con Choices.js
function focusChoicesElement(selectId) {
const choicesContainer = document.querySelector(`#${selectId}`).parentElement.querySelector('.choices');
if (choicesContainer) {
choicesContainer.focus();
}
}
// En tu validación del submit:
if (!pais_o_d) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor selecciona el país de origen.', confirmButtonColor: '#dc3545' });
focusChoicesElement('pais_origen_destino');
return;
}
if (!pais_c_v) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor selecciona el país de destino.', confirmButtonColor: '#dc3545' });
focusChoicesElement('pais_comprador_vendedor');
return;
}
if (!unidad_medida) {
Swal.fire({ icon: 'warning', title: 'Campo requerido', text: 'Por favor selecciona la unidad de medida.', confirmButtonColor: '#dc3545' });
focusChoicesElement('umc_id');
return;
}
// Obtener todos los inputs y selects para validación
const inputs = document.querySelectorAll('#altaProductoFrecuenteForm input[required], #altaProductoFrecuenteForm select[required]');
let isValid = true;
inputs.forEach(input => {
if (!input.checkValidity()) {
input.classList.add('shake');
isValid = false;
}
});
}
// Referencias a los <select>
const selProv = document.getElementById('proveedor');
const selUmc = document.getElementById('umc_id');
const selPor = document.getElementById('pais_origen_destino');
const selPcv = document.getElementById('pais_comprador_vendedor');
const prefEl = document.getElementById('preferencia');
const critEl = document.getElementById('criterio_preferencia');
// Valores previamente guardados (inyectados por PHP)
const savedProv = <?= json_encode($producto['proveedor']) ?>;
const savedUmc = <?= json_encode($producto['umc_id']) ?>;
const savedPor = <?= json_encode($producto['pais_origen_destino']) ?>;
const savedPcv = <?= json_encode($producto['pais_comprador_vendedor']) ?>;
const savedPref = <?= json_encode($producto['preferencia']) ?>;
const savedCrit = <?= json_encode($producto['criterio_preferencia']) ?>;
Promise.all([
fetchJsonOrThrow('/IMPORTADORES/solicitud_importacion/ajax_proveedores'),
fetchJsonOrThrow('/IMPORTADORES/productos_frecuentes/ajax_unidades'),
fetchJsonOrThrow('/IMPORTADORES/productos_frecuentes/ajax_paises')
])
.then(([provData, umcData, paisData]) => {
// Proveedores
selProv.innerHTML = '<option value="">-- Selecciona Proveedor --</option>';
provData.results.forEach(it => {
const o = document.createElement('option');
o.value = it.id;
o.textContent = it.text;
if (it.id == savedProv) o.selected = true;
selProv.appendChild(o);
});
// Unidades de Medida
selUmc.innerHTML = '<option value="">-- Selecciona UMC --</option>';
umcData.results.forEach(it => {
const o = document.createElement('option');
o.value = it.id;
o.textContent = it.text;
if (it.id == savedUmc) o.selected = true;
selUmc.appendChild(o);
});
// Países de Origen/Destino y Comprador/Vendedor
selPor.innerHTML = '<option value="">-- Selecciona País --</option>';
selPcv.innerHTML = '<option value="">-- Selecciona País --</option>';
paisData.results.forEach(it => {
[selPor, selPcv].forEach(sel => {
const o = document.createElement('option');
o.value = it.id;
o.textContent = it.text;
if (sel === selPor && it.id == savedPor) o.selected = true;
if (sel === selPcv && it.id == savedPcv) o.selected = true;
sel.appendChild(o);
});
});
// Inicializar Choices.js en todos los .searchable
document.querySelectorAll('.searchable').forEach(el => {
if (el._choices) el._choices.destroy();
el._choices = new Choices(el, {
searchEnabled: true,
itemSelectText: '',
shouldSort: false
});
});
// Restaurar y controlar Preferencia → Criterio
prefEl.value = savedPref || '';
function updateCriterio() {
if (prefEl.value === 'PROSEC') {
critEl.disabled = false;
critEl._choices.enable();
critEl.value = savedCrit || '';
critEl._choices.setChoiceByValue(savedCrit);
} else {
critEl._choices.removeActiveItems();
critEl._choices.disable();
critEl.disabled = true;
if (isValid) {
// Si pasa la validación, enviamos el formulario manualmente
this.submit();
}
}
// Inicial y evento
updateCriterio();
prefEl.addEventListener('change', updateCriterio);
})
.catch(err => {
console.error('Error en AJAX:', err);
Swal.fire({
icon: 'error',
title: 'Error cargando datos',
text: err.message
});
});
});
</script>
document.addEventListener('DOMContentLoaded', () => {
// Helper para fetch + validación JSON
function fetchJsonOrThrow(url) {
return fetch(url)
.then(resp => {
if (!resp.ok) throw new Error(`HTTP ${resp.status} en ${url}`);
return resp.text();
})
.then(txt => {
try {
return JSON.parse(txt);
} catch (e) {
console.error(`Respuesta no-JSON en ${url}:`, txt);
throw e;
}
});
}
// Referencias a los <select>
const selProv = document.getElementById('proveedor');
const selUmc = document.getElementById('umc_id');
const selPor = document.getElementById('pais_origen_destino');
const selPcv = document.getElementById('pais_comprador_vendedor');
const prefEl = document.getElementById('preferencia');
const critEl = document.getElementById('criterio_preferencia');
// Valores previamente guardados (inyectados por PHP)
const savedProv = <?= json_encode($producto['proveedor']) ?>;
const savedUmc = <?= json_encode($producto['umc_id']) ?>;
const savedPor = <?= json_encode($producto['pais_origen_destino']) ?>;
const savedPcv = <?= json_encode($producto['pais_comprador_vendedor']) ?>;
const savedPref = <?= json_encode($producto['preferencia']) ?>;
const savedCrit = <?= json_encode($producto['criterio_preferencia']) ?>;
Promise.all([
fetchJsonOrThrow('/IMPORTADORES/solicitud_importacion/ajax_proveedores'),
fetchJsonOrThrow('/IMPORTADORES/productos_frecuentes/ajax_unidades'),
fetchJsonOrThrow('/IMPORTADORES/productos_frecuentes/ajax_paises')
])
.then(([provData, umcData, paisData]) => {
// Proveedores
selProv.innerHTML = '<option value="">-- Selecciona Proveedor --</option>';
provData.results.forEach(it => {
const o = document.createElement('option');
o.value = it.id;
o.textContent = it.text;
if (it.id == savedProv) o.selected = true;
selProv.appendChild(o);
});
// Unidades de Medida
selUmc.innerHTML = '<option value="">-- Selecciona UMC --</option>';
umcData.results.forEach(it => {
const o = document.createElement('option');
o.value = it.id;
o.textContent = it.text;
if (it.id == savedUmc) o.selected = true;
selUmc.appendChild(o);
});
// Países de Origen/Destino y Comprador/Vendedor
selPor.innerHTML = '<option value="">-- Selecciona País --</option>';
selPcv.innerHTML = '<option value="">-- Selecciona País --</option>';
paisData.results.forEach(it => {
[selPor, selPcv].forEach(sel => {
const o = document.createElement('option');
o.value = it.id;
o.textContent = it.text;
if (sel === selPor && it.id == savedPor) o.selected = true;
if (sel === selPcv && it.id == savedPcv) o.selected = true;
sel.appendChild(o);
});
});
// Inicializar Choices.js en todos los .searchable
document.querySelectorAll('.searchable').forEach(el => {
if (el._choices) el._choices.destroy();
el._choices = new Choices(el, {
searchEnabled: true,
itemSelectText: '',
shouldSort: false
});
});
// Restaurar y controlar Preferencia → Criterio
prefEl.value = savedPref || '';
function updateCriterio() {
if (prefEl.value === 'PROSEC') {
critEl.disabled = false;
critEl._choices.enable();
critEl.value = savedCrit || '';
critEl._choices.setChoiceByValue(savedCrit);
} else {
critEl._choices.removeActiveItems();
critEl._choices.disable();
critEl.disabled = true;
}
}
// Inicial y evento
updateCriterio();
prefEl.addEventListener('change', updateCriterio);
})
.catch(err => {
console.error('Error en AJAX:', err);
Swal.fire({
icon: 'error',
title: 'Error cargando datos',
text: err.message
});
});
});
</script>
</body>
</html>
</html>

View File

@@ -57,26 +57,19 @@
<?php if (!empty($_SESSION['flash_error'])): ?>
<script>
Swal.fire({
icon: 'error',
title: 'Error',
text: '<?= addslashes($_SESSION['flash_error']) ?>'
});
Swal.fire({ icon: 'error', title: 'Error', text: '<?= addslashes($_SESSION['flash_error']) ?>' });
</script>
<?php unset($_SESSION['flash_error']); endif; ?>
<?php if (!empty($_SESSION['flash_success'])): ?>
<script>
Swal.fire({
icon: 'success',
title: '¡Listo!',
text: '<?= addslashes($_SESSION['flash_success']) ?>'
});
Swal.fire({ icon: 'success', title: '¡Listo!', text: '<?= addslashes($_SESSION['flash_success']) ?>' });
</script>
<?php unset($_SESSION['flash_success']); endif; ?>
<div class="content">
<h4 class="mb-4 animate__animated animate__fadeInDown title_glow">📋 Productos Frecuentes</h4>
<a href="/IMPORTADORES/productos_frecuentes/alta" class="btn btn-success mb-3 mt-auto w-auto btn-animated"> Nuevo Producto</a>
<div class="card p-4 shadow-sm card-hover position-relative h-auto">
<div class="table-responsive">
<table id="tablaProductosFrecuentes" class="table table-striped table-bordered">
@@ -99,50 +92,14 @@
</tr>
</thead>
<tbody>
<?php
$conn = getConnection();
$sql = "
SELECT
pf.id_producto_frecuente,
pf.sinonimo,
pf.fraccion,
pf.nico,
pf.numero_parte,
pf.proveedor AS proveedor_guardado,
u.descripcion AS unidad_de_medida,
por.nombre AS pais_origen_destino,
pc.nombre AS pais_comprador_vendedor,
pf.uso_mercancia,
pf.estado_mercancia,
pf.preferencia,
pf.frecuencia_uso
FROM dbo.productos_frecuentes pf
LEFT JOIN dbo.unidades_medida_apendice7 u
ON pf.umc_id = u.id
LEFT JOIN dbo.paises por
ON pf.pais_origen_destino = por.id_pais
LEFT JOIN dbo.paises pc
ON pf.pais_comprador_vendedor = pc.id_pais
WHERE pf.id_importador = ?
ORDER BY pf.fecha_alta DESC
";
$stmt = sqlsrv_query($conn, $sql, [$_SESSION['usuario_id']]);
if ($stmt === false) {
echo '<pre>', print_r(sqlsrv_errors(), true), '</pre>';
exit;
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)):
?>
<?php foreach ($productos as $row): ?>
<tr>
<td><?= htmlspecialchars($row['id_producto_frecuente']) ?></td>
<td><?= htmlspecialchars($row['sinonimo']) ?></td>
<td><?= htmlspecialchars($row['fraccion']) ?></td>
<td><?= htmlspecialchars($row['nico']) ?></td>
<td><?= htmlspecialchars($row['numero_parte']) ?></td>
<td><?= htmlspecialchars($row['proveedor_guardado']) ?></td>
<td><?= htmlspecialchars($row['nombre_proveedor']) ?></td>
<td><?= htmlspecialchars($row['unidad_de_medida']) ?></td>
<td><?= htmlspecialchars($row['pais_origen_destino']) ?></td>
<td><?= htmlspecialchars($row['pais_comprador_vendedor']) ?></td>
@@ -151,16 +108,12 @@
<td><?= htmlspecialchars($row['preferencia']) ?></td>
<td><?= htmlspecialchars($row['frecuencia_uso']) ?></td>
<td class="text-center">
<a href="/IMPORTADORES/productos_frecuentes/editar?id=<?= $row['id_producto_frecuente'] ?>"
class="btn btn-sm btn-primary mt-auto w-auto btn-animated">✏️</a>
<button class="btn btn-sm btn-danger mt-auto w-auto btn-animated"
onclick="confirmDelete(<?= $row['id_producto_frecuente'] ?>)">
🗑️
</button>
<a href="/IMPORTADORES/productos_frecuentes/editar?id=<?= $row['id_producto_frecuente'] ?>" class="btn btn-sm btn-primary mt-auto w-auto btn-animated">✏️</a>
<button class="btn btn-sm btn-danger mt-auto w-auto btn-animated" onclick="confirmDelete(<?= $row['id_producto_frecuente'] ?>)">🗑️</button>
</td>
</tr>
<?php endwhile; ?>
</tbody>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
@@ -193,6 +146,11 @@
}
});
}
<?php if (isset($_GET['deleted']) && $_GET['deleted']==='ok'): ?>
Swal.fire({ icon: 'success', title: 'Producto eliminado', text: 'Ya no aparecerá en tu lista.', confirmButtonColor: '#198754' });
<?php endif; ?>
</script>
</body>
</html>
</html>