import 'dotenv/config'; import cors from 'cors'; import express from 'express'; import { pool } from './db.js'; import { notifySubmission } from './mailer.js'; const app = express(); const allowedOrigins = (process.env.ALLOWED_ORIGIN || '').split(',').map((s) => s.trim()).filter(Boolean); app.use(cors({ origin: allowedOrigins.length ? allowedOrigins : '*' })); app.use(express.json({ limit: '256kb' })); app.get('/api/health', async (_req, res) => { try { await pool.query('SELECT 1'); res.json({ ok: true }); } catch (err) { res.status(500).json({ ok: false, error: err.message }); } }); // Matches the payload shape already sent by src/lib/crm.js's webhook provider // (event: 'toolkit_registration' | 'roi_report_downloaded'), so no frontend // changes are needed beyond pointing VITE_CRM_WEBHOOK_URL at this endpoint. app.post('/api/webhook', async (req, res) => { const { event, lead, roi, utm = {}, leadSource, submittedAt, pageUri, referrer } = req.body || {}; if (!lead?.email) return res.status(400).json({ ok: false, error: 'lead.email is required' }); try { if (event === 'toolkit_registration') { await upsertLead({ lead, leadSource, utm, pageUri, referrer, submittedAt }); } else if (event === 'roi_report_downloaded') { await upsertLead({ lead, submittedAt }); await insertRoi({ lead, roi, submittedAt }); } else { return res.status(400).json({ ok: false, error: `Unknown event: ${event}` }); } notifySubmission({ event, lead, roi, submittedAt }).catch((err) => console.error('[mail] notify failed:', err)); res.json({ ok: true }); } catch (err) { console.error('[db] write failed:', err); res.status(500).json({ ok: false, error: 'Internal error' }); } }); async function upsertLead({ lead, leadSource, utm = {}, pageUri, referrer, submittedAt }) { await pool.query( `INSERT INTO leads (email, first_name, last_name, company, title, region, subscriber_band, lead_source, utm_source, utm_medium, utm_campaign, utm_term, utm_content, gclid, fbclid, li_fat_id, page_uri, referrer, submitted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE first_name = COALESCE(VALUES(first_name), first_name), last_name = COALESCE(VALUES(last_name), last_name), company = COALESCE(VALUES(company), company), title = COALESCE(VALUES(title), title), region = COALESCE(VALUES(region), region), subscriber_band = COALESCE(VALUES(subscriber_band), subscriber_band), lead_source = COALESCE(VALUES(lead_source), lead_source), utm_source = COALESCE(VALUES(utm_source), utm_source), utm_medium = COALESCE(VALUES(utm_medium), utm_medium), utm_campaign = COALESCE(VALUES(utm_campaign), utm_campaign), utm_term = COALESCE(VALUES(utm_term), utm_term), utm_content = COALESCE(VALUES(utm_content), utm_content), gclid = COALESCE(VALUES(gclid), gclid), fbclid = COALESCE(VALUES(fbclid), fbclid), li_fat_id = COALESCE(VALUES(li_fat_id), li_fat_id), page_uri = COALESCE(VALUES(page_uri), page_uri), referrer = COALESCE(VALUES(referrer), referrer), submitted_at = VALUES(submitted_at)`, [ lead.email, lead.first ?? null, lead.last ?? null, lead.company ?? null, lead.title ?? null, lead.region ?? null, lead.subs ?? null, leadSource ?? null, utm.utm_source ?? null, utm.utm_medium ?? null, utm.utm_campaign ?? null, utm.utm_term ?? null, utm.utm_content ?? null, utm.gclid ?? null, utm.fbclid ?? null, utm.li_fat_id ?? null, pageUri ?? null, referrer ?? null, new Date(submittedAt || Date.now()), ] ); } /** Empty strings aren't valid for numeric columns — MySQL rejects them outright. */ function numOrNull(v) { return v === '' || v === undefined || v === null ? null : v; } async function insertRoi({ lead, roi, submittedAt }) { const { inputs = {}, formatted = {}, results = {} } = roi || {}; await pool.query( `INSERT INTO roi_submissions (lead_email, total_low, total_high, bandwidth_savings, support_calls_savings, churn_savings, equipment_savings, ddos_savings, subscribers, arpu, churn_rate, pricing_region, downloaded_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`, [ lead.email, numOrNull(results?.total?.lo), numOrNull(results?.total?.hi), formatted.bw ?? null, formatted.calls ?? null, formatted.churn ?? null, formatted.equip ?? null, formatted.ddos ?? null, numOrNull(inputs.subs), numOrNull(inputs.arpu), numOrNull(inputs.churn), inputs.regionLabel ?? null, new Date(submittedAt || Date.now()), ] ); } const port = process.env.PORT || 8080; app.listen(port, () => console.log(`BlackDice ROI toolkit API listening on :${port}`));