From 20d1a358fc744bfbec4692462719b6001e8cec20 Mon Sep 17 00:00:00 2001 From: Alexeer Date: Tue, 17 Jun 2025 07:48:59 -0600 Subject: [PATCH] Locaciones --- views/locaciones/gestion_locaciones.php | 252 +++++++++++++++--------- 1 file changed, 158 insertions(+), 94 deletions(-) diff --git a/views/locaciones/gestion_locaciones.php b/views/locaciones/gestion_locaciones.php index 3ab8162..d023308 100644 --- a/views/locaciones/gestion_locaciones.php +++ b/views/locaciones/gestion_locaciones.php @@ -205,7 +205,7 @@ selectElement.innerHTML = ''; selectElement.disabled = true; - fetch(`/IMPORTADORES/agentes/estados?pais=${paisId}`) + fetch(`/IMPORTADORES/locaciones/estados?pais=${paisId}`) .then(response => response.json()) .then(estados => { selectElement.innerHTML = ''; @@ -237,52 +237,164 @@ } }); - // Función para abrir modal de edición + // Función editarItem mejorada para manejar caracteres especiales function editarItem(tipo, id, nombre, iso2 = '', iso3 = '', abreviatura = '', padreId = null) { - document.getElementById('editTipo').value = tipo; - document.getElementById('editId').value = id; - document.getElementById('tipoItem').textContent = tipo.charAt(0).toUpperCase() + tipo.slice(1); - - // Ocultar todos los campos - document.getElementById('camposPais').style.display = 'none'; - document.getElementById('camposEstado').style.display = 'none'; - document.getElementById('camposCiudad').style.display = 'none'; - - if (tipo === 'pais') { - document.getElementById('camposPais').style.display = 'block'; - document.getElementById('editNombrePais').value = nombre; - document.getElementById('editIso2').value = iso2; - document.getElementById('editIso3').value = iso3; + try { + // Sanitizar parámetros para evitar problemas con caracteres especiales + tipo = String(tipo).trim(); + id = parseInt(id); + nombre = String(nombre).trim(); + iso2 = String(iso2).trim(); + iso3 = String(iso3).trim(); + abreviatura = String(abreviatura).trim(); + padreId = padreId ? parseInt(padreId) : null; + + // Validaciones básicas + if (!tipo || !id || !nombre) { + throw new Error('Parámetros requeridos faltantes'); + } + + document.getElementById('editTipo').value = tipo; + document.getElementById('editId').value = id; + document.getElementById('tipoItem').textContent = tipo.charAt(0).toUpperCase() + tipo.slice(1); + + // Ocultar todos los campos + document.getElementById('camposPais').style.display = 'none'; + document.getElementById('camposEstado').style.display = 'none'; + document.getElementById('camposCiudad').style.display = 'none'; + + if (tipo === 'pais') { + document.getElementById('camposPais').style.display = 'block'; + document.getElementById('editNombrePais').value = nombre; + document.getElementById('editIso2').value = iso2; + document.getElementById('editIso3').value = iso3; - } else if (tipo === 'estado') { - document.getElementById('camposEstado').style.display = 'block'; - document.getElementById('editNombreEstado').value = nombre; - document.getElementById('editAbreviatura').value = abreviatura; - document.getElementById('editPaisEstado').value = padreId; + } else if (tipo === 'estado') { + document.getElementById('camposEstado').style.display = 'block'; + document.getElementById('editNombreEstado').value = nombre; + document.getElementById('editAbreviatura').value = abreviatura; + document.getElementById('editPaisEstado').value = padreId || ''; - } else if (tipo === 'ciudad') { - document.getElementById('camposCiudad').style.display = 'block'; - document.getElementById('editNombreCiudad').value = nombre; + } else if (tipo === 'ciudad') { + document.getElementById('camposCiudad').style.display = 'block'; + document.getElementById('editNombreCiudad').value = nombre; - // Necesitamos obtener el país del estado para cargar los estados - if (padreId) { - fetch(`/IMPORTADORES/agentes/obtenerPaisPorEstado?estado=${padreId}`) + // Necesitamos obtener el país del estado para cargar los estados + if (padreId) { + fetch(`/IMPORTADORES/locaciones/obtenerPaisPorEstado?estado=${padreId}`) + .then(response => { + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + return response.text(); // Primero como texto para verificar + }) + .then(text => { + try { + return JSON.parse(text); + } catch (jsonError) { + console.error('Response no es JSON válido:', text); + throw new Error('Respuesta del servidor no es JSON válido'); + } + }) + .then(data => { + if (data.success) { + document.getElementById('editPaisCiudad').value = data.pais_id; + cargarEstados(data.pais_id, document.getElementById('editEstadoCiudad'), padreId); + } else { + console.error('Error al obtener país:', data.message); + Swal.fire({ + icon: 'error', + title: 'Error', + text: data.message || 'No se pudo cargar la información del país' + }); + } + }) + .catch(error => { + console.error('Error:', error); + Swal.fire({ + icon: 'error', + title: 'Error', + text: 'Error al cargar la información: ' + error.message + }); + }); + } + } + + new bootstrap.Modal(document.getElementById('editarModal')).show(); + + } catch (error) { + console.error('Error en editarItem:', error); + Swal.fire({ + icon: 'error', + title: 'Error', + text: 'Error al abrir el formulario de edición: ' + error.message + }); + } + } + + // Función eliminarItem mejorada + function eliminarItem(tipo, id, nombre) { + try { + // Sanitizar parámetros + tipo = String(tipo).trim(); + id = parseInt(id); + nombre = String(nombre).trim(); + + if (!tipo || !id || !nombre) { + throw new Error('Parámetros requeridos faltantes'); + } + + Swal.fire({ + title: '¿Estás seguro?', + text: `¿Deseas eliminar el ${tipo} "${nombre}"?`, + icon: 'warning', + showCancelButton: true, + confirmButtonColor: '#d33', + cancelButtonColor: '#3085d6', + confirmButtonText: 'Sí, eliminar', + cancelButtonText: 'Cancelar' + }).then((result) => { + if (result.isConfirmed) { + fetch('/IMPORTADORES/locaciones/eliminar', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + tipo: tipo, + id: id + }) + }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } - return response.json(); + return response.text(); // Primero como texto + }) + .then(text => { + try { + return JSON.parse(text); + } catch (jsonError) { + console.error('Response no es JSON válido:', text); + throw new Error('Respuesta del servidor no es JSON válido'); + } }) .then(data => { if (data.success) { - document.getElementById('editPaisCiudad').value = data.pais_id; - cargarEstados(data.pais_id, document.getElementById('editEstadoCiudad'), padreId); + Swal.fire({ + icon: 'success', + title: '¡Eliminado!', + text: data.message, + timer: 2000, + showConfirmButton: false + }).then(() => { + location.reload(); + }); } else { - console.error('Error al obtener país:', data.message); Swal.fire({ icon: 'error', title: 'Error', - text: 'No se pudo cargar la información del país' + data.message + text: data.message || 'Error desconocido al eliminar' }); } }) @@ -291,68 +403,20 @@ Swal.fire({ icon: 'error', title: 'Error', - text: 'Error al cargar la información' + text: 'Ocurrió un error al eliminar: ' + error.message }); }); - } + } + }); + + } catch (error) { + console.error('Error en eliminarItem:', error); + Swal.fire({ + icon: 'error', + title: 'Error', + text: 'Error al procesar eliminación: ' + error.message + }); } - - new bootstrap.Modal(document.getElementById('editarModal')).show(); - } - - // Función para eliminar item - function eliminarItem(tipo, id, nombre) { - Swal.fire({ - title: '¿Estás seguro?', - text: `¿Deseas eliminar el ${tipo} "${nombre}"?`, - icon: 'warning', - showCancelButton: true, - confirmButtonColor: '#d33', - cancelButtonColor: '#3085d6', - confirmButtonText: 'Sí, eliminar', - cancelButtonText: 'Cancelar' - }).then((result) => { - if (result.isConfirmed) { - fetch('/IMPORTADORES/agentes/eliminar', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - tipo: tipo, - id: id - }) - }) - .then(response => response.json()) - .then(data => { - if (data.success) { - Swal.fire({ - icon: 'success', - title: '¡Eliminado!', - text: data.message, - timer: 2000, - showConfirmButton: false - }).then(() => { - location.reload(); - }); - } else { - Swal.fire({ - icon: 'error', - title: 'Error', - text: data.message - }); - } - }) - .catch(error => { - console.error('Error:', error); - Swal.fire({ - icon: 'error', - title: 'Error', - text: 'Ocurrió un error al eliminar' - }); - }); - } - }); } // REEMPLAZA tu función de submit del formulario con esta versión corregida @@ -390,7 +454,7 @@ }); return; } - endpoint = '/IMPORTADORES/agentes/actualizarPais'; + endpoint = '/IMPORTADORES/locaciones/actualizarPais'; formData.append('nombre', nombre); formData.append('iso2', document.getElementById('editIso2').value.trim()); formData.append('iso3', document.getElementById('editIso3').value.trim()); @@ -407,7 +471,7 @@ }); return; } - endpoint = '/IMPORTADORES/agentes/actualizarEstado'; + endpoint = '/IMPORTADORES/locaciones/actualizarEstado'; formData.append('nombre', nombre); formData.append('abreviatura', document.getElementById('editAbreviatura').value.trim()); formData.append('pais_id', paisId); @@ -424,7 +488,7 @@ }); return; } - endpoint = '/IMPORTADORES/agentes/actualizarCiudad'; + endpoint = '/IMPORTADORES/locaciones/actualizarCiudad'; formData.append('nombre', nombre); formData.append('estado_id', estadoId); }