Suggestions

This commit is contained in:
2025-07-22 13:41:13 -06:00
parent 8bb0f84fd1
commit b18c05d52a
5 changed files with 478 additions and 473 deletions

View File

@@ -80,13 +80,11 @@
.form-group-animated:nth-child(10) { animation-delay: 1.0s; }
@keyframes slideUp { to { opacity: 1; transform: translateY(0); } }
/* Estilos para las sugerencias de autocompletado */
.autocomplete-suggestions { position: absolute; width: calc(100% - 2px); /* Ajustar al ancho del input */ background: white; border: 1px solid #ced4da; border-top: none;
border-radius: 0 0 4px 4px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); z-index: 1000; max-height: 200px; overflow-y: auto; display: none; /* Inicialmente oculto */ }
.autocomplete-item { padding: 8px 12px; cursor: pointer; transition: background-color 0.2s; }
.autocomplete-item:hover, .autocomplete-item.active { background-color: #f8f9fa; }
.autocomplete-item strong { display: block; margin-bottom: 2px; }
.autocomplete-item .text-muted { font-size: 0.85em; color: #6c757d; }
.cursor-pointer { cursor: pointer; }
#global-autocomplete-suggestions { box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important; border: 1px solid #dee2e6 !important; width: calc(100% - 30px) !important; /* Ajusta según el padding de tu contenedor */ }
#global-autocomplete-suggestions .autocomplete-item { transition: background-color 0.15s ease; }
#global-autocomplete-suggestions .autocomplete-item:hover,
#global-autocomplete-suggestions .autocomplete-item.active { background-color: #f8f9fa !important; }
#global-autocomplete-suggestions .autocomplete-item:last-child { border-bottom: none; }
/* Estilos para validación */
.choices.required .choices__inner { border: 1px solid #ced4da; }
.choices.is-invalid .choices__inner { border: 1px solid #dc3545; background-color: #fff5f5; }
@@ -666,142 +664,243 @@
$(document).ready(function() {
let timeoutId;
let currentRequest = null;
let currentInput = null; // Para rastrear qué input está activo
// Crear un único contenedor de sugerencias al final del body
if ($('#global-autocomplete-suggestions').length === 0) {
$('#tabla-partidas').after(`
<div id="global-autocomplete-suggestions"
class="bg-white border shadow-lg w-100"
style="display: none;
max-height: 200px;
overflow-y: auto;
border-radius: 4px;
margin-top: 5px;
margin-bottom: 10px;">
</div>
`);
}
const $globalSuggestions = $('#global-autocomplete-suggestions');
// Función para configurar autocompletado en un input
function setupAutocomplete(input) {
const $input = $(input);
// Crear contenedor de sugerencias si no existe
if ($input.siblings('.autocomplete-suggestions').length === 0) {
$input.after('<div class="autocomplete-suggestions position-absolute w-100 bg-white border border-top-0 shadow-sm" style="max-height: 200px; overflow-y: auto; z-index: 1000; display: none;"></div>');
}
const $suggestions = $input.siblings('.autocomplete-suggestions');
const $row = $input.closest('tr');
const $row = $input.closest('tr');
$input.off('input').on('input', function() {
const query = $(this).val().trim();
currentInput = $input; // Guardar referencia del input activo
clearTimeout(timeoutId);
if (currentRequest) currentRequest.abort();
if (query.length < 2) {
$suggestions.hide().empty();
$globalSuggestions.hide().empty();
return;
}
timeoutId = setTimeout(() => {
currentRequest = $.ajax({
url: '/IMPORTADORES/solicitud_importacion/buscar_productos',
method: 'GET',
data: { q: query },
url: '/IMPORTADORES/solicitud_importacion/buscar_productos',
method: 'GET',
data: { q: query },
dataType: 'json',
success: function(productos) {
$suggestions.empty();
success: function(productos) {
$globalSuggestions.empty();
if (productos && productos.length > 0) {
productos.forEach(function(producto) {
const $item = $(`
<div class="autocomplete-item px-3 py-2 cursor-pointer border-bottom">
<strong>${producto.sinonimo}</strong>
<div class="row mb-3 small text-muted">
<span>${producto.fraccion || 'Sin fracción'}</span>
<span>${producto.descripcion?.substring(0, 50) || ''}</span>
<div class="autocomplete-item px-3 py-2 cursor-pointer border-bottom hover-bg-light"
style="cursor: pointer;">
<strong style="color: #333;">${producto.sinonimo}</strong>
<div class="small text-muted mt-1">
<div>Fracción: ${producto.fraccion || 'Sin fracción'}</div>
<div>Desc: ${producto.descripcion?.substring(0, 50) || ''}${producto.descripcion?.length > 50 ? '...' : ''}</div>
</div>
</div>
`).data('producto', producto);
$item.on('click', function() { selectProduct($(this).data('producto'), $row); });
$suggestions.append($item);
// Efectos hover
$item.on('mouseenter', function() {
$globalSuggestions.find('.autocomplete-item').removeClass('active');
$(this).addClass('active').css('background-color', '#f8f9fa');
}).on('mouseleave', function() {
$(this).removeClass('active').css('background-color', '');
});
$item.on('click', function() {
selectProduct($(this).data('producto'), currentInput.closest('tr'));
});
$globalSuggestions.append($item);
});
$suggestions.show();
// Posicionar y mostrar
$globalSuggestions.show();
}
else {
$globalSuggestions.hide();
}
else { $suggestions.hide(); }
},
error: function(xhr, status, error) {
if (status !== 'abort') { console.error("Error en búsqueda:", error); }
$suggestions.hide();
if (status !== 'abort') {
console.error("Error en búsqueda:", error);
}
$globalSuggestions.hide();
},
complete: function() { currentRequest = null; }
complete: function() {
currentRequest = null;
}
});
}, 300);
});
// Manejar eventos de foco
$input.on('focus', function() {
currentInput = $input;
});
// Manejar teclado
$input.on('keydown', function(e) {
const $items = $suggestions.find('.autocomplete-item');
if (!$globalSuggestions.is(':visible')) return;
const $items = $globalSuggestions.find('.autocomplete-item');
const $active = $items.filter('.active');
switch(e.key) {
case 'ArrowDown':
e.preventDefault();
$items.removeClass('active').css('background-color', '');
const $next = $active.length ? $active.next() : $items.first();
$items.removeClass('active');
$next.addClass('active');
$next.addClass('active').css('background-color', '#f8f9fa');
// Scroll automático
const containerHeight = $globalSuggestions.height();
const itemTop = $next.position().top;
const itemHeight = $next.outerHeight();
if (itemTop + itemHeight > containerHeight) {
$globalSuggestions.scrollTop($globalSuggestions.scrollTop() + itemHeight);
}
break;
case 'ArrowUp':
e.preventDefault();
$items.removeClass('active').css('background-color', '');
const $prev = $active.length ? $active.prev() : $items.last();
$items.removeClass('active');
$prev.addClass('active');
$prev.addClass('active').css('background-color', '#f8f9fa');
// Scroll automático
if ($prev.position().top < 0) {
$globalSuggestions.scrollTop($globalSuggestions.scrollTop() - $prev.outerHeight());
}
break;
case 'Enter':
if ($active.length) {
e.preventDefault();
selectProduct($active.data('producto'), $row);
selectProduct($active.data('producto'), $input.closest('tr'));
}
break;
case 'Tab':
if ($suggestions.is(':visible')) {
if ($globalSuggestions.is(':visible')) {
e.preventDefault();
const $first = $items.first();
if ($first.length) selectProduct($first.data('producto'), $row);
if ($first.length) {
selectProduct($first.data('producto'), $input.closest('tr'));
}
}
break;
case 'Escape':
$suggestions.hide();
$globalSuggestions.hide();
break;
}
});
// Ocultar al hacer clic fuera
$(document).on('click', function(e) { if (!$input.is(e.target) && !$suggestions.is(e.target) && !$suggestions.has(e.target).length) { $suggestions.hide(); } });
}
// Ocultar sugerencias al hacer clic fuera o al hacer scroll
$(document).on('click', function(e) {
if (!currentInput ||
(!currentInput.is(e.target) &&
!$globalSuggestions.is(e.target) &&
!$globalSuggestions.has(e.target).length)) {
$globalSuggestions.hide();
}
});
// Ocultar al hacer scroll (opcional)
$(window).on('scroll resize', function() {
if ($globalSuggestions.is(':visible') && currentInput) {
// Reposicionar en lugar de ocultar
positionGlobalSuggestions(currentInput);
}
});
// Función para seleccionar un producto
function selectProduct(producto, $row) {
// Campos básicos
$row.find('input[name*="[descripcion]"]').val(producto.sinonimo);
// Tasa preferencial
if (producto.preferencia) {
const $select = $row.find('select[name*="[tasa_preferencial]"]');
if ($select[0] && $select[0]._choices) { $select[0]._choices.setChoiceByValue(producto.preferencia); }
else { $select.val(producto.preferencia).trigger('change'); }
if ($select[0] && $select[0]._choices) {
$select[0]._choices.setChoiceByValue(producto.preferencia);
} else {
$select.val(producto.preferencia).trigger('change');
}
}
// Unidad de medida
if (producto.umc_id) {
const $select = $row.find('select[name*="[unidad_comercial_id]"]');
setTimeout(() => {
if ($select[0] && $select[0]._choices) { $select[0]._choices.setChoiceByValue(producto.umc_id.toString()); }
else { $select.val(producto.umc_id).trigger('change'); }
if ($select[0] && $select[0]._choices) {
$select[0]._choices.setChoiceByValue(producto.umc_id.toString());
} else {
$select.val(producto.umc_id).trigger('change');
}
}, 50);
}
// Número de parte
if (producto.numero_parte) { $row.find('input[name*="[oma_factura]"]').val(producto.numero_parte); }
if (producto.numero_parte) {
$row.find('input[name*="[oma_factura]"]').val(producto.numero_parte);
}
// Incrementar frecuencia
$.ajax({
url: '/IMPORTADORES/solicitud_importacion/incrementar_frecuencia',
url: '/IMPORTADORES/solicitud_importacion/incrementar_frecuencia',
method: 'POST',
data: { producto_id: producto.id }
data: { producto_id: producto.id }
});
// Ocultar sugerencias
$row.find('.autocomplete-suggestions').hide();
$globalSuggestions.hide();
// Enfocar el siguiente campo si existe
const $nextInput = $row.next('tr').find('.descripcion-input');
if ($nextInput.length) {
setTimeout(() => $nextInput.focus(), 100);
}
}
// Inicializar autocompletado en inputs existentes
$('.descripcion-input').each(function() { setupAutocomplete(this); });
$('.descripcion-input').each(function() {
setupAutocomplete(this);
});
// Configurar autocompletado para nuevas filas
$('#add-partida').on('click', function() { setTimeout(function() { $('.descripcion-input').last().each(function() { setupAutocomplete(this); }); }, 100); });
$('#add-partida').on('click', function() {
setTimeout(function() {
$('.descripcion-input').last().each(function() {
setupAutocomplete(this);
});
}, 100);
});
});
</script>

View File

@@ -81,13 +81,11 @@
.form-group-animated:nth-child(10) { animation-delay: 1.0s; }
@keyframes slideUp { to { opacity: 1; transform: translateY(0); } }
/* Estilos para las sugerencias de autocompletado */
.autocomplete-suggestions { position: absolute; width: calc(100% - 2px); /* Ajustar al ancho del input */ background: white; border: 1px solid #ced4da; border-top: none;
border-radius: 0 0 4px 4px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); z-index: 1000; max-height: 200px; overflow-y: auto; display: none; /* Inicialmente oculto */ }
.autocomplete-item { padding: 8px 12px; cursor: pointer; transition: background-color 0.2s; }
.autocomplete-item:hover, .autocomplete-item.active { background-color: #f8f9fa; }
.autocomplete-item strong { display: block; margin-bottom: 2px; }
.autocomplete-item .text-muted { font-size: 0.85em; color: #6c757d; }
.cursor-pointer { cursor: pointer; }
#global-autocomplete-suggestions { box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important; border: 1px solid #dee2e6 !important; width: calc(100% - 30px) !important; /* Ajusta según el padding de tu contenedor */ }
#global-autocomplete-suggestions .autocomplete-item { transition: background-color 0.15s ease; }
#global-autocomplete-suggestions .autocomplete-item:hover,
#global-autocomplete-suggestions .autocomplete-item.active { background-color: #f8f9fa !important; }
#global-autocomplete-suggestions .autocomplete-item:last-child { border-bottom: none; }
/* Estilos para validación */
.choices.required .choices__inner { border: 1px solid #ced4da; }
.choices.is-invalid .choices__inner { border: 1px solid #dc3545; background-color: #fff5f5; }
@@ -361,6 +359,26 @@
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/js/select2.min.js"></script>
<script>
// Variables globales para el autocompletado
let timeoutId;
let currentRequest = null;
let currentInput = null;
// ✅ 1. INICIALIZACIÓN PRINCIPAL
document.addEventListener('DOMContentLoaded', function() {
const proveedorActual = '<?= htmlspecialchars($proveedor_clave_actual ?? '') ?>';
console.log('📦 Proveedor actual:', proveedorActual);
// Inicializar Choices.js en todos los selects
cargarProveedores(proveedorActual).then(() => {
document.querySelectorAll('.searchable').forEach(safeInitializeChoices);
});
// Inicializar el sistema de autocompletado
initAutocompleteSystem();
});
// ✅ 2. FUNCIÓN PARA INICIALIZAR CHOICES.JS
function safeInitializeChoices(element) {
if (!element._choices) {
const isRequired = element.hasAttribute('required');
@@ -370,45 +388,47 @@
}
element._choices = new Choices(element, {
searchEnabled: true,
searchEnabled: true,
itemSelectText: '',
shouldSort: false,
silent: true
shouldSort: false,
silent: true
});
if (isRequired) {
const container = element.closest('.choices');
if (container) { container.classList.add('required'); }
if (container) container.classList.add('required');
element.addEventListener('change', validateChoice.bind(null, element));
}
}
}
// ✅ 1. INICIALIZACIÓN PRINCIPAL
document.addEventListener('DOMContentLoaded', function() {
const proveedorActual = '<?= htmlspecialchars($proveedor_clave_actual ?? '') ?>';
console.log('📦 Proveedor actual:', proveedorActual);
cargarProveedores(proveedorActual).then(() => {
document.querySelectorAll('.searchable').forEach(el => {
// Destruir instancia previa si existe
if (el.choicesInstance) el.choicesInstance.destroy();
const instance = new Choices(el, {
searchEnabled: true,
itemSelectText: '',
shouldSort: false
});
// Guardar instancia
el.choicesInstance = instance;
});
});
});
// ✅ 2. FUNCIÓN PARA CARGAR PROVEEDORES (CON PROMESA)
// ✅ 3. FUNCIÓN PARA VALIDAR CAMPOS CHOICES
function validateChoice(selectElement) {
const choicesInstance = selectElement._choices;
if (choicesInstance) {
const container = selectElement.closest('.choices');
const hasValue = choicesInstance.getValue(true).length > 0;
const isRequired = selectElement.hasAttribute('data-required');
if (isRequired) {
if (hasValue) {
container.classList.remove('is-invalid');
container.classList.add('is-valid');
} else {
container.classList.remove('is-valid');
container.classList.add('is-invalid');
}
}
}
}
// ✅ 4. FUNCIÓN PARA CARGAR PROVEEDORES
function cargarProveedores(proveedorActual) {
const proveedorEl = document.getElementById('proveedor_id');
// Asegurarse que el nombre sea consistente
proveedorEl.name = 'proveedor_id';
return fetch('/IMPORTADORES/solicitud_importacion/ajax_proveedores')
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
@@ -418,47 +438,42 @@
proveedorEl.innerHTML = '<option value="">-- Selecciona Proveedor --</option>';
json.results.forEach(item => {
const opt = document.createElement('option');
opt.value = item.id;
const opt = document.createElement('option');
opt.value = item.id;
opt.textContent = item.text;
if (String(item.id) === proveedorActual) {
opt.selected = true;
}
proveedorEl.appendChild(opt);
});
// Forzar manualmente el value
proveedorEl.value = proveedorActual;
console.log('✅ Proveedores cargados. Proveedor actual:', proveedorActual);
console.log('🧪 Select value actual (después de asignar):', proveedorEl.value);
if (proveedorActual) {
proveedorEl.value = proveedorActual;
}
})
.catch(err => {
console.error('❌ Error cargando proveedores:', err);
proveedorEl.innerHTML = '<option value="">Error cargando proveedores</option>';
});
}
// ✅ 3. AGREGAR PARTIDAS - VERSIÓN CORREGIDA
// ✅ 5. AGREGAR PARTIDAS
document.getElementById('add-partida').addEventListener('click', () => {
const tbody = document.querySelector('#tabla-partidas tbody');
const rows = tbody.querySelectorAll('tr');
const idx = rows.length; // Esto asegura índices únicos y secuenciales
const row = document.createElement('tr');
const idx = tbody.querySelectorAll('tr').length;
const row = document.createElement('tr');
row.innerHTML = `
<td>
<div class="position-relative">
<input name="partidas[${idx}][descripcion]" class="form-control w-auto descripcion-input" required autocomplete="off">
<div class="autocomplete-suggestions position-absolute w-100 bg-white border border-top-0 shadow-sm"
style="max-height: 200px; overflow-y: auto; z-index: 1000; display: none;"></div>
</div>
</td>
<td><input name="partidas[${idx}][cantidad_comercial]" type="number" step="0.0001" class="form-control w-auto" min="0" required></td>
<td><input name="partidas[${idx}][cantidad_tarifa]" type="number" step="0.0001" class="form-control w-auto" min="0"></td>
<td>
<select name="partidas[${idx}][unidad_comercial_id]" class="form-select searchable">
<select name="partidas[${idx}][unidad_comercial_id]" class="form-select searchable" data-required="true">
<option value="">-- Unidad --</option>
<?php foreach($unidades_medida as $um): ?>
<option value="<?= htmlspecialchars($um['id']) ?>"><?= htmlspecialchars($um['descripcion']) ?></option>
@@ -468,7 +483,7 @@
<td><input name="partidas[${idx}][valor_factura]" type="number" step="0.01" class="form-control valor-partida w-auto" min="0"></td>
<td><input name="partidas[${idx}][peso_bruto]" type="number" step="0.0001" class="form-control w-auto" min="0"></td>
<td>
<select name="partidas[${idx}][tasa_preferencial]" class="form-select searchable">
<select name="partidas[${idx}][tasa_preferencial]" class="form-select searchable" data-required="true">
<option value="">-- Selecciona --</option>
<option>General</option>
<option>TLC</option>
@@ -481,382 +496,271 @@
<td class="hide"><input name="partidas[${idx}][oma_factura]" class="form-control w-auto"></td>
<td><button type="button" class="btn btn-danger btn-sm remove-row mt-auto w-auto btn-animated">✖️</button></td>
`;
tbody.appendChild(row);
// Inicializamos Choices en los nuevos selects
// Inicializar Choices en los nuevos selects
setTimeout(() => {
row.querySelectorAll('.searchable').forEach(el => {
if (!el._choices) {
el._choices = new Choices(el, {
searchEnabled: true,
itemSelectText: '',
shouldSort: false,
silent: true
});
}
safeInitializeChoices(el);
});
// Configurar autocompletado para el nuevo campo de descripción
// Configurar autocompletado para el nuevo campo
setupAutocomplete(row.querySelector('.descripcion-input'));
}, 50);
});
// ✅ 4. REMOVER PARTIDAS
// ✅ 6. REMOVER PARTIDAS
document.querySelector('#tabla-partidas tbody').addEventListener('click', e => {
if (e.target.matches('.remove-row')) {
// Destruir instancia de Choices.js antes de remover la fila
const row = e.target.closest('tr');
row.querySelectorAll('.searchable').forEach(el => {
if (el.choicesInstance) {
el.choicesInstance.destroy();
}
if (el._choices) el._choices.destroy();
});
row.remove();
}
});
// ✅ 5. CONTROLAR OVERFLOW DE LA TABLA
// ✅ 7. CONTROLAR OVERFLOW DE LA TABLA
document.addEventListener('click', function(e) {
const tableContainer = document.querySelector('.table-responsive');
if (!tableContainer) return;
if (e.target.closest('.choices__inner')) {
tableContainer.style.overflow = 'visible';
} else {
tableContainer.style.overflow = 'auto';
}
});
// ✅ 6. VALIDACIÓN DEL FORMULARIO
$(document).ready(function() {
$('#solicitudForm').submit(function(e){
const total = parseFloat($('#valor_factura').val()) || 0;
let sum = 0;
$('.valor-partida').each(function(){ sum += parseFloat($(this).val()) || 0; });
if(Math.abs(sum - total) > 0.001){
e.preventDefault();
Swal.fire({ icon: 'error', title: 'Error de validación', text: `La suma de partidas (${sum.toFixed(2)}) no coincide con Valor Factura (${total.toFixed(2)}).` });
}
});
});
document.addEventListener('DOMContentLoaded', function() {
const transportistaSelect = document.getElementById('transportista_id');
const choferSelect = document.getElementById('chofer_id');
// Guardar todas las opciones de choferes originales (para fallback)
const allChoferes = Array.from(choferSelect.querySelectorAll('option')).slice(1); // Excluir la primera opción vacía
// Obtener valores actuales (para modo edición)
const transportistaActual = transportistaSelect.value;
const choferActual = choferSelect.value;
// Crear un mapa de choferes por transportista desde las opciones cargadas
const choferesPorTransportista = {};
allChoferes.forEach(option => {
const transportistaId = option.getAttribute('data-transportista');
if (transportistaId) {
if (!choferesPorTransportista[transportistaId]) {
choferesPorTransportista[transportistaId] = [];
// ✅ 8. VALIDACIÓN DEL FORMULARIO
document.getElementById('solicitudForm').addEventListener('submit', function(e) {
// Validar selects de Choices.js
let isValid = true;
document.querySelectorAll('.searchable[data-required]').forEach(el => {
validateChoice(el);
const choicesInstance = el._choices;
if (choicesInstance && choicesInstance.getValue(true).length === 0) {
isValid = false;
// Desplazarse al primer error
if (isValid === false) {
el.closest('.choices').scrollIntoView({ behavior: 'smooth', block: 'center' });
}
choferesPorTransportista[transportistaId].push({
id_chofer: option.value,
nombre: option.textContent.trim()
});
}
});
// Debug: mostrar el cache inicial
console.log('Cache de choferes por transportista:', choferesPorTransportista);
// Inicializar Choices.js si está disponible
let choferChoices = null;
if (typeof Choices !== 'undefined') {
choferChoices = new Choices(choferSelect, {
searchEnabled: true,
placeholderValue: '-- Selecciona Transportista primero --',
noResultsText: 'No se encontraron resultados',
itemSelectText: '',
searchPlaceholderValue: 'Buscar chofer...'
// Validar suma de partidas
const total = parseFloat(document.getElementById('valor_factura').value) || 0;
let sum = 0;
document.querySelectorAll('.valor-partida').forEach(input => {
sum += parseFloat(input.value) || 0;
});
if (Math.abs(sum - total) > 0.001) {
e.preventDefault();
Swal.fire({
icon: 'error',
title: 'Error de validación',
text: `La suma de partidas (${sum.toFixed(2)}) no coincide con Valor Factura (${total.toFixed(2)}).`
});
return;
}
if (!isValid) {
e.preventDefault();
Swal.fire({
icon: 'error',
title: 'Campos requeridos',
text: 'Por favor complete todos los campos obligatorios marcados en rojo',
confirmButtonColor: '#3085d6'
});
}
// Función para filtrar choferes por transportista
function filtrarChoferes(transportistaId) {
// Limpiar opciones excepto la primera
if (choferChoices) { choferChoices.clearStore(); }
else { choferSelect.innerHTML = '<option value="">-- Selecciona Chofer --</option>'; }
if (transportistaId) {
// Intentar usar datos locales primero (más rápido)
if (choferesPorTransportista[transportistaId] && choferesPorTransportista[transportistaId].length > 0) {
console.log('Usando datos locales para transportista:', transportistaId);
cargarChoferes(choferesPorTransportista[transportistaId]);
} else {
// Si no hay datos locales, hacer petición AJAX
console.log('Haciendo petición AJAX para transportista:', transportistaId);
mostrarCargando();
fetch(`/IMPORTADORES/solicitud_importacion/obtenerChoferesPorTransportista?transportista_id=${transportistaId}`)
.then(response => {
console.log('Response status:', response.status);
if (!response.ok) { return response.json().then(data => { throw new Error(data.error || `Error ${response.status}`); }); }
return response.json();
})
.then(choferes => {
console.log('Choferes recibidos:', choferes);
// Guardar en cache local para futuras consultas
choferesPorTransportista[transportistaId] = choferes;
cargarChoferes(choferes);
})
.catch(error => {
console.error('Error al cargar choferes:', error);
mostrarError();
});
}
}
else {
// Si no hay transportista seleccionado, mostrar mensaje
mostrarSeleccionarTransportista();
}
}
// Función para mostrar estado de carga
function mostrarCargando() {
if (choferChoices) {
choferChoices.clearStore();
choferChoices.setChoices([{
value: '',
label: '-- Cargando choferes... --',
disabled: true
}], 'value', 'label', true);
}
else { choferSelect.innerHTML = '<option value="">-- Cargando choferes... --</option>'; }
}
// Función para mostrar mensaje de seleccionar transportista
function mostrarSeleccionarTransportista() {
if (choferChoices) {
choferChoices.clearStore();
choferChoices.setChoices([{
value: '',
label: '-- Selecciona Transportista primero --',
disabled: true
}], 'value', 'label', true);
}
else { choferSelect.innerHTML = '<option value="">-- Selecciona Transportista primero --</option>'; }
}
// Función para mostrar error
function mostrarError() {
const errorMessage = '-- Error al cargar choferes --';
if (choferChoices) {
choferChoices.clearStore();
choferChoices.setChoices([{
value: '',
label: errorMessage,
disabled: true
}], 'value', 'label', true);
}
else { choferSelect.innerHTML = `<option value="">${errorMessage}</option>`; }
}
// Función para cargar choferes en el select
function cargarChoferes(choferes) {
const opciones = [{
value: '',
label: '-- Selecciona Chofer --',
disabled: false
}];
choferes.forEach(chofer => {
opciones.push({
value: chofer.id_chofer,
label: chofer.nombre,
disabled: false
});
});
if (choferChoices) {
choferChoices.clearStore();
choferChoices.setChoices(opciones, 'value', 'label', true);
// Restaurar selección actual si es válida
if (choferActual && choferes.some(c => c.id_chofer == choferActual)) {
choferChoices.setChoiceByValue(choferActual);
}
} else {
choferSelect.innerHTML = '';
opciones.forEach(opcion => {
const option = document.createElement('option');
option.value = opcion.value;
option.textContent = opcion.label;
if (opcion.disabled) option.disabled = true;
choferSelect.appendChild(option);
});
// Restaurar selección actual si es válida
if (choferActual && choferes.some(c => c.id_chofer == choferActual)) { choferSelect.value = choferActual; }
}
}
// Inicializar el filtro al cargar la página (para modo edición)
if (transportistaActual) { filtrarChoferes(transportistaActual); }
else { mostrarSeleccionarTransportista(); }
// Event listener para cambio de transportista
transportistaSelect.addEventListener('change', function() {
const transportistaId = this.value;
filtrarChoferes(transportistaId);
});
// Event listener para validar que se seleccione un chofer válido
choferSelect.addEventListener('change', function() {
const choferSeleccionado = this.value;
if (choferSeleccionado && !transportistaSelect.value) {
alert('Por favor, selecciona un transportista primero.');
this.value = '';
if (choferChoices) { choferChoices.setChoiceByValue(''); }
}
});
});
$(document).ready(function() {
let timeoutId;
let currentRequest = null;
// Función para configurar autocompletado
function setupAutocomplete(input) {
const $input = $(input);
// Crear contenedor de sugerencias si no existe
if ($input.siblings('.autocomplete-suggestions').length === 0) { $input.after('<div class="autocomplete-suggestions position-absolute w-100 bg-white border border-top-0 shadow-sm" style="max-height: 200px; overflow-y: auto; z-index: 1000; display: none;"></div>'); }
const $suggestions = $input.siblings('.autocomplete-suggestions');
const $row = $input.closest('tr');
$input.on('input', function() {
const query = $(this).val().trim();
clearTimeout(timeoutId);
if (currentRequest) currentRequest.abort();
if (query.length < 2) {
$suggestions.hide().empty();
return;
}
timeoutId = setTimeout(() => {
currentRequest = $.ajax({
url: '/IMPORTADORES/solicitud_importacion/buscar_productos',
method: 'GET',
data: { q: query },
dataType: 'json',
success: function(productos) {
$suggestions.empty();
if (productos && productos.length > 0) {
productos.forEach(function(producto) {
const $item = $(`
<div class="autocomplete-item px-3 py-2 cursor-pointer border-bottom">
<strong>${producto.sinonimo}</strong>
<div class="row mb-3 small text-muted">
<span>${producto.fraccion || 'Sin fracción'}</span>
<span>${producto.descripcion?.substring(0, 50) || ''}</span>
</div>
</div>
`).data('producto', producto);
$item.on('click', function() { selectProduct($(this).data('producto'), $row); });
$suggestions.append($item);
});
$suggestions.show();
}
else { $suggestions.hide(); }
},
error: function(xhr, status, error) {
if (status !== 'abort') { console.error("Error en búsqueda:", error); }
$suggestions.hide();
},
complete: function() { currentRequest = null; }
});
}, 300);
});
// Manejar teclado
$input.on('keydown', function(e) {
const $items = $suggestions.find('.autocomplete-item');
const $active = $items.filter('.active');
switch(e.key) {
case 'ArrowDown':
e.preventDefault();
const $next = $active.length ? $active.next() : $items.first();
$items.removeClass('active');
$next.addClass('active');
break;
case 'ArrowUp':
e.preventDefault();
const $prev = $active.length ? $active.prev() : $items.last();
$items.removeClass('active');
$prev.addClass('active');
break;
case 'Enter':
if ($active.length) {
e.preventDefault();
selectProduct($active.data('producto'), $row);
}
break;
case 'Tab':
if ($suggestions.is(':visible')) {
e.preventDefault();
const $first = $items.first();
if ($first.length) selectProduct($first.data('producto'), $row);
}
break;
case 'Escape':
$suggestions.hide();
break;
}
});
// Ocultar al hacer clic fuera
$(document).on('click', function(e) { if (!$input.is(e.target) && !$suggestions.is(e.target) && !$suggestions.has(e.target).length) { $suggestions.hide(); } });
// ✅ 9. SISTEMA DE AUTOCOMPLETADO
function initAutocompleteSystem() {
// Crear contenedor de sugerencias si no existe
if (!document.getElementById('global-autocomplete-suggestions')) {
const suggestionsDiv = document.createElement('div');
suggestionsDiv.id = 'global-autocomplete-suggestions';
suggestionsDiv.className = 'bg-white border shadow-sm w-100';
suggestionsDiv.style.cssText = 'display: none; max-height: 200px; overflow-y: auto; border-radius: 4px; margin-top: 5px; margin-bottom: 10px;';
document.querySelector('#tabla-partidas').after(suggestionsDiv);
}
// Función para seleccionar un producto
function selectProduct(producto, $row) {
// Campos básicos
$row.find('input[name*="[descripcion]"]').val(producto.sinonimo);
// Tasa preferencial
if (producto.preferencia) {
const $select = $row.find('select[name*="[tasa_preferencial]"]');
if ($select[0] && $select[0]._choices) { $select[0]._choices.setChoiceByValue(producto.preferencia); }
else { $select.val(producto.preferencia).trigger('change'); }
}
// Unidad de medida
if (producto.umc_id) {
const $select = $row.find('select[name*="[unidad_comercial_id]"]');
setTimeout(() => {
if ($select[0] && $select[0]._choices) { $select[0]._choices.setChoiceByValue(producto.umc_id.toString()); }
else { $select.val(producto.umc_id).trigger('change'); }
}, 50);
}
// Número de parte
if (producto.numero_parte) { $row.find('input[name*="[oma_factura]"]').val(producto.numero_parte); }
// Incrementar frecuencia
$.ajax({
url: '/IMPORTADORES/solicitud_importacion/incrementar_frecuencia',
method: 'POST',
data: { producto_id: producto.id }
});
// Ocultar sugerencias
$row.find('.autocomplete-suggestions').hide();
}
// Inicializar autocompletado en inputs existentes
$('.descripcion-input').each(function() { setupAutocomplete(this); });
// Configurar autocompletado para inputs existentes
document.querySelectorAll('.descripcion-input').forEach(input => {
setupAutocomplete(input);
});
// Configurar autocompletado para nuevas filas
$('#add-partida').on('click', function() { setTimeout(function() { $('.descripcion-input').last().each(function() { setupAutocomplete(this); }); }, 100); });
});
document.getElementById('add-partida').addEventListener('click', function() {
setTimeout(() => {
const newInput = document.querySelector('#tabla-partidas tbody tr:last-child .descripcion-input');
if (newInput) setupAutocomplete(newInput);
}, 100);
});
}
function setupAutocomplete(input) {
const $input = $(input);
const $globalSuggestions = $('#global-autocomplete-suggestions');
$input.off('input').on('input', function() {
const query = $(this).val().trim();
currentInput = $input;
clearTimeout(timeoutId);
if (currentRequest) currentRequest.abort();
if (query.length < 2) {
$globalSuggestions.hide().empty();
return;
}
timeoutId = setTimeout(() => {
currentRequest = $.ajax({
url: '/IMPORTADORES/solicitud_importacion/buscar_productos',
method: 'GET',
data: { q: query },
dataType: 'json',
success: function(productos) {
$globalSuggestions.empty();
if (productos && productos.length > 0) {
productos.forEach(function(producto) {
const $item = $(`
<div class="autocomplete-item px-3 py-2 cursor-pointer border-bottom hover-bg-light">
<strong style="color: #333;">${producto.sinonimo}</strong>
<div class="small text-muted mt-1">
<div>Fracción: ${producto.fraccion || 'Sin fracción'}</div>
<div>Desc: ${producto.descripcion?.substring(0, 50) || ''}${producto.descripcion?.length > 50 ? '...' : ''}</div>
</div>
</div>
`).data('producto', producto);
$item.on('mouseenter', function() {
$globalSuggestions.find('.autocomplete-item').removeClass('active');
$(this).addClass('active').css('background-color', '#f8f9fa');
}).on('mouseleave', function() {
$(this).removeClass('active').css('background-color', '');
});
$item.on('click', function() {
selectProduct($(this).data('producto'), $input.closest('tr'));
});
$globalSuggestions.append($item);
});
$globalSuggestions.show();
}
},
error: function(xhr, status, error) {
if (status !== 'abort') console.error("Error en búsqueda:", error);
$globalSuggestions.hide();
},
complete: function() {
currentRequest = null;
}
});
}, 300);
});
// Manejar eventos de teclado
$input.on('keydown', function(e) {
if (!$globalSuggestions.is(':visible')) return;
const $items = $globalSuggestions.find('.autocomplete-item');
const $active = $items.filter('.active');
switch(e.key) {
case 'ArrowDown':
e.preventDefault();
$items.removeClass('active').css('background-color', '');
const $next = $active.length ? $active.next() : $items.first();
$next.addClass('active').css('background-color', '#f8f9fa');
break;
case 'ArrowUp':
e.preventDefault();
$items.removeClass('active').css('background-color', '');
const $prev = $active.length ? $active.prev() : $items.last();
$prev.addClass('active').css('background-color', '#f8f9fa');
break;
case 'Enter':
if ($active.length) {
e.preventDefault();
selectProduct($active.data('producto'), $input.closest('tr'));
}
break;
case 'Escape':
$globalSuggestions.hide();
break;
}
});
// Ocultar sugerencias al hacer clic fuera
$(document).on('click', function(e) {
if (!currentInput ||
(!currentInput.is(e.target) &&
!$globalSuggestions.is(e.target) &&
!$globalSuggestions.has(e.target).length)) {
$globalSuggestions.hide();
}
});
}
function selectProduct(producto, $row) {
// Campos básicos
$row.find('input[name*="[descripcion]"]').val(producto.sinonimo);
// Tasa preferencial
if (producto.preferencia) {
const $select = $row.find('select[name*="[tasa_preferencial]"]');
if ($select[0] && $select[0]._choices) {
$select[0]._choices.setChoiceByValue(producto.preferencia);
} else {
$select.val(producto.preferencia).trigger('change');
}
}
// Unidad de medida
if (producto.umc_id) {
const $select = $row.find('select[name*="[unidad_comercial_id]"]');
setTimeout(() => {
if ($select[0] && $select[0]._choices) {
$select[0]._choices.setChoiceByValue(producto.umc_id.toString());
} else {
$select.val(producto.umc_id).trigger('change');
}
}, 50);
}
// Número de parte
if (producto.numero_parte) {
$row.find('input[name*="[oma_factura]"]').val(producto.numero_parte);
}
// Incrementar frecuencia
$.ajax({
url: '/IMPORTADORES/solicitud_importacion/incrementar_frecuencia',
method: 'POST',
data: { producto_id: producto.id }
});
// Ocultar sugerencias
$('#global-autocomplete-suggestions').hide();
// Enfocar el siguiente campo si existe
const $nextInput = $row.next('tr').find('.descripcion-input');
if ($nextInput.length) {
setTimeout(() => $nextInput.focus(), 100);
}
}
</script>
</body>

View File

@@ -141,11 +141,11 @@
function confirmChangeAgency(id) {
Swal.fire({
title: '¿Quieres cambiar de agencia?',
text: 'Dejaras de usar la agencia actual y cambiarás a la nueva.',
title: '¿Quieres usar esta agencia?',
text: 'Cambiarás la agencia activa a esta.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sí, cambiar agencia',
confirmButtonText: 'Sí, usar agencia',
cancelButtonText: 'Cancelar'
}).then((result) => {
if (result.isConfirmed) {