Actualizar server.js

This commit is contained in:
2026-03-04 07:55:04 +00:00
parent 06d67be7ca
commit 4ce5fa7ba2

View File

@@ -1553,18 +1553,21 @@ app.post('/clients/ensure', authMiddleware, async (req, res) => {
const { phone, name, address } = req.body; const { phone, name, address } = req.body;
if (!phone) return res.status(400).json({ ok: false, error: "Teléfono obligatorio" }); if (!phone) return res.status(400).json({ ok: false, error: "Teléfono obligatorio" });
// Normalizar teléfono (quitar espacios, +34, etc) para buscar bien
const cleanPhone = phone.replace('+34', '').replace(/\s+/g, '').trim(); const cleanPhone = phone.replace('+34', '').replace(/\s+/g, '').trim();
const ownerId = req.user.accountId; const ownerId = req.user.accountId;
const q = await pool.query("SELECT * FROM clients WHERE phone LIKE $1 AND owner_id = $2 LIMIT 1", [`%${cleanPhone}%`, ownerId]); const q = await pool.query("SELECT * FROM clients WHERE phone LIKE $1 AND owner_id = $2 LIMIT 1", [`%${cleanPhone}%`, ownerId]);
if (q.rowCount > 0) { if (q.rowCount > 0) {
// Cliente existe, devolvemos su token let client = q.rows[0];
res.json({ ok: true, client: q.rows[0] }); // PARCHE: Si el cliente existe pero no tiene token (porque es antiguo), se lo creamos
if (!client.portal_token) {
client.portal_token = crypto.randomBytes(6).toString('hex');
await pool.query("UPDATE clients SET portal_token = $1 WHERE id = $2", [client.portal_token, client.id]);
}
res.json({ ok: true, client });
} else { } else {
// Cliente nuevo, generamos token y lo creamos const newToken = crypto.randomBytes(6).toString('hex');
const newToken = crypto.randomBytes(6).toString('hex'); // Token seguro y corto
const insert = await pool.query( const insert = await pool.query(
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING portal_token", "INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING portal_token",
[ownerId, name || "Cliente", phone, JSON.stringify([address || ""]), newToken] [ownerId, name || "Cliente", phone, JSON.stringify([address || ""]), newToken]
@@ -1572,7 +1575,6 @@ app.post('/clients/ensure', authMiddleware, async (req, res) => {
res.json({ ok: true, client: { portal_token: insert.rows[0].portal_token } }); res.json({ ok: true, client: { portal_token: insert.rows[0].portal_token } });
} }
} catch (e) { } catch (e) {
console.error("Error ensure client:", e);
res.status(500).json({ ok: false, error: "Error interno del servidor" }); res.status(500).json({ ok: false, error: "Error interno del servidor" });
} }
}); });