Actualizar server.js

This commit is contained in:
2026-04-03 21:46:16 +00:00
parent e5b778b9db
commit 46e6e730e5

116
server.js
View File

@@ -5267,122 +5267,6 @@ app.post("/public/portal/:token/budget/:id/checkout", async (req, res) => {
}
});
// B) WEBHOOK DE STRIPE (El chivatazo invisible que avisa cuando el cliente YA ha pagado)
app.post("/webhook/stripe", async (req, res) => {
try {
const event = req.body;
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
const ownerId = session.metadata.owner_id;
const amountTotal = (session.amount_total / 100).toFixed(2);
const paymentType = session.metadata.type;
if (paymentType === 'protection_plan') {
const subId = session.metadata.subscription_id;
console.log(`💰 [STRIPE WEBHOOK] Pago de Seguro PREM-${subId} por ${amountTotal}`);
await pool.query("UPDATE protection_subscriptions SET payment_status = 'pagado', status = 'activo' WHERE id = $1 AND company_id = $2", [subId, ownerId]);
await pool.query("INSERT INTO protection_activity (company_id, type, description) VALUES ($1, 'cobro', $2)", [ownerId, `Pago de suscripción inicial confirmado (${amountTotal}€)`]);
} else {
const budgetId = session.metadata.budget_id;
console.log(`💰 [STRIPE WEBHOOK] ¡PAGO RECIBIDO! Presupuesto PRE-${budgetId} por ${amountTotal}`);
await pool.query("UPDATE budgets SET status = 'paid' WHERE id = $1 AND owner_id = $2", [budgetId, ownerId]);
const sq = await pool.query("SELECT id, raw_data FROM scraped_services WHERE service_ref = $1 AND owner_id = $2", [`PRE-${budgetId}`, ownerId]);
if (sq.rowCount > 0) {
const serviceId = sq.rows[0].id;
let rawData = sq.rows[0].raw_data || {};
rawData.is_paid = true;
await pool.query("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(rawData), serviceId]);
await pool.query(`
INSERT INTO service_financials (scraped_id, amount, payment_method, is_paid)
VALUES ($1, $2, 'Tarjeta (Stripe)', true)
ON CONFLICT (scraped_id) DO UPDATE SET is_paid = true, payment_method = 'Tarjeta (Stripe)'
`, [serviceId, amountTotal]);
await pool.query("INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
[serviceId, "Stripe API", "Pago Confirmado", `El cliente ha abonado ${amountTotal}€ por pasarela segura.`]
);
}
const ownerQ = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]);
if (ownerQ.rowCount > 0) {
const msgWa = `💰 *¡PAGO RECIBIDO (STRIPE)!*\n\nSe acaba de confirmar el pago con tarjeta del presupuesto *PRE-${budgetId}* por un importe de *${amountTotal}€*.\n\nEl sistema lo ha marcado como pagado automáticamente.`;
sendWhatsAppAuto(ownerQ.rows[0].phone, msgWa, `cliente_${ownerId}`, false).catch(console.error);
}
}
}
res.json({ received: true });
} catch (e) {
console.error("❌ Error grave procesando Webhook de Stripe:", e.message);
res.status(400).send(`Webhook Error: ${e.message}`);
}
});
try {
const event = req.body;
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
const ownerId = session.metadata.owner_id;
const amountTotal = (session.amount_total / 100).toFixed(2);
const paymentType = session.metadata.type; // <-- NUEVO: Diferencia qué están pagando
if (paymentType === 'protection_plan') {
// 🟢 1. PAGO DE PLAN DE PROTECCIÓN (SEGURO)
const subId = session.metadata.subscription_id;
console.log(`💰 [STRIPE WEBHOOK] Pago de Seguro PREM-${subId} por ${amountTotal}`);
// Marcamos la suscripción como pagada y la activamos
await pool.query("UPDATE protection_subscriptions SET payment_status = 'pagado', status = 'activo' WHERE id = $1 AND company_id = $2", [subId, ownerId]);
await pool.query("INSERT INTO protection_activity (company_id, type, description) VALUES ($1, 'cobro', $2)", [ownerId, `Pago de suscripción inicial confirmado (${amountTotal}€)`]);
} else {
// 🔵 2. PAGO DE PRESUPUESTO DE REPARACIÓN NORMAL
const budgetId = session.metadata.budget_id;
console.log(`💰 [STRIPE WEBHOOK] ¡PAGO RECIBIDO! Presupuesto PRE-${budgetId} por ${amountTotal}`);
await pool.query("UPDATE budgets SET status = 'paid' WHERE id = $1 AND owner_id = $2", [budgetId, ownerId]);
const sq = await pool.query("SELECT id, raw_data FROM scraped_services WHERE service_ref = $1 AND owner_id = $2", [`PRE-${budgetId}`, ownerId]);
if (sq.rowCount > 0) {
const serviceId = sq.rows[0].id;
let rawData = sq.rows[0].raw_data || {};
rawData.is_paid = true;
await pool.query("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(rawData), serviceId]);
await pool.query(`
INSERT INTO service_financials (scraped_id, amount, payment_method, is_paid)
VALUES ($1, $2, 'Tarjeta (Stripe)', true)
ON CONFLICT (scraped_id) DO UPDATE SET is_paid = true, payment_method = 'Tarjeta (Stripe)'
`, [serviceId, amountTotal]);
await pool.query("INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
[serviceId, "Stripe API", "Pago Confirmado", `El cliente ha abonado ${amountTotal}€ por pasarela segura.`]
);
}
// Avisar al jefe por WhatsApp
const ownerQ = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]);
if (ownerQ.rowCount > 0) {
const msgWa = `💰 *¡PAGO RECIBIDO (STRIPE)!*\n\nSe acaba de confirmar el pago con tarjeta del presupuesto *PRE-${budgetId}* por un importe de *${amountTotal}€*.\n\nEl sistema lo ha marcado como pagado automáticamente.`;
sendWhatsAppAuto(ownerQ.rows[0].phone, msgWa, `cliente_${ownerId}`, false).catch(console.error);
}
}
}
res.json({ received: true });
} catch (e) {
console.error("❌ Error grave procesando Webhook de Stripe:", e.message);
res.status(400).send(`Webhook Error: ${e.message}`);
}
});
// ==========================================
// 🛡️ MÓDULO SAAS: PLANES DE PROTECCIÓN