Actualizar server.js
This commit is contained in:
82
server.js
82
server.js
@@ -347,63 +347,93 @@ app.get("/providers/scraped", authMiddleware, async (req, res) => {
|
|||||||
} catch (e) { res.status(500).json({ ok: false }); }
|
} 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) => {
|
app.post("/providers/import/:id", authMiddleware, async (req, res) => {
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
const scrapedId = req.params.id;
|
const scrapedId = req.params.id;
|
||||||
await client.query('BEGIN');
|
await client.query('BEGIN');
|
||||||
|
|
||||||
// 1. Obtener datos RAW
|
// 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]);
|
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" });
|
if (scrapedQ.rowCount === 0) return res.status(404).json({ ok: false, error: "No encontrado" });
|
||||||
|
|
||||||
const raw = scrapedQ.rows[0].raw_data;
|
const raw = scrapedQ.rows[0].raw_data;
|
||||||
const provider = scrapedQ.rows[0].provider;
|
const provider = scrapedQ.rows[0].provider;
|
||||||
const ref = scrapedQ.rows[0].service_ref;
|
const ref = scrapedQ.rows[0].service_ref;
|
||||||
|
|
||||||
// 2. Buscar/Crear Cliente
|
// 2. Obtener tus reglas de mapeo que acabas de guardar
|
||||||
const phoneClean = normalizePhone(raw.phone || "");
|
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;
|
let clientId = null;
|
||||||
if (phoneClean) {
|
if (phoneClean) {
|
||||||
const cCheck = await client.query("SELECT id FROM clients WHERE phone=$1 AND owner_id=$2", [phoneClean, req.user.accountId]);
|
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 (cCheck.rowCount > 0) clientId = cCheck.rows[0].id;
|
||||||
}
|
}
|
||||||
if (!clientId) {
|
if (!clientId) {
|
||||||
const newC = await client.query("INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING id",
|
const newC = await client.query(
|
||||||
[req.user.accountId, raw.clientName || "Cliente Robot", phoneClean || "", JSON.stringify([raw.address || ""])]);
|
"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;
|
clientId = newC.rows[0].id;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Buscar/Crear Compañía
|
// 5. Insertar el Servicio Final
|
||||||
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)
|
|
||||||
const statusQ = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]);
|
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(`
|
const insertSvc = await client.query(`
|
||||||
INSERT INTO services (
|
INSERT INTO services (
|
||||||
owner_id, client_id, company_id, status_id, company_ref, title, description, address, contact_phone, contact_name,
|
owner_id, client_id, status_id, company_ref, title, description, address, contact_phone, contact_name,
|
||||||
is_company, import_source, provider_data
|
is_company, import_source, provider_data, scheduled_date
|
||||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id
|
) 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,
|
req.user.accountId,
|
||||||
`${companyName} - ${ref}`, raw.description || "Sin descripción", raw.address, phoneClean, raw.clientName,
|
clientId,
|
||||||
true, provider, JSON.stringify(raw)
|
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("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');
|
await client.query('COMMIT');
|
||||||
res.json({ ok: true });
|
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(); }
|
} catch (e) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
console.error(e);
|
||||||
|
res.status(500).json({ ok: false, error: e.message });
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|||||||
Reference in New Issue
Block a user