+ ${badgeEstado}
+
${!isArchived ? `
-
+
` : ''}
@@ -366,17 +402,22 @@
document.getElementById('impScrapedId').value = id;
document.getElementById('impName').value = raw['Nombre Cliente'] || raw['CLIENTE'] || "S/N";
+
+ // Permite editar telefono
const rawPhone = raw['Teléfono'] || raw['TELEFONOS'] || raw['TELEFONO'] || "";
- document.getElementById('impPhone').value = rawPhone.match(/[6789]\d{8}/)?.[0] || "";
+ document.getElementById('impPhone').value = rawPhone.match(/[6789]\d{8}/)?.[0] || rawPhone;
+
const addr = raw['Dirección'] || raw['DOMICILIO'] || "";
const pop = raw['Población'] || raw['POBLACION-PROVINCIA'] || "";
document.getElementById('impAddress').value = `${addr} ${pop}`.trim();
document.getElementById('impCP').value = raw['Código Postal'] || raw['C.P.'] || "";
- document.getElementById('impDesc').value = raw['Descripción'] || "";
+ document.getElementById('impDesc').value = raw['Descripción'] || raw['DESCRIPCION'] || "";
+
const isUrgent = raw['Urgente'] === 'Sí' || raw['Urgente'] === 'true' || raw['URGENTE'] === 'SI';
document.getElementById('impUrgent').value = isUrgent.toString();
document.getElementById('impNotesInt').value = raw['internal_notes'] || "";
document.getElementById('impNotesExt').value = raw['client_notes'] || "";
+
const savedGuild = raw['guild_id'] || "";
document.getElementById('impGuild').value = savedGuild;
@@ -393,14 +434,11 @@
function closeModal() { document.getElementById('importModal').classList.add('hidden'); }
- async function saveDraftChanges(e) {
- const id = document.getElementById('impScrapedId').value;
- const btn = e.currentTarget;
- btn.disabled = true;
+ function getFormPayload() {
const opSelect = document.getElementById('impOperator');
const opName = opSelect.options[opSelect.selectedIndex]?.text.includes('--') ? null : opSelect.options[opSelect.selectedIndex]?.text;
-
- const payload = {
+
+ return {
name: document.getElementById('impName').value,
phone: document.getElementById('impPhone').value,
address: document.getElementById('impAddress').value,
@@ -413,82 +451,92 @@
internal_notes: document.getElementById('impNotesInt').value,
client_notes: document.getElementById('impNotesExt').value
};
+ }
+ async function saveFormToDB(id, payload) {
+ const res = await fetch(`${API_URL}/providers/scraped/${id}`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
+ body: JSON.stringify(payload)
+ });
+ return res.ok;
+ }
+
+ // CAMBIO 2: Guardar Borrador ahora cierra el modal.
+ async function saveDraftChanges(e) {
+ const id = document.getElementById('impScrapedId').value;
+ const btn = e.currentTarget;
+ btn.disabled = true;
try {
- const res = await fetch(`${API_URL}/providers/scraped/${id}`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
- body: JSON.stringify(payload)
- });
- if(res.ok) { showToast("✅ Borrador guardado"); loadInbox(); }
+ const ok = await saveFormToDB(id, getFormPayload());
+ if(ok) {
+ showToast("✅ Cambios guardados correctamente");
+ closeModal(); // Cierra el modal
+ loadInbox();
+ }
else { showToast("❌ Error al guardar", true); }
- } catch (e) { showToast("❌ Error de red", true); }
+ } catch (err) { showToast("❌ Error de red", true); }
finally { btn.disabled = false; }
}
+ // CAMBIO 3: Traspaso Manual bloquea si no hay operario asignado
async function handleFinalImport(event) {
event.preventDefault();
const btn = event.submitter;
if(btn.type === 'button') return;
+
+ const id = document.getElementById('impScrapedId').value;
+ const payload = getFormPayload();
+
+ // VALIDACIÓN: ¿Hay operario seleccionado?
+ if (!payload.assigned_to) {
+ showToast("⚠️ ERROR: Selecciona un operario para hacer el traspaso manual.", true);
+ return;
+ }
+
btn.disabled = true;
- const payload = {
- name: document.getElementById('impName').value,
- phone: document.getElementById('impPhone').value,
- address: document.getElementById('impAddress').value,
- cp: document.getElementById('impCP').value,
- description: document.getElementById('impDesc').value,
- company_ref: document.getElementById('displayRef').innerText.replace('REF: ', ''),
- guild_id: document.getElementById('impGuild').value,
- assigned_to: document.getElementById('impOperator').value || null,
- internal_notes: document.getElementById('impNotesInt').value,
- client_notes: document.getElementById('impNotesExt').value,
- is_urgent: document.getElementById('impUrgent').value === 'true'
- };
+ payload.company_ref = document.getElementById('displayRef').innerText.replace('REF: ', '');
+
try {
- const res = await fetch(`${API_URL}/providers/import/${document.getElementById('impScrapedId').value}`, {
+ await saveFormToDB(id, payload);
+
+ const res = await fetch(`${API_URL}/providers/import/${id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
- body: JSON.stringify(payload)
+ body: JSON.stringify(payload)
});
const result = await res.json();
- if(result.ok) { showToast("✅ Traspasado con éxito"); closeModal(); loadInbox(); }
+ if(result.ok) { showToast("✅ Expediente traspasado con éxito"); closeModal(); loadInbox(); }
else { showToast("❌ Error al importar", true); }
} catch (e) { showToast("❌ Error de red", true); }
finally { btn.disabled = false; }
}
- // NUEVA FUNCIÓN: MANDAR A LA COLA
async function sendToQueue() {
const id = document.getElementById('impScrapedId').value;
- const guild_id = document.getElementById('impGuild').value;
- const cp = document.getElementById('impCP').value;
+ const payload = getFormPayload();
- if (!guild_id) {
- showToast("⚠️ Selecciona un gremio para el automatismo", true);
+ if (!payload.guild_id) {
+ showToast("⚠️ Debes seleccionar un Gremio Especialista", true);
return;
}
try {
+ await saveFormToDB(id, payload);
+
showToast("🚀 Iniciando automatismo...");
const res = await fetch(`${API_URL}/providers/automate/${id}`, {
method: 'POST',
- headers: {
- "Content-Type": "application/json",
- "Authorization": `Bearer ${localStorage.getItem("token")}`
- },
- body: JSON.stringify({ guild_id, cp })
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
+ body: JSON.stringify({ guild_id: payload.guild_id, cp: payload.cp })
});
const data = await res.json();
if (data.ok) {
- showToast("✅ ¡En cola! Se ha enviado el primer WhatsApp.");
+ showToast("✅ ¡En cola! Se ha enviado a los operarios.");
closeModal();
loadInbox();
- } else {
- showToast("❌ " + data.error, true);
- }
- } catch (e) {
- showToast("❌ Error de conexión", true);
- }
+ } else { showToast("❌ " + data.error, true); }
+ } catch (e) { showToast("❌ Error de conexión", true); }
}
function showToast(msg, isError = false) {