Actualizar server.js

This commit is contained in:
2026-02-13 17:55:47 +00:00
parent 29c91985f9
commit 3d7e5d8e9c

View File

@@ -347,63 +347,93 @@ app.get("/providers/scraped", authMiddleware, async (req, res) => {
} catch (e) { res.status(500).json({ ok: false }); }
});
// 📥 IMPORTACIÓN INTELIGENTE (LA CLAVE)
// 📥 IMPORTACIÓN DEFINITIVA CON MAPEADOR DE VARIABLES
app.post("/providers/import/:id", authMiddleware, async (req, res) => {
const client = await pool.connect();
try {
const scrapedId = req.params.id;
await client.query('BEGIN');
// 1. Obtener datos RAW
const scrapedQ = await client.query("SELECT * FROM scraped_services WHERE id=$1 AND owner_id=$2", [scrapedId, req.user.accountId]);
// 1. Obtener los datos crudos del robot
const scrapedQ = await client.query(
"SELECT * FROM scraped_services WHERE id=$1 AND owner_id=$2",
[scrapedId, req.user.accountId]
);
if (scrapedQ.rowCount === 0) return res.status(404).json({ ok: false, error: "No encontrado" });
const raw = scrapedQ.rows[0].raw_data;
const provider = scrapedQ.rows[0].provider;
const ref = scrapedQ.rows[0].service_ref;
// 2. Buscar/Crear Cliente
const phoneClean = normalizePhone(raw.phone || "");
// 2. Obtener tus reglas de mapeo que acabas de guardar
const mappingQ = await client.query(
"SELECT original_key, target_key FROM variable_mappings WHERE owner_id=$1 AND provider=$2 AND is_ignored=FALSE",
[req.user.accountId, provider]
);
// 3. Crear el objeto final "limpio" basado en tus reglas
const cleanData = {};
mappingQ.rows.forEach(m => {
if (raw[m.original_key]) {
cleanData[m.target_key] = raw[m.original_key];
}
});
// 4. Buscar/Crear Cliente (Usando tus campos mapeados)
const phone = cleanData.phone || cleanData.phone2 || "";
const name = cleanData.clientName || "Cliente Importado";
const address = cleanData.address || "";
const phoneClean = normalizePhone(phone);
let clientId = null;
if (phoneClean) {
const cCheck = await client.query("SELECT id FROM clients WHERE phone=$1 AND owner_id=$2", [phoneClean, req.user.accountId]);
if (cCheck.rowCount > 0) clientId = cCheck.rows[0].id;
}
if (!clientId) {
const newC = await client.query("INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING id",
[req.user.accountId, raw.clientName || "Cliente Robot", phoneClean || "", JSON.stringify([raw.address || ""])]);
const newC = await client.query(
"INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING id",
[req.user.accountId, name, phoneClean, JSON.stringify([address])]
);
clientId = newC.rows[0].id;
}
// 3. Buscar/Crear Compañía
let companyId = null;
const companyName = provider.charAt(0).toUpperCase() + provider.slice(1);
const compCheck = await client.query("SELECT id FROM companies WHERE name ILIKE $1 AND owner_id=$2", [companyName, req.user.accountId]);
if (compCheck.rowCount > 0) companyId = compCheck.rows[0].id;
else {
const newComp = await client.query("INSERT INTO companies (owner_id, name) VALUES ($1, $2) RETURNING id", [req.user.accountId, companyName]);
companyId = newComp.rows[0].id;
}
// 4. Insertar Servicio (CON PROVIDER_DATA)
// 5. Insertar el Servicio Final
const statusQ = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]);
const insertSvc = await client.query(`
INSERT INTO services (
owner_id, client_id, company_id, status_id, company_ref, title, description, address, contact_phone, contact_name,
is_company, import_source, provider_data
owner_id, client_id, status_id, company_ref, title, description, address, contact_phone, contact_name,
is_company, import_source, provider_data, scheduled_date
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id
`, [
req.user.accountId, clientId, companyId, statusQ.rows[0]?.id, ref,
`${companyName} - ${ref}`, raw.description || "Sin descripción", raw.address, phoneClean, raw.clientName,
true, provider, JSON.stringify(raw)
req.user.accountId,
clientId,
statusQ.rows[0]?.id,
ref,
`${provider.toUpperCase()} - ${ref}`,
cleanData.descripcion || "Sin descripción",
address,
phoneClean,
name,
true,
provider,
JSON.stringify(cleanData), // Guardamos todo tu mapeo limpio aquí
cleanData.fecha_cita || 'NOW()'
]);
// 6. Marcar como importado
await client.query("UPDATE scraped_services SET status='imported' WHERE id=$1", [scrapedId]);
await client.query("INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, $3, 'Importado por Robot')", [insertSvc.rows[0].id, req.user.sub, statusQ.rows[0]?.id]);
await client.query('COMMIT');
res.json({ ok: true });
} catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); }
res.json({ ok: true, serviceId: insertSvc.rows[0].id });
} catch (e) {
await client.query('ROLLBACK');
console.error(e);
res.status(500).json({ ok: false, error: e.message });
} finally {
client.release();
}
});
// ==========================================