Actualizar server.js

This commit is contained in:
2026-03-29 10:31:33 +00:00
parent 743963c93a
commit eaa7323770

View File

@@ -3769,12 +3769,66 @@ app.get("/budgets", authMiddleware, async (req, res) => {
app.post("/budgets", authMiddleware, async (req, res) => { app.post("/budgets", authMiddleware, async (req, res) => {
try { try {
const { client_phone, client_name, client_address, items, subtotal, tax, total } = req.body; const { client_phone, client_name, client_address, items, subtotal, tax, total } = req.body;
// 1. Guardamos el presupuesto en la BBDD
await pool.query( await pool.query(
"INSERT INTO budgets (owner_id, client_phone, client_name, client_address, items, subtotal, tax, total) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", "INSERT INTO budgets (owner_id, client_phone, client_name, client_address, items, subtotal, tax, total) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
[req.user.accountId, client_phone, client_name, client_address, JSON.stringify(items), subtotal, tax, total] [req.user.accountId, client_phone, client_name, client_address, JSON.stringify(items), subtotal, tax, total]
); );
// Respondemos a la App rápido para que no se quede pensando
res.json({ ok: true }); res.json({ ok: true });
} catch(e) { res.status(500).json({ok: false}); }
// 2. TAREAS EN SEGUNDO PLANO (Envío del WhatsApp)
(async () => {
try {
let rawPhone = client_phone || "";
let cleanPhoneToMatch = extractValidPhone(rawPhone);
if (cleanPhoneToMatch.length >= 9) {
const finalPhoneToSend = "34" + cleanPhoneToMatch;
let token = null;
// Buscamos si el cliente ya tiene un token
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${cleanPhoneToMatch}%`, req.user.accountId]);
if (clientQ.rowCount > 0) {
token = clientQ.rows[0].portal_token;
} else {
// Si es un cliente totalmente nuevo, lo registramos y le creamos un token seguro
const newToken = crypto.randomBytes(32).toString('hex');
const insertC = await pool.query(
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING portal_token",
[req.user.accountId, client_name || "Cliente", finalPhoneToSend, JSON.stringify([client_address || ""]), newToken]
);
token = insertC.rows[0].portal_token;
}
if (token) {
const linkMagico = `https://portal.integrarepara.es/?token=${token}`;
const msg = `👋 Hola ${client_name || "Cliente"},\n\nAcabamos de generar un *nuevo presupuesto* para tu reparación por un total de *${total}€*.\n\n📄 Puedes revisarlo al detalle y descargarlo en PDF directamente desde tu portal privado:\n🔗 ${linkMagico}`;
// MODO PRUEBAS: Si quieres probarlo a tu número primero, cambia MODO_PRUEBAS a true
const MODO_PRUEBAS = false;
const MI_TELEFONO = "34667248132";
if (MODO_PRUEBAS) {
console.log(`🛡️ [MODO PRUEBAS] Enviando WA presupuesto a (${MI_TELEFONO}) en lugar de al cliente`);
await sendWhatsAppAuto(MI_TELEFONO, `*(SIMULACIÓN PRESUPUESTO PARA: ${finalPhoneToSend})*\n\n${msg}`, `cliente_${req.user.accountId}`, false);
} else {
console.log(`✅ Enviando WA de nuevo presupuesto al cliente: ${finalPhoneToSend}`);
await sendWhatsAppAuto(finalPhoneToSend, msg, `cliente_${req.user.accountId}`, false);
}
}
}
} catch(errWA) {
console.error("❌ Error enviando WA de presupuesto:", errWA);
}
})();
} catch(e) {
res.status(500).json({ok: false});
}
}); });
app.patch("/budgets/:id/status", authMiddleware, async (req, res) => { app.patch("/budgets/:id/status", authMiddleware, async (req, res) => {