${fullAddr}
@@ -622,34 +717,46 @@
setTimeout(() => { toast.classList.add('hidden'); }, 3500);
}
+ // LA FUNCIÓN CORREGIDA
function openDetail(id, startInEditMode = false) {
const s = localData.find(x => x.id === id);
if (!s) return;
- const raw = s.raw_data;
+ const raw = s.raw_data || {}; // Seguridad anti-crashes
document.getElementById('detId').value = s.id;
- document.getElementById('detRef').innerText = s.service_ref;
- document.getElementById('detCp').value = raw["Código Postal"] || "00000";
+ document.getElementById('detRef').innerText = s.service_ref || "";
+ if (document.getElementById('detCp')) document.getElementById('detCp').value = raw["Código Postal"] || "00000";
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "Particular";
- document.getElementById('detCompany').innerText = companyName;
-
- // Rellenar campos del editor
+ if (document.getElementById('detCompany')) document.getElementById('detCompany').innerText = companyName;
+
+ // RELLENADO DE CAMPOS PARA EL EDITOR Y VISTA (Inputs)
const clientName = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado Sin Nombre";
if(document.getElementById('editName')) document.getElementById('editName').value = clientName;
-
+
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
const singlePhone = matchPhone ? matchPhone[0] : "";
if(document.getElementById('editPhone')) document.getElementById('editPhone').value = singlePhone;
+ // Lógica del botón de llamada dinámico
+ const callBtn = document.getElementById('btnCallPhone');
+ if (callBtn) {
+ if (singlePhone) {
+ callBtn.href = `tel:+34${singlePhone}`;
+ callBtn.classList.remove('hidden');
+ } else {
+ callBtn.classList.add('hidden');
+ }
+ }
+
const fullAddr = `${raw["Dirección"] || ""} ${raw["Población"] || ""}`.trim();
if(document.getElementById('editAddr')) document.getElementById('editAddr').value = fullAddr;
const descContent = raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas.";
if(document.getElementById('editDesc')) document.getElementById('editDesc').value = descContent;
- const stateInfo = s._stateInfo;
+ const stateInfo = s._stateInfo || getServiceStateInfo(s);
if (s.automation_status === 'in_progress') {
document.getElementById('panelEnBolsa').classList.remove('hidden');
@@ -682,7 +789,6 @@
document.getElementById('detailModal').classList.remove('hidden');
- // Activar modo edición si se ha pulsado el lápiz
if (startInEditMode) {
enableEditing();
} else {
@@ -695,6 +801,7 @@
async function stopAutomation() {
const id = document.getElementById('detId').value;
if(!confirm("¿Deseas cancelar la búsqueda del robot para asignar este servicio manualmente?")) return;
+
try {
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
@@ -704,7 +811,9 @@
showToast("Bolsa detenida. Ya puedes asignar el servicio.");
closeDetailModal();
refreshPanel();
- } catch (e) { alert("Error al detener el automatismo."); }
+ } catch (e) {
+ alert("Error al detener el automatismo.");
+ }
}
async function saveAppointment() {
@@ -714,6 +823,7 @@
const statusMap = document.getElementById('detStatusMap').value;
const selectedSt = systemStatuses.find(st => String(st.id) === String(statusMap));
+
if (selectedSt && !selectedSt.is_final && !date && !selectedSt.name.toLowerCase().includes('pausa') && !selectedSt.name.toLowerCase().includes('asignar')) {
if(!confirm("No has asignado Fecha para este estado. ¿Deseas continuar?")) return;
}
@@ -729,6 +839,7 @@
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ date, time, status_operativo: statusMap })
});
+
closeDetailModal(); showToast("Estado actualizado"); refreshPanel();
} catch (e) { alert("Error"); }
finally { btn.innerHTML = originalContent; btn.disabled = false; }
@@ -740,6 +851,7 @@
const cp = document.getElementById('detCp').value;
if(!guild_id) return alert("Selecciona un gremio primero.");
+
const btn = document.getElementById('btnAuto');
btn.innerHTML = '';
@@ -787,8 +899,12 @@
})
});
- closeDetailModal(); showToast("Asignado y notificado correctamente"); refreshPanel();
- } catch (e) { alert("Error en la asignación manual"); }
+ closeDetailModal();
+ showToast("Asignado y notificado correctamente");
+ refreshPanel();
+ } catch (e) {
+ alert("Error en la asignación manual");
+ }
}
async function saveNewService(e) {
@@ -820,20 +936,23 @@
}
function closeDetailModal() { document.getElementById('detailModal').classList.add('hidden'); }
- function openCreateModal() {
+
+ async function openCreateModal() {
document.getElementById('createModal').classList.remove('hidden');
document.getElementById('isCompanyCheck').checked = false;
toggleCompanyFields(false);
- fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } })
- .then(r => r.json())
- .then(data => {
- const sel = document.getElementById('nCompanySelect');
- sel.innerHTML = '';
- if(data.companies) {
- data.companies.forEach(c => sel.innerHTML += ``);
- }
- }).catch(e=>{});
+ try {
+ const res = await fetch(`${API_URL}/companies`, {
+ headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
+ });
+ const data = await res.json();
+ const sel = document.getElementById('nCompanySelect');
+ sel.innerHTML = '';
+ data.companies.forEach(c => {
+ sel.innerHTML += ``;
+ });
+ } catch(e) {}
lucide.createIcons();
}
@@ -848,15 +967,19 @@
async function checkDuplicateRef(ref) {
if(!ref) return;
- const res = await fetch(`${API_URL}/services/check-ref?ref=${ref}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
+ const res = await fetch(`${API_URL}/services/check-ref?ref=${ref}`, {
+ headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
+ });
const data = await res.json();
const alertEl = document.getElementById('refAlert');
const inputEl = document.getElementById('nExpRef');
if(data.exists) {
- alertEl.classList.remove('hidden'); inputEl.classList.add('border-red-500', 'bg-red-50');
+ alertEl.classList.remove('hidden');
+ inputEl.classList.add('border-red-500', 'bg-red-50');
} else {
- alertEl.classList.add('hidden'); inputEl.classList.remove('border-red-500', 'bg-red-50');
+ alertEl.classList.add('hidden');
+ inputEl.classList.remove('border-red-500', 'bg-red-50');
}
}