PUT budgets id: aviso WhatsApp al modificar presupuesto
This commit is contained in:
55
server.js
55
server.js
@@ -5551,18 +5551,63 @@ app.post("/budgets", authMiddleware, async (req, res) => {
|
||||
app.put("/budgets/:id", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { client_phone, client_name, client_address, items, subtotal, tax, total } = req.body;
|
||||
|
||||
|
||||
const q = await pool.query(
|
||||
"UPDATE budgets SET client_phone=$1, client_name=$2, client_address=$3, items=$4, subtotal=$5, tax=$6, total=$7 WHERE id=$8 AND owner_id=$9",
|
||||
[client_phone, client_name, client_address, JSON.stringify(items), subtotal, tax, total, req.params.id, req.user.accountId]
|
||||
);
|
||||
|
||||
|
||||
if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Presupuesto no encontrado" });
|
||||
|
||||
|
||||
// Respondemos rápido a la App y avisamos al cliente en segundo plano
|
||||
res.json({ ok: true });
|
||||
} catch(e) {
|
||||
|
||||
// AVISO AL CLIENTE DE PRESUPUESTO MODIFICADO (con reenvío del enlace del portal)
|
||||
(async () => {
|
||||
try {
|
||||
let rawPhone = client_phone || "";
|
||||
let cleanPhoneToMatch = extractValidPhone(rawPhone);
|
||||
|
||||
if (cleanPhoneToMatch.length >= 9) {
|
||||
const finalPhoneToSend = "34" + cleanPhoneToMatch;
|
||||
let token = null;
|
||||
|
||||
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 {
|
||||
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\nHemos *actualizado tu presupuesto*. El nuevo importe total es *${total}€*.\n\n📄 Puedes revisar los cambios y descargarlo de nuevo en PDF desde tu portal privado:\n🔗 ${linkMagico}`;
|
||||
|
||||
const MODO_PRUEBAS = false;
|
||||
const MI_TELEFONO = "34667248132";
|
||||
|
||||
if (MODO_PRUEBAS) {
|
||||
console.log(`🛡️ [MODO PRUEBAS] Enviando WA de presupuesto modificado a (${MI_TELEFONO}) en lugar de al cliente`);
|
||||
await sendWhatsAppAuto(MI_TELEFONO, `*(SIMULACIÓN PRESUPUESTO MODIFICADO PARA: ${finalPhoneToSend})*\n\n${msg}`, `cliente_${req.user.accountId}`, false);
|
||||
} else {
|
||||
console.log(`✅ Enviando WA de presupuesto modificado al cliente: ${finalPhoneToSend}`);
|
||||
await sendWhatsAppAuto(finalPhoneToSend, msg, `cliente_${req.user.accountId}`, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (errWA) {
|
||||
console.error("❌ Error enviando WA de presupuesto modificado:", errWA);
|
||||
}
|
||||
})();
|
||||
} catch(e) {
|
||||
console.error("Error al actualizar presupuesto:", e);
|
||||
res.status(500).json({ ok: false, error: "Error en el servidor al actualizar" });
|
||||
res.status(500).json({ ok: false, error: "Error en el servidor al actualizar" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user