From adeb5a7031c2b61dd61f5b049c3745fad97c6249 Mon Sep 17 00:00:00 2001 From: marsalva Date: Mon, 16 Feb 2026 14:52:37 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 128 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 74 insertions(+), 54 deletions(-) diff --git a/server.js b/server.js index 91eb495..18f66c5 100644 --- a/server.js +++ b/server.js @@ -559,23 +559,21 @@ app.post("/providers/automate/:id", authMiddleware, async (req, res) => { } }); +// AÑADIDO: CAPTURA COMPLETA DE DATOS (...EXTRA) app.post("/providers/import/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const scrapedId = req.params.id; + const { name, phone, address, cp, description, guild_id, assigned_to, internal_notes, client_notes, is_urgent, ...extra } = req.body; + await client.query('BEGIN'); 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 }); + const raw = scrapedQ.rows[0].raw_data; const provider = scrapedQ.rows[0].provider; const ref = scrapedQ.rows[0].service_ref; - 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]); - const cleanData = {}; - mappingQ.rows.forEach(m => { if (raw[m.original_key]) cleanData[m.target_key] = raw[m.original_key]; }); - const phone = cleanData.phone || cleanData.phone2 || ""; - const name = cleanData.clientName || "Cliente Importado"; - const address = cleanData.address || ""; - const cpExpediente = cleanData.cp || ""; + const phoneClean = normalizePhone(phone); let clientId = null; if (phoneClean) { @@ -586,44 +584,66 @@ app.post("/providers/import/:id", authMiddleware, async (req, res) => { 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; } - let autoAssignedTo = null; - if (cpExpediente) { - const workerQ = await client.query(`SELECT id FROM users WHERE owner_id = $1 AND role = 'operario' AND status = 'active' AND zones @> $2::jsonb LIMIT 1`, [req.user.accountId, JSON.stringify([{ cps: cpExpediente.toString() }])]); - if (workerQ.rowCount > 0) autoAssignedTo = workerQ.rows[0].id; - } + 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, status_id, company_ref, title, description, address, contact_phone, contact_name, is_company, import_source, provider_data, scheduled_date, assigned_to) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING id`, [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), cleanData.fecha_cita || 'NOW()', autoAssignedTo]); + const finalStatusId = statusQ.rows[0]?.id; + + // Fusión total: datos originales del scraper + todo lo recibido en el body + const fullProviderData = { ...raw, ...extra, "Nombre Cliente": name, "Teléfono": phone, "Dirección": address, "Código Postal": cp, "Descripción": description }; + + const insertSvc = await client.query(` + INSERT INTO services + (owner_id, client_id, status_id, company_ref, title, description, address, contact_phone, contact_name, is_company, import_source, provider_data, guild_id, assigned_to, internal_notes, client_notes, is_urgent) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) + RETURNING id`, + [req.user.accountId, clientId, finalStatusId, ref, `${provider.toUpperCase()} - ${ref}`, description, address, phoneClean, name, true, provider, JSON.stringify(fullProviderData), guild_id || null, assigned_to || null, internal_notes, client_notes, is_urgent] + ); + await client.query("UPDATE scraped_services SET status='imported' WHERE id=$1", [scrapedId]); await client.query('COMMIT'); - res.json({ ok: true, serviceId: insertSvc.rows[0].id, assigned: !!autoAssignedTo }); - } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } + res.json({ ok: true, serviceId: insertSvc.rows[0].id, assigned: !!assigned_to }); + } catch (e) { + await client.query('ROLLBACK'); + res.status(500).json({ ok: false }); + } finally { client.release(); } }); +// AÑADIDO: CAPTURA COMPLETA DE DATOS (...EXTRA) app.put('/providers/scraped/:id', authMiddleware, async (req, res) => { const { id } = req.params; - const { automation_status, name, phone, address, status } = req.body; + const { automation_status, status, name, phone, address, cp, description, guild_id, assigned_to, assigned_to_name, internal_notes, client_notes, is_urgent, ...extra } = req.body; try { if (automation_status) { - await pool.query( - `UPDATE scraped_services SET automation_status = $1 WHERE id = $2 AND owner_id = $3`, - [automation_status, id, req.user.accountId] - ); + await pool.query(`UPDATE scraped_services SET automation_status = $1 WHERE id = $2 AND owner_id = $3`, [automation_status, id, req.user.accountId]); return res.json({ ok: true }); } if (status === 'archived') { - await pool.query( - `UPDATE scraped_services SET status = 'archived', automation_status = 'manual' WHERE id = $2 AND owner_id = $3`, - [id, req.user.accountId] - ); + await pool.query(`UPDATE scraped_services SET status = 'archived', automation_status = 'manual' WHERE id = $2 AND owner_id = $3`, [id, req.user.accountId]); return res.json({ ok: true }); } const current = await pool.query('SELECT raw_data FROM scraped_services WHERE id = $1 AND owner_id = $2', [id, req.user.accountId]); if (current.rows.length === 0) return res.status(404).json({ error: 'No encontrado' }); - const updatedRawData = { ...current.rows[0].raw_data, "Nombre Cliente": name, "Teléfono": phone, "Dirección": address }; + // Fusión total: conservamos los extra para no perder información + const updatedRawData = { + ...current.rows[0].raw_data, + ...extra, + "Nombre Cliente": name || current.rows[0].raw_data["Nombre Cliente"], + "Teléfono": phone || current.rows[0].raw_data["Teléfono"], + "Dirección": address || current.rows[0].raw_data["Dirección"], + "Código Postal": cp || current.rows[0].raw_data["Código Postal"], + "Descripción": description || current.rows[0].raw_data["Descripción"], + "guild_id": guild_id, + "assigned_to": assigned_to, + "assigned_to_name": assigned_to_name, + "internal_notes": internal_notes, + "client_notes": client_notes, + "Urgente": is_urgent ? "Sí" : "No" + }; + await pool.query( `UPDATE scraped_services SET raw_data = $1, status = 'pending' WHERE id = $2 AND owner_id = $3`, [JSON.stringify(updatedRawData), id, req.user.accountId] @@ -795,37 +815,37 @@ app.delete("/services/:id", authMiddleware, async (req, res) => { try { await po // 🕒 EL RELOJ DEL SISTEMA (Ejecutar cada minuto) // ========================================== setInterval(async () => { - try { - const expiredPings = await pool.query(` - SELECT ap.id, ap.scraped_id, ap.user_id, s.owner_id, s.raw_data - FROM assignment_pings ap - JOIN scraped_services s ON ap.scraped_id = s.id - WHERE ap.status = 'pending' - AND EXTRACT(EPOCH FROM (ap.expires_at - CURRENT_TIMESTAMP)) <= 0 - AND s.automation_status = 'in_progress' - `); +    try { +       const expiredPings = await pool.query(` +            SELECT ap.id, ap.scraped_id, ap.user_id, s.owner_id, s.raw_data +            FROM assignment_pings ap +            JOIN scraped_services s ON ap.scraped_id = s.id +            WHERE ap.status = 'pending'  +            AND EXTRACT(EPOCH FROM (ap.expires_at - CURRENT_TIMESTAMP)) <= 0 +            AND s.automation_status = 'in_progress' +        `);  - for (const ping of expiredPings.rows) { - await pool.query("UPDATE assignment_pings SET status = 'expired' WHERE id = $1", [ping.id]); - const nextWorkerQ = await pool.query(` - SELECT u.id, u.phone, u.full_name - FROM users u - JOIN user_guilds ug ON u.id = ug.user_id - WHERE u.owner_id = $1 AND u.status = 'active' - AND u.id NOT IN (SELECT user_id FROM assignment_pings WHERE scraped_id = $2) - LIMIT 1 - `, [ping.owner_id, ping.scraped_id]); +        for (const ping of expiredPings.rows) { +            await pool.query("UPDATE assignment_pings SET status = 'expired' WHERE id = $1", [ping.id]); +            const nextWorkerQ = await pool.query(` +                SELECT u.id, u.phone, u.full_name  +                FROM users u +                JOIN user_guilds ug ON u.id = ug.user_id +                WHERE u.owner_id = $1 AND u.status = 'active' +                AND u.id NOT IN (SELECT user_id FROM assignment_pings WHERE scraped_id = $2) +                LIMIT 1 +            `, [ping.owner_id, ping.scraped_id]); - if (nextWorkerQ.rowCount > 0) { - const nextW = nextWorkerQ.rows[0]; - const newToken = crypto.randomBytes(16).toString('hex'); - await pool.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, CURRENT_TIMESTAMP + INTERVAL '5 minutes')`, [ping.scraped_id, nextW.id, newToken]); - await sendWhatsAppAuto(nextW.phone, `🛠️ *SERVICIO DISPONIBLE*\nEl anterior compañero no respondió. Es tu turno:\n🔗 https://integrarepara.es/aceptar.html?t=${newToken}`); - } else { - await pool.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [ping.scraped_id]); - } - } - } catch (e) { console.error("Reloj:", e); } +            if (nextWorkerQ.rowCount > 0) { +                const nextW = nextWorkerQ.rows[0]; +                const newToken = crypto.randomBytes(16).toString('hex'); +                await pool.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, CURRENT_TIMESTAMP + INTERVAL '5 minutes')`, [ping.scraped_id, nextW.id, newToken]); +                await sendWhatsAppAuto(nextW.phone, `🛠️ *SERVICIO DISPONIBLE*\nEl anterior compañero no respondió. Es tu turno:\n🔗 https://integrarepara.es/aceptar.html?t=${newToken}`); +            } else { +                await pool.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [ping.scraped_id]); +            } +        } +    } catch (e) { console.error("Reloj:", e); } }, 60000); const port = process.env.PORT || 3000;