{
  "name": "Lead Pipeline: Ads + CRM to Real-time Dashboard",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "GET",
        "path": "lead-pipeline-metrics",
        "responseMode": "responseNode",
        "options": {
          "allowedOrigins": "*"
        }
      },
      "id": "8510acfc-52a1-549e-996a-689d5e1b63f0",
      "name": "Dashboard Poll (Webhook)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        320
      ],
      "webhookId": "2a86128b-d7f4-55fd-8b28-5dac965c5e36"
    },
    {
      "parameters": {
        "jsCode": "// Generated from data-automation/pipeline.js by build_workflow.py. Edit pipeline.js, then rebuild.\n\nconst PIPELINE_VERSION = '1.0.0';\n\n// Campaign config: in production this is a lookup table (Google Sheet / Postgres)\n// that maps UTM values to ad-platform campaigns.\nconst CAMPAIGNS = [\n  { id: 'c1', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Dental Implants | Lead Form',    utm: 'dental_implants_lf',       imp: [500, 1200],  ctr: [0.012, 0.022], cvr: [0.05, 0.08], cpc: [2.0, 3.2],  book: 0.30, value: [400, 1200] },\n  { id: 'c2', client: 'Coastline Dental',   channel: 'Google Ads', name: 'Dental Implants | Search',       utm: 'dental_implants_search',   imp: [120, 300],   ctr: [0.05, 0.09],   cvr: [0.08, 0.12], cpc: [6, 11],     book: 0.40, value: [400, 1200] },\n  { id: 'c3', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Invisalign | Reels',             utm: 'invisalign_reels',         imp: [800, 1700],  ctr: [0.008, 0.016], cvr: [0.03, 0.06], cpc: [1.5, 2.6],  book: 0.20, value: [600, 1400] },\n  { id: 'c4', client: 'Gleam Auto Care',    channel: 'Meta Ads',   name: 'Ceramic Coating | Promo',        utm: 'ceramic_coating_promo',    imp: [500, 1200],  ctr: [0.010, 0.020], cvr: [0.04, 0.07], cpc: [1.2, 2.2],  book: 0.35, value: [300, 700] },\n  { id: 'c5', client: 'Gleam Auto Care',    channel: 'Google Ads', name: 'Car Detailing Near Me | Search', utm: 'detailing_search',         imp: [100, 250],   ctr: [0.06, 0.10],   cvr: [0.08, 0.14], cpc: [2.0, 3.5],  book: 0.45, value: [150, 320] },\n  { id: 'c6', client: 'Rapid Flow Plumbing', channel: 'Google Ads', name: 'Emergency Plumber | Search',    utm: 'emergency_plumber_search', imp: [90, 220],    ctr: [0.07, 0.12],   cvr: [0.10, 0.16], cpc: [9, 16],     book: 0.50, value: [300, 800] },\n  { id: 'c7', client: 'Rapid Flow Plumbing', channel: 'Meta Ads',   name: 'Water Heater | Lead Form',      utm: 'water_heater_lf',          imp: [400, 900],   ctr: [0.009, 0.018], cvr: [0.03, 0.06], cpc: [1.8, 3.0],  book: 0.25, value: [800, 1800] },\n];\n\nconst HOUR_MS = 3600000;\nconst WINDOW_HOURS = 24;\n// Relative activity by local hour of day (morning and evening peaks).\nconst HOUR_WEIGHT = [0.15, 0.1, 0.08, 0.08, 0.1, 0.2, 0.4, 0.65, 0.85, 1, 1, 0.95, 0.85, 0.8, 0.8, 0.85, 0.9, 0.95, 1, 1, 0.9, 0.7, 0.45, 0.25];\nconst FIRST = ['James', 'Maria', 'Robert', 'Linda', 'Michael', 'Patricia', 'David', 'Jennifer', 'Daniel', 'Elizabeth', 'Carlos', 'Aisha', 'Kevin', 'Grace', 'Brian', 'Sofia', 'Jason', 'Nina', 'Anthony', 'Chloe'];\nconst LAST = ['Smith', 'Garcia', 'Johnson', 'Nguyen', 'Brown', 'Martinez', 'Lee', 'Walker', 'Reyes', 'Hall', 'Young', 'Lopez', 'King', 'Wright', 'Scott', 'Torres', 'Hill', 'Adams', 'Baker', 'Rivera'];\nconst DOMAINS = ['example.com', 'example.net', 'example.org', 'mail.example.com'];\n\nfunction hashStr(s) {\n  let h = 2166136261;\n  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }\n  return h >>> 0;\n}\nfunction rng(seed) {\n  let a = typeof seed === 'string' ? hashStr(seed) : seed >>> 0;\n  return function () {\n    a = (a + 0x6D2B79F5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction between(r, range) { return range[0] + r() * (range[1] - range[0]); }\nfunction pick(r, arr) { return arr[Math.floor(r() * arr.length)]; }\nfunction pad2(n) { return String(n).padStart(2, '0'); }\nfunction round2(n) { return Math.round(n * 100) / 100; }\nfunction isoDate(d) { return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()); }\n\n// The simulated \"world\": what really happened across both ad platforms and the CRM\n// in the last 24 hours. Deterministic for a given hour, so every poll sees the same\n// history and only the current hour grows.\nfunction simulateWorld(nowMs) {\n  const now = Math.floor(nowMs / 5000) * 5000;\n  const currentHour = Math.floor(now / HOUR_MS);\n  const hours = [];\n  const leads = [];\n  for (let hi = currentHour - WINDOW_HOURS + 1; hi <= currentHour; hi++) {\n    const start = hi * HOUR_MS;\n    const frac = hi === currentHour ? (now - start) / HOUR_MS : 1;\n    const w = HOUR_WEIGHT[new Date(start).getHours()];\n    const rows = [];\n    for (const c of CAMPAIGNS) {\n      const r = rng('h' + hi + c.id);\n      const impressionsFull = Math.round(between(r, c.imp) * w);\n      const clicksFull = Math.round(impressionsFull * between(r, c.ctr));\n      const spendFull = clicksFull * between(r, c.cpc);\n      const leadCount = Math.max(0, Math.round(clicksFull * between(r, c.cvr) + (r() - 0.5)));\n      let realised = 0;\n      for (let k = 0; k < leadCount; k++) {\n        const lr = rng('l' + hi + c.id + k);\n        const ts = start + Math.floor(lr() * HOUR_MS);\n        if (ts > now) continue;\n        realised++;\n        leads.push(makeLead(lr, c, ts, hi + c.id + k));\n      }\n      rows.push({\n        campaign: c,\n        impressions: Math.round(impressionsFull * frac),\n        clicks: Math.round(clicksFull * frac),\n        spend: round2(spendFull * frac),\n        leads: realised,\n        overReport: r() < 0.1 ? 1 : 0,\n      });\n    }\n    // Organic website-form leads (no ad spend).\n    const or = rng('o' + hi);\n    const organicCount = Math.round(or() * 1.4 * w);\n    for (let k = 0; k < organicCount; k++) {\n      const lr = rng('ol' + hi + k);\n      const ts = start + Math.floor(lr() * HOUR_MS);\n      if (ts <= now) leads.push(makeLead(lr, null, ts, 'o' + hi + k));\n    }\n    hours.push({ start, rows });\n  }\n  return { now, hours, leads };\n}\n\nfunction makeLead(r, c, ts, key) {\n  const first = pick(r, FIRST);\n  const last = pick(r, LAST);\n  const booked = r() < (c ? c.book : 0.3);\n  const valueRange = c ? c.value : [200, 900];\n  return {\n    id: 'ct_' + hashStr('lead' + key).toString(36),\n    key,\n    campaign: c,\n    ts,\n    first,\n    last,\n    email: (first + '.' + last + Math.floor(r() * 90 + 10)).toLowerCase() + '@' + pick(r, DOMAINS),\n    phone: '555' + String(Math.floor(r() * 9000000 + 1000000)),\n    booked,\n    value: booked ? Math.round(between(r, valueRange)) : 0,\n  };\n}\n\n// Shape mirrors the Meta Marketing API insights endpoint:\n// GET /act_{ad_account_id}/insights?level=campaign&breakdowns=hourly_stats_aggregated_by_advertiser_time_zone\nfunction extractMetaAds(nowMs) {\n  const t0 = Date.now();\n  const world = simulateWorld(nowMs);\n  const rows = [];\n  for (const h of world.hours) {\n    const d = new Date(h.start);\n    for (const x of h.rows) {\n      if (x.campaign.channel !== 'Meta Ads') continue;\n      const r = rng('mx' + h.start + x.campaign.id);\n      const name = r() < 0.1 ? x.campaign.name.toUpperCase() + '  ' : r() < 0.15 ? '  ' + x.campaign.name : x.campaign.name;\n      const row = {\n        _source: 'meta_ads',\n        campaign_name: name,\n        date_start: isoDate(d),\n        hourly_stats_aggregated_by_advertiser_time_zone: pad2(d.getHours()) + ':00:00 - ' + pad2(d.getHours()) + ':59:59',\n        impressions: String(x.impressions),\n        clicks: String(x.clicks),\n        spend: r() < 0.03 ? null : x.spend.toFixed(2),\n        actions: [{ action_type: 'lead', value: String(x.leads + x.overReport) }],\n      };\n      rows.push(row);\n      // API pagination overlap occasionally returns the same row twice.\n      if (r() < 0.04) rows.push(Object.assign({}, row));\n    }\n  }\n  return { rows, ms: Date.now() - t0 };\n}\n\nconst res = extractMetaAds(Date.now());\nreturn res.rows.map(r => ({ json: Object.assign(r, { _extractMs: res.ms }) }));\n"
      },
      "id": "e188fdf5-a3f0-599e-8319-2bdd5f25719c",
      "name": "Extract: Meta Ads Insights",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        280,
        120
      ],
      "notes": "Sample data shaped like GET /act_{id}/insights",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// Generated from data-automation/pipeline.js by build_workflow.py. Edit pipeline.js, then rebuild.\n\nconst PIPELINE_VERSION = '1.0.0';\n\n// Campaign config: in production this is a lookup table (Google Sheet / Postgres)\n// that maps UTM values to ad-platform campaigns.\nconst CAMPAIGNS = [\n  { id: 'c1', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Dental Implants | Lead Form',    utm: 'dental_implants_lf',       imp: [500, 1200],  ctr: [0.012, 0.022], cvr: [0.05, 0.08], cpc: [2.0, 3.2],  book: 0.30, value: [400, 1200] },\n  { id: 'c2', client: 'Coastline Dental',   channel: 'Google Ads', name: 'Dental Implants | Search',       utm: 'dental_implants_search',   imp: [120, 300],   ctr: [0.05, 0.09],   cvr: [0.08, 0.12], cpc: [6, 11],     book: 0.40, value: [400, 1200] },\n  { id: 'c3', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Invisalign | Reels',             utm: 'invisalign_reels',         imp: [800, 1700],  ctr: [0.008, 0.016], cvr: [0.03, 0.06], cpc: [1.5, 2.6],  book: 0.20, value: [600, 1400] },\n  { id: 'c4', client: 'Gleam Auto Care',    channel: 'Meta Ads',   name: 'Ceramic Coating | Promo',        utm: 'ceramic_coating_promo',    imp: [500, 1200],  ctr: [0.010, 0.020], cvr: [0.04, 0.07], cpc: [1.2, 2.2],  book: 0.35, value: [300, 700] },\n  { id: 'c5', client: 'Gleam Auto Care',    channel: 'Google Ads', name: 'Car Detailing Near Me | Search', utm: 'detailing_search',         imp: [100, 250],   ctr: [0.06, 0.10],   cvr: [0.08, 0.14], cpc: [2.0, 3.5],  book: 0.45, value: [150, 320] },\n  { id: 'c6', client: 'Rapid Flow Plumbing', channel: 'Google Ads', name: 'Emergency Plumber | Search',    utm: 'emergency_plumber_search', imp: [90, 220],    ctr: [0.07, 0.12],   cvr: [0.10, 0.16], cpc: [9, 16],     book: 0.50, value: [300, 800] },\n  { id: 'c7', client: 'Rapid Flow Plumbing', channel: 'Meta Ads',   name: 'Water Heater | Lead Form',      utm: 'water_heater_lf',          imp: [400, 900],   ctr: [0.009, 0.018], cvr: [0.03, 0.06], cpc: [1.8, 3.0],  book: 0.25, value: [800, 1800] },\n];\n\nconst HOUR_MS = 3600000;\nconst WINDOW_HOURS = 24;\n// Relative activity by local hour of day (morning and evening peaks).\nconst HOUR_WEIGHT = [0.15, 0.1, 0.08, 0.08, 0.1, 0.2, 0.4, 0.65, 0.85, 1, 1, 0.95, 0.85, 0.8, 0.8, 0.85, 0.9, 0.95, 1, 1, 0.9, 0.7, 0.45, 0.25];\nconst FIRST = ['James', 'Maria', 'Robert', 'Linda', 'Michael', 'Patricia', 'David', 'Jennifer', 'Daniel', 'Elizabeth', 'Carlos', 'Aisha', 'Kevin', 'Grace', 'Brian', 'Sofia', 'Jason', 'Nina', 'Anthony', 'Chloe'];\nconst LAST = ['Smith', 'Garcia', 'Johnson', 'Nguyen', 'Brown', 'Martinez', 'Lee', 'Walker', 'Reyes', 'Hall', 'Young', 'Lopez', 'King', 'Wright', 'Scott', 'Torres', 'Hill', 'Adams', 'Baker', 'Rivera'];\nconst DOMAINS = ['example.com', 'example.net', 'example.org', 'mail.example.com'];\n\nfunction hashStr(s) {\n  let h = 2166136261;\n  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }\n  return h >>> 0;\n}\nfunction rng(seed) {\n  let a = typeof seed === 'string' ? hashStr(seed) : seed >>> 0;\n  return function () {\n    a = (a + 0x6D2B79F5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction between(r, range) { return range[0] + r() * (range[1] - range[0]); }\nfunction pick(r, arr) { return arr[Math.floor(r() * arr.length)]; }\nfunction pad2(n) { return String(n).padStart(2, '0'); }\nfunction round2(n) { return Math.round(n * 100) / 100; }\nfunction isoDate(d) { return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()); }\n\n// The simulated \"world\": what really happened across both ad platforms and the CRM\n// in the last 24 hours. Deterministic for a given hour, so every poll sees the same\n// history and only the current hour grows.\nfunction simulateWorld(nowMs) {\n  const now = Math.floor(nowMs / 5000) * 5000;\n  const currentHour = Math.floor(now / HOUR_MS);\n  const hours = [];\n  const leads = [];\n  for (let hi = currentHour - WINDOW_HOURS + 1; hi <= currentHour; hi++) {\n    const start = hi * HOUR_MS;\n    const frac = hi === currentHour ? (now - start) / HOUR_MS : 1;\n    const w = HOUR_WEIGHT[new Date(start).getHours()];\n    const rows = [];\n    for (const c of CAMPAIGNS) {\n      const r = rng('h' + hi + c.id);\n      const impressionsFull = Math.round(between(r, c.imp) * w);\n      const clicksFull = Math.round(impressionsFull * between(r, c.ctr));\n      const spendFull = clicksFull * between(r, c.cpc);\n      const leadCount = Math.max(0, Math.round(clicksFull * between(r, c.cvr) + (r() - 0.5)));\n      let realised = 0;\n      for (let k = 0; k < leadCount; k++) {\n        const lr = rng('l' + hi + c.id + k);\n        const ts = start + Math.floor(lr() * HOUR_MS);\n        if (ts > now) continue;\n        realised++;\n        leads.push(makeLead(lr, c, ts, hi + c.id + k));\n      }\n      rows.push({\n        campaign: c,\n        impressions: Math.round(impressionsFull * frac),\n        clicks: Math.round(clicksFull * frac),\n        spend: round2(spendFull * frac),\n        leads: realised,\n        overReport: r() < 0.1 ? 1 : 0,\n      });\n    }\n    // Organic website-form leads (no ad spend).\n    const or = rng('o' + hi);\n    const organicCount = Math.round(or() * 1.4 * w);\n    for (let k = 0; k < organicCount; k++) {\n      const lr = rng('ol' + hi + k);\n      const ts = start + Math.floor(lr() * HOUR_MS);\n      if (ts <= now) leads.push(makeLead(lr, null, ts, 'o' + hi + k));\n    }\n    hours.push({ start, rows });\n  }\n  return { now, hours, leads };\n}\n\nfunction makeLead(r, c, ts, key) {\n  const first = pick(r, FIRST);\n  const last = pick(r, LAST);\n  const booked = r() < (c ? c.book : 0.3);\n  const valueRange = c ? c.value : [200, 900];\n  return {\n    id: 'ct_' + hashStr('lead' + key).toString(36),\n    key,\n    campaign: c,\n    ts,\n    first,\n    last,\n    email: (first + '.' + last + Math.floor(r() * 90 + 10)).toLowerCase() + '@' + pick(r, DOMAINS),\n    phone: '555' + String(Math.floor(r() * 9000000 + 1000000)),\n    booked,\n    value: booked ? Math.round(between(r, valueRange)) : 0,\n  };\n}\n\n// Shape mirrors a Google Ads API searchStream (GAQL) result row:\n// SELECT campaign.name, segments.date, segments.hour, metrics.impressions,\n//        metrics.clicks, metrics.cost_micros, metrics.conversions FROM campaign\nfunction extractGoogleAds(nowMs) {\n  const t0 = Date.now();\n  const world = simulateWorld(nowMs);\n  const rows = [];\n  for (const h of world.hours) {\n    const d = new Date(h.start);\n    for (const x of h.rows) {\n      if (x.campaign.channel !== 'Google Ads') continue;\n      const r = rng('gx' + h.start + x.campaign.id);\n      const row = {\n        _source: 'google_ads',\n        campaign: { name: r() < 0.12 ? ' ' + x.campaign.name.toLowerCase() : x.campaign.name },\n        segments: { date: isoDate(d), hour: d.getHours() },\n        metrics: {\n          impressions: String(x.impressions),\n          clicks: String(x.clicks),\n          cost_micros: String(Math.round(x.spend * 1e6)),\n          conversions: x.leads + (r() < 0.15 ? 1 : 0),\n        },\n      };\n      rows.push(row);\n      if (r() < 0.03) rows.push(JSON.parse(JSON.stringify(row)));\n    }\n  }\n  return { rows, ms: Date.now() - t0 };\n}\n\nconst res = extractGoogleAds(Date.now());\nreturn res.rows.map(r => ({ json: Object.assign(r, { _extractMs: res.ms }) }));\n"
      },
      "id": "04962d4b-43d8-55e6-9f4b-544b7544ced2",
      "name": "Extract: Google Ads Report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        280,
        320
      ],
      "notes": "Sample data shaped like a GAQL searchStream row",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// Generated from data-automation/pipeline.js by build_workflow.py. Edit pipeline.js, then rebuild.\n\nconst PIPELINE_VERSION = '1.0.0';\n\n// Campaign config: in production this is a lookup table (Google Sheet / Postgres)\n// that maps UTM values to ad-platform campaigns.\nconst CAMPAIGNS = [\n  { id: 'c1', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Dental Implants | Lead Form',    utm: 'dental_implants_lf',       imp: [500, 1200],  ctr: [0.012, 0.022], cvr: [0.05, 0.08], cpc: [2.0, 3.2],  book: 0.30, value: [400, 1200] },\n  { id: 'c2', client: 'Coastline Dental',   channel: 'Google Ads', name: 'Dental Implants | Search',       utm: 'dental_implants_search',   imp: [120, 300],   ctr: [0.05, 0.09],   cvr: [0.08, 0.12], cpc: [6, 11],     book: 0.40, value: [400, 1200] },\n  { id: 'c3', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Invisalign | Reels',             utm: 'invisalign_reels',         imp: [800, 1700],  ctr: [0.008, 0.016], cvr: [0.03, 0.06], cpc: [1.5, 2.6],  book: 0.20, value: [600, 1400] },\n  { id: 'c4', client: 'Gleam Auto Care',    channel: 'Meta Ads',   name: 'Ceramic Coating | Promo',        utm: 'ceramic_coating_promo',    imp: [500, 1200],  ctr: [0.010, 0.020], cvr: [0.04, 0.07], cpc: [1.2, 2.2],  book: 0.35, value: [300, 700] },\n  { id: 'c5', client: 'Gleam Auto Care',    channel: 'Google Ads', name: 'Car Detailing Near Me | Search', utm: 'detailing_search',         imp: [100, 250],   ctr: [0.06, 0.10],   cvr: [0.08, 0.14], cpc: [2.0, 3.5],  book: 0.45, value: [150, 320] },\n  { id: 'c6', client: 'Rapid Flow Plumbing', channel: 'Google Ads', name: 'Emergency Plumber | Search',    utm: 'emergency_plumber_search', imp: [90, 220],    ctr: [0.07, 0.12],   cvr: [0.10, 0.16], cpc: [9, 16],     book: 0.50, value: [300, 800] },\n  { id: 'c7', client: 'Rapid Flow Plumbing', channel: 'Meta Ads',   name: 'Water Heater | Lead Form',      utm: 'water_heater_lf',          imp: [400, 900],   ctr: [0.009, 0.018], cvr: [0.03, 0.06], cpc: [1.8, 3.0],  book: 0.25, value: [800, 1800] },\n];\n\nconst HOUR_MS = 3600000;\nconst WINDOW_HOURS = 24;\n// Relative activity by local hour of day (morning and evening peaks).\nconst HOUR_WEIGHT = [0.15, 0.1, 0.08, 0.08, 0.1, 0.2, 0.4, 0.65, 0.85, 1, 1, 0.95, 0.85, 0.8, 0.8, 0.85, 0.9, 0.95, 1, 1, 0.9, 0.7, 0.45, 0.25];\nconst FIRST = ['James', 'Maria', 'Robert', 'Linda', 'Michael', 'Patricia', 'David', 'Jennifer', 'Daniel', 'Elizabeth', 'Carlos', 'Aisha', 'Kevin', 'Grace', 'Brian', 'Sofia', 'Jason', 'Nina', 'Anthony', 'Chloe'];\nconst LAST = ['Smith', 'Garcia', 'Johnson', 'Nguyen', 'Brown', 'Martinez', 'Lee', 'Walker', 'Reyes', 'Hall', 'Young', 'Lopez', 'King', 'Wright', 'Scott', 'Torres', 'Hill', 'Adams', 'Baker', 'Rivera'];\nconst DOMAINS = ['example.com', 'example.net', 'example.org', 'mail.example.com'];\n\nfunction hashStr(s) {\n  let h = 2166136261;\n  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }\n  return h >>> 0;\n}\nfunction rng(seed) {\n  let a = typeof seed === 'string' ? hashStr(seed) : seed >>> 0;\n  return function () {\n    a = (a + 0x6D2B79F5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction between(r, range) { return range[0] + r() * (range[1] - range[0]); }\nfunction pick(r, arr) { return arr[Math.floor(r() * arr.length)]; }\nfunction pad2(n) { return String(n).padStart(2, '0'); }\nfunction round2(n) { return Math.round(n * 100) / 100; }\nfunction isoDate(d) { return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()); }\n\n// The simulated \"world\": what really happened across both ad platforms and the CRM\n// in the last 24 hours. Deterministic for a given hour, so every poll sees the same\n// history and only the current hour grows.\nfunction simulateWorld(nowMs) {\n  const now = Math.floor(nowMs / 5000) * 5000;\n  const currentHour = Math.floor(now / HOUR_MS);\n  const hours = [];\n  const leads = [];\n  for (let hi = currentHour - WINDOW_HOURS + 1; hi <= currentHour; hi++) {\n    const start = hi * HOUR_MS;\n    const frac = hi === currentHour ? (now - start) / HOUR_MS : 1;\n    const w = HOUR_WEIGHT[new Date(start).getHours()];\n    const rows = [];\n    for (const c of CAMPAIGNS) {\n      const r = rng('h' + hi + c.id);\n      const impressionsFull = Math.round(between(r, c.imp) * w);\n      const clicksFull = Math.round(impressionsFull * between(r, c.ctr));\n      const spendFull = clicksFull * between(r, c.cpc);\n      const leadCount = Math.max(0, Math.round(clicksFull * between(r, c.cvr) + (r() - 0.5)));\n      let realised = 0;\n      for (let k = 0; k < leadCount; k++) {\n        const lr = rng('l' + hi + c.id + k);\n        const ts = start + Math.floor(lr() * HOUR_MS);\n        if (ts > now) continue;\n        realised++;\n        leads.push(makeLead(lr, c, ts, hi + c.id + k));\n      }\n      rows.push({\n        campaign: c,\n        impressions: Math.round(impressionsFull * frac),\n        clicks: Math.round(clicksFull * frac),\n        spend: round2(spendFull * frac),\n        leads: realised,\n        overReport: r() < 0.1 ? 1 : 0,\n      });\n    }\n    // Organic website-form leads (no ad spend).\n    const or = rng('o' + hi);\n    const organicCount = Math.round(or() * 1.4 * w);\n    for (let k = 0; k < organicCount; k++) {\n      const lr = rng('ol' + hi + k);\n      const ts = start + Math.floor(lr() * HOUR_MS);\n      if (ts <= now) leads.push(makeLead(lr, null, ts, 'o' + hi + k));\n    }\n    hours.push({ start, rows });\n  }\n  return { now, hours, leads };\n}\n\nfunction makeLead(r, c, ts, key) {\n  const first = pick(r, FIRST);\n  const last = pick(r, LAST);\n  const booked = r() < (c ? c.book : 0.3);\n  const valueRange = c ? c.value : [200, 900];\n  return {\n    id: 'ct_' + hashStr('lead' + key).toString(36),\n    key,\n    campaign: c,\n    ts,\n    first,\n    last,\n    email: (first + '.' + last + Math.floor(r() * 90 + 10)).toLowerCase() + '@' + pick(r, DOMAINS),\n    phone: '555' + String(Math.floor(r() * 9000000 + 1000000)),\n    booked,\n    value: booked ? Math.round(between(r, valueRange)) : 0,\n  };\n}\n\n// Shape mirrors GoHighLevel contacts + opportunity data:\n// GET https://services.leadconnectorhq.com/contacts/?locationId=...\n// Real CRM exports are messy: mixed formats, duplicates, test leads, missing UTMs.\nfunction extractGhlContacts(nowMs) {\n  const t0 = Date.now();\n  const world = simulateWorld(nowMs);\n  const metaLabels = ['facebook', 'Facebook Lead Ads', 'FB', 'instagram', 'Meta'];\n  const googleLabels = ['google', 'Google Ads', 'adwords', 'google_cpc'];\n  const organicLabels = ['website', 'Website Form', 'organic'];\n  const rows = [];\n  const toRaw = function (lead, r, overrides) {\n    const c = lead.campaign;\n    const d = new Date(lead.ts);\n    const fmt = r();\n    const dateAdded = fmt < 0.6 ? d.toISOString()\n      : fmt < 0.85 ? pad2(d.getMonth() + 1) + '/' + pad2(d.getDate()) + '/' + d.getFullYear() + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes())\n      : lead.ts;\n    const p = lead.phone;\n    const pf = r();\n    const phone = pf < 0.05 ? '' : pf < 0.3 ? '(' + p.slice(0, 3) + ') ' + p.slice(3, 6) + '-' + p.slice(6)\n      : pf < 0.55 ? p.slice(0, 3) + '.' + p.slice(3, 6) + '.' + p.slice(6)\n      : pf < 0.8 ? '+1' + p : '1 ' + p;\n    const ef = r();\n    const email = ef < 0.04 ? pick(r, ['n/a', 'none', 'test@', ''])\n      : ef < 0.3 ? '  ' + lead.email.replace(/^./, function (m) { return m.toUpperCase(); }).replace(/@.*$/, function (m) { return m.toUpperCase(); }) + ' '\n      : lead.email;\n    const labels = !c ? organicLabels : c.channel === 'Meta Ads' ? metaLabels : googleLabels;\n    const raw = {\n      _source: 'ghl',\n      id: lead.id,\n      firstName: r() < 0.2 ? lead.first.toLowerCase() + ' ' : lead.first,\n      lastName: r() < 0.15 ? lead.last.toUpperCase() : lead.last,\n      email,\n      phone,\n      source: pick(r, labels),\n      tags: c ? [c.client.split(' ')[0].toLowerCase(), 'new lead'] : ['website'],\n      dateAdded,\n      customFields: { utm_campaign: c && r() > 0.08 ? c.utm : null },\n      opportunity: {\n        status: lead.booked ? 'won' : r() < 0.2 ? 'lost' : 'open',\n        monetaryValue: lead.booked ? (r() < 0.5 ? lead.value.toLocaleString('en-US') + '.00' : lead.value) : null,\n      },\n    };\n    return Object.assign(raw, overrides || {});\n  };\n  for (const lead of world.leads) {\n    const r = rng('gh' + lead.key);\n    rows.push(toRaw(lead, r));\n    // Same person re-submits the form a few minutes later (duplicate contact).\n    if (r() < 0.07) {\n      const ts = lead.ts + Math.floor(2 + r() * 18) * 60000;\n      if (ts <= world.now) {\n        const dup = toRaw(Object.assign({}, lead, { ts }), rng('dup' + lead.key), { id: lead.id + 'd' });\n        dup.email = '  ' + lead.email.toUpperCase();\n        rows.push(dup);\n      }\n    }\n  }\n  // Staff test submissions that must never reach reporting.\n  const firstHour = world.hours[0].start;\n  for (let t = firstHour; t <= world.now; t += 6 * HOUR_MS) {\n    const r = rng('test' + t);\n    rows.push({\n      _source: 'ghl', id: 'ct_test' + t.toString(36), firstName: 'Test', lastName: 'Lead',\n      email: 'test@example.com', phone: '5555555555', source: 'Website Form', tags: ['test'],\n      dateAdded: new Date(t + Math.floor(r() * HOUR_MS)).toISOString(),\n      customFields: { utm_campaign: null }, opportunity: { status: 'open', monetaryValue: null },\n    });\n  }\n  return { rows, ms: Date.now() - t0 };\n}\n\nconst res = extractGhlContacts(Date.now());\nreturn res.rows.map(r => ({ json: Object.assign(r, { _extractMs: res.ms }) }));\n"
      },
      "id": "43522f61-0a39-516a-bddb-908b25dc2a9e",
      "name": "Extract: GHL CRM Contacts",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        280,
        520
      ],
      "notes": "Sample data shaped like GHL /contacts/",
      "notesInFlow": true
    },
    {
      "parameters": {
        "numberInputs": 3
      },
      "id": "c1ffa1da-df72-57ea-9254-d96a46c7b5fc",
      "name": "Merge Sources",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        560,
        320
      ]
    },
    {
      "parameters": {
        "jsCode": "// Generated from data-automation/pipeline.js by build_workflow.py. Edit pipeline.js, then rebuild.\n\nconst PIPELINE_VERSION = '1.0.0';\n\n// Campaign config: in production this is a lookup table (Google Sheet / Postgres)\n// that maps UTM values to ad-platform campaigns.\nconst CAMPAIGNS = [\n  { id: 'c1', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Dental Implants | Lead Form',    utm: 'dental_implants_lf',       imp: [500, 1200],  ctr: [0.012, 0.022], cvr: [0.05, 0.08], cpc: [2.0, 3.2],  book: 0.30, value: [400, 1200] },\n  { id: 'c2', client: 'Coastline Dental',   channel: 'Google Ads', name: 'Dental Implants | Search',       utm: 'dental_implants_search',   imp: [120, 300],   ctr: [0.05, 0.09],   cvr: [0.08, 0.12], cpc: [6, 11],     book: 0.40, value: [400, 1200] },\n  { id: 'c3', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Invisalign | Reels',             utm: 'invisalign_reels',         imp: [800, 1700],  ctr: [0.008, 0.016], cvr: [0.03, 0.06], cpc: [1.5, 2.6],  book: 0.20, value: [600, 1400] },\n  { id: 'c4', client: 'Gleam Auto Care',    channel: 'Meta Ads',   name: 'Ceramic Coating | Promo',        utm: 'ceramic_coating_promo',    imp: [500, 1200],  ctr: [0.010, 0.020], cvr: [0.04, 0.07], cpc: [1.2, 2.2],  book: 0.35, value: [300, 700] },\n  { id: 'c5', client: 'Gleam Auto Care',    channel: 'Google Ads', name: 'Car Detailing Near Me | Search', utm: 'detailing_search',         imp: [100, 250],   ctr: [0.06, 0.10],   cvr: [0.08, 0.14], cpc: [2.0, 3.5],  book: 0.45, value: [150, 320] },\n  { id: 'c6', client: 'Rapid Flow Plumbing', channel: 'Google Ads', name: 'Emergency Plumber | Search',    utm: 'emergency_plumber_search', imp: [90, 220],    ctr: [0.07, 0.12],   cvr: [0.10, 0.16], cpc: [9, 16],     book: 0.50, value: [300, 800] },\n  { id: 'c7', client: 'Rapid Flow Plumbing', channel: 'Meta Ads',   name: 'Water Heater | Lead Form',      utm: 'water_heater_lf',          imp: [400, 900],   ctr: [0.009, 0.018], cvr: [0.03, 0.06], cpc: [1.8, 3.0],  book: 0.25, value: [800, 1800] },\n];\n\nconst HOUR_MS = 3600000;\nconst WINDOW_HOURS = 24;\n// Relative activity by local hour of day (morning and evening peaks).\nconst HOUR_WEIGHT = [0.15, 0.1, 0.08, 0.08, 0.1, 0.2, 0.4, 0.65, 0.85, 1, 1, 0.95, 0.85, 0.8, 0.8, 0.85, 0.9, 0.95, 1, 1, 0.9, 0.7, 0.45, 0.25];\nconst FIRST = ['James', 'Maria', 'Robert', 'Linda', 'Michael', 'Patricia', 'David', 'Jennifer', 'Daniel', 'Elizabeth', 'Carlos', 'Aisha', 'Kevin', 'Grace', 'Brian', 'Sofia', 'Jason', 'Nina', 'Anthony', 'Chloe'];\nconst LAST = ['Smith', 'Garcia', 'Johnson', 'Nguyen', 'Brown', 'Martinez', 'Lee', 'Walker', 'Reyes', 'Hall', 'Young', 'Lopez', 'King', 'Wright', 'Scott', 'Torres', 'Hill', 'Adams', 'Baker', 'Rivera'];\nconst DOMAINS = ['example.com', 'example.net', 'example.org', 'mail.example.com'];\n\nfunction hashStr(s) {\n  let h = 2166136261;\n  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }\n  return h >>> 0;\n}\nfunction rng(seed) {\n  let a = typeof seed === 'string' ? hashStr(seed) : seed >>> 0;\n  return function () {\n    a = (a + 0x6D2B79F5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction between(r, range) { return range[0] + r() * (range[1] - range[0]); }\nfunction pick(r, arr) { return arr[Math.floor(r() * arr.length)]; }\nfunction pad2(n) { return String(n).padStart(2, '0'); }\nfunction round2(n) { return Math.round(n * 100) / 100; }\nfunction isoDate(d) { return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()); }\n\n// The simulated \"world\": what really happened across both ad platforms and the CRM\n// in the last 24 hours. Deterministic for a given hour, so every poll sees the same\n// history and only the current hour grows.\nfunction simulateWorld(nowMs) {\n  const now = Math.floor(nowMs / 5000) * 5000;\n  const currentHour = Math.floor(now / HOUR_MS);\n  const hours = [];\n  const leads = [];\n  for (let hi = currentHour - WINDOW_HOURS + 1; hi <= currentHour; hi++) {\n    const start = hi * HOUR_MS;\n    const frac = hi === currentHour ? (now - start) / HOUR_MS : 1;\n    const w = HOUR_WEIGHT[new Date(start).getHours()];\n    const rows = [];\n    for (const c of CAMPAIGNS) {\n      const r = rng('h' + hi + c.id);\n      const impressionsFull = Math.round(between(r, c.imp) * w);\n      const clicksFull = Math.round(impressionsFull * between(r, c.ctr));\n      const spendFull = clicksFull * between(r, c.cpc);\n      const leadCount = Math.max(0, Math.round(clicksFull * between(r, c.cvr) + (r() - 0.5)));\n      let realised = 0;\n      for (let k = 0; k < leadCount; k++) {\n        const lr = rng('l' + hi + c.id + k);\n        const ts = start + Math.floor(lr() * HOUR_MS);\n        if (ts > now) continue;\n        realised++;\n        leads.push(makeLead(lr, c, ts, hi + c.id + k));\n      }\n      rows.push({\n        campaign: c,\n        impressions: Math.round(impressionsFull * frac),\n        clicks: Math.round(clicksFull * frac),\n        spend: round2(spendFull * frac),\n        leads: realised,\n        overReport: r() < 0.1 ? 1 : 0,\n      });\n    }\n    // Organic website-form leads (no ad spend).\n    const or = rng('o' + hi);\n    const organicCount = Math.round(or() * 1.4 * w);\n    for (let k = 0; k < organicCount; k++) {\n      const lr = rng('ol' + hi + k);\n      const ts = start + Math.floor(lr() * HOUR_MS);\n      if (ts <= now) leads.push(makeLead(lr, null, ts, 'o' + hi + k));\n    }\n    hours.push({ start, rows });\n  }\n  return { now, hours, leads };\n}\n\nfunction makeLead(r, c, ts, key) {\n  const first = pick(r, FIRST);\n  const last = pick(r, LAST);\n  const booked = r() < (c ? c.book : 0.3);\n  const valueRange = c ? c.value : [200, 900];\n  return {\n    id: 'ct_' + hashStr('lead' + key).toString(36),\n    key,\n    campaign: c,\n    ts,\n    first,\n    last,\n    email: (first + '.' + last + Math.floor(r() * 90 + 10)).toLowerCase() + '@' + pick(r, DOMAINS),\n    phone: '555' + String(Math.floor(r() * 9000000 + 1000000)),\n    booked,\n    value: booked ? Math.round(between(r, valueRange)) : 0,\n  };\n}\n\n// Input: every raw row from the three sources (n8n Merge node output).\n// Output: one object with clean ad rows, clean leads, quality stats and samples.\nfunction cleanData(rawRows) {\n  const t0 = Date.now();\n  const q = {\n    rawRows: rawRows.length, bySource: { meta_ads: 0, google_ads: 0, ghl: 0 },\n    duplicatesRemoved: 0, testLeadsRemoved: 0, invalidEmails: 0, emailsNormalized: 0,\n    phonesNormalized: 0, missingPhones: 0, sourcesMapped: 0, datesParsed: 0,\n    nullSpendFilled: 0, campaignNamesFixed: 0, microsConverted: 0, cleanRows: 0,\n  };\n  const extractMs = {};\n  const ads = [];\n  const adKeys = new Set();\n  const contacts = [];\n  for (const row of rawRows) {\n    const src = row._source;\n    if (q.bySource[src] !== undefined) q.bySource[src]++;\n    if (row._extractMs !== undefined) extractMs[src] = row._extractMs;\n    if (src === 'meta_ads' || src === 'google_ads') {\n      const isMeta = src === 'meta_ads';\n      const rawName = isMeta ? row.campaign_name : row.campaign.name;\n      const name = String(rawName || '').trim().replace(/\\s+/g, ' ');\n      const canonical = CAMPAIGNS.find(function (c) { return c.name.toLowerCase() === name.toLowerCase(); });\n      if (rawName !== (canonical ? canonical.name : name)) q.campaignNamesFixed++;\n      const date = isMeta ? row.date_start : row.segments.date;\n      const hour = isMeta ? parseInt(row.hourly_stats_aggregated_by_advertiser_time_zone, 10) : Number(row.segments.hour);\n      const key = src + '|' + name.toLowerCase() + '|' + date + '|' + hour;\n      if (adKeys.has(key)) { q.duplicatesRemoved++; continue; }\n      adKeys.add(key);\n      let spend;\n      if (isMeta) {\n        if (row.spend === null || row.spend === undefined || row.spend === '') { spend = 0; q.nullSpendFilled++; } else spend = parseFloat(row.spend);\n      } else { spend = Number(row.metrics.cost_micros) / 1e6; q.microsConverted++; }\n      const leadAction = isMeta ? (row.actions || []).find(function (a) { return a.action_type === 'lead'; }) : null;\n      ads.push({\n        channel: isMeta ? 'Meta Ads' : 'Google Ads',\n        campaign: canonical ? canonical.name : name,\n        client: canonical ? canonical.client : 'Unknown',\n        date, hour,\n        hourStart: new Date(date + 'T' + pad2(hour) + ':00:00').getTime(),\n        impressions: parseInt(isMeta ? row.impressions : row.metrics.impressions, 10) || 0,\n        clicks: parseInt(isMeta ? row.clicks : row.metrics.clicks, 10) || 0,\n        spend: round2(spend || 0),\n        platformLeads: isMeta ? parseInt(leadAction ? leadAction.value : '0', 10) : Number(row.metrics.conversions) || 0,\n      });\n    } else if (src === 'ghl') {\n      contacts.push(row);\n    }\n  }\n\n  const sourceMap = function (s) {\n    const v = String(s || '').toLowerCase().trim();\n    if (/facebook|fb|instagram|meta/.test(v)) return 'Meta Ads';\n    if (/google|adwords|cpc/.test(v)) return 'Google Ads';\n    return 'Organic';\n  };\n  const parseDate = function (v) {\n    if (typeof v === 'number') return v;\n    const s = String(v).trim();\n    const us = s.match(/^(\\d{2})\\/(\\d{2})\\/(\\d{4}) (\\d{2}):(\\d{2})$/);\n    if (us) return new Date(+us[3], +us[1] - 1, +us[2], +us[4], +us[5]).getTime();\n    return new Date(s).getTime();\n  };\n  const normPhone = function (p) {\n    const digits = String(p || '').replace(/\\D/g, '');\n    if (digits.length === 10) return '+1' + digits;\n    if (digits.length === 11 && digits.charAt(0) === '1') return '+' + digits;\n    return null;\n  };\n  const titleCase = function (s) { s = String(s || '').trim().toLowerCase(); return s.charAt(0).toUpperCase() + s.slice(1); };\n  const emailRe = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n  const sorted = contacts.slice().sort(function (a, b) { return parseDate(a.dateAdded) - parseDate(b.dateAdded); });\n  const seen = new Map();\n  const leads = [];\n  const samples = [];\n  for (const row of sorted) {\n    const issues = [];\n    if (/^test$/i.test(String(row.firstName).trim()) || (row.tags || []).indexOf('test') >= 0) {\n      q.testLeadsRemoved++;\n      if (!samples.some(function (s) { return s.result === 'Removed: test lead'; })) samples.push({ raw: row, issues: ['test submission'], result: 'Removed: test lead' });\n      continue;\n    }\n    const rawEmail = String(row.email || '');\n    let email = rawEmail.trim().toLowerCase();\n    if (email !== rawEmail) { q.emailsNormalized++; issues.push('email case/whitespace'); }\n    if (!emailRe.test(email)) { q.invalidEmails++; issues.push('invalid email'); email = null; }\n    const phone = normPhone(row.phone);\n    if (phone && phone !== row.phone) { q.phonesNormalized++; issues.push('phone format'); }\n    if (!phone) { q.missingPhones++; issues.push('missing phone'); }\n    const ts = parseDate(row.dateAdded);\n    if (typeof row.dateAdded !== 'string' || !/T/.test(row.dateAdded)) { q.datesParsed++; issues.push('date format'); }\n    const channel = sourceMap(row.source);\n    if (row.source !== channel) q.sourcesMapped++;\n    const dedupeKey = email || phone || row.id;\n    if (seen.has(dedupeKey)) {\n      q.duplicatesRemoved++;\n      if (!samples.some(function (s) { return s.result === 'Removed: duplicate'; })) samples.push({ raw: row, issues: issues.concat(['duplicate of ' + seen.get(dedupeKey)]), result: 'Removed: duplicate' });\n      continue;\n    }\n    seen.set(dedupeKey, row.id);\n    const mv = row.opportunity && row.opportunity.monetaryValue;\n    const value = mv === null || mv === undefined ? 0 : parseFloat(String(mv).replace(/,/g, '')) || 0;\n    const lead = {\n      id: row.id,\n      name: titleCase(row.firstName) + ' ' + titleCase(row.lastName),\n      email, phone, channel,\n      utm: row.customFields ? row.customFields.utm_campaign : null,\n      ts, booked: row.opportunity && row.opportunity.status === 'won', value,\n    };\n    leads.push(lead);\n    if (issues.length >= 2 && samples.filter(function (s) { return typeof s.result !== 'string'; }).length < 4) samples.push({ raw: row, issues, result: lead });\n  }\n  q.cleanRows = ads.length + leads.length;\n  const fixes = q.emailsNormalized + q.invalidEmails + q.phonesNormalized + q.datesParsed + q.sourcesMapped + q.nullSpendFilled + q.campaignNamesFixed;\n  q.score = Math.round(100 * q.cleanRows / Math.max(1, q.cleanRows + q.duplicatesRemoved + q.testLeadsRemoved + q.invalidEmails + q.missingPhones));\n  q.fixes = fixes;\n  return { ads, leads, quality: q, samples, timings: { extract: extractMs, clean: Date.now() - t0 } };\n}\n\nreturn [{ json: cleanData($input.all().map(i => i.json)) }];\n"
      },
      "id": "c54bb5a1-5a19-543a-ae43-04f2ece3d7e0",
      "name": "Clean Data",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        800,
        320
      ],
      "notes": "Dedupe, normalize, validate, drop test leads",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// Generated from data-automation/pipeline.js by build_workflow.py. Edit pipeline.js, then rebuild.\n\nconst PIPELINE_VERSION = '1.0.0';\n\n// Campaign config: in production this is a lookup table (Google Sheet / Postgres)\n// that maps UTM values to ad-platform campaigns.\nconst CAMPAIGNS = [\n  { id: 'c1', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Dental Implants | Lead Form',    utm: 'dental_implants_lf',       imp: [500, 1200],  ctr: [0.012, 0.022], cvr: [0.05, 0.08], cpc: [2.0, 3.2],  book: 0.30, value: [400, 1200] },\n  { id: 'c2', client: 'Coastline Dental',   channel: 'Google Ads', name: 'Dental Implants | Search',       utm: 'dental_implants_search',   imp: [120, 300],   ctr: [0.05, 0.09],   cvr: [0.08, 0.12], cpc: [6, 11],     book: 0.40, value: [400, 1200] },\n  { id: 'c3', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Invisalign | Reels',             utm: 'invisalign_reels',         imp: [800, 1700],  ctr: [0.008, 0.016], cvr: [0.03, 0.06], cpc: [1.5, 2.6],  book: 0.20, value: [600, 1400] },\n  { id: 'c4', client: 'Gleam Auto Care',    channel: 'Meta Ads',   name: 'Ceramic Coating | Promo',        utm: 'ceramic_coating_promo',    imp: [500, 1200],  ctr: [0.010, 0.020], cvr: [0.04, 0.07], cpc: [1.2, 2.2],  book: 0.35, value: [300, 700] },\n  { id: 'c5', client: 'Gleam Auto Care',    channel: 'Google Ads', name: 'Car Detailing Near Me | Search', utm: 'detailing_search',         imp: [100, 250],   ctr: [0.06, 0.10],   cvr: [0.08, 0.14], cpc: [2.0, 3.5],  book: 0.45, value: [150, 320] },\n  { id: 'c6', client: 'Rapid Flow Plumbing', channel: 'Google Ads', name: 'Emergency Plumber | Search',    utm: 'emergency_plumber_search', imp: [90, 220],    ctr: [0.07, 0.12],   cvr: [0.10, 0.16], cpc: [9, 16],     book: 0.50, value: [300, 800] },\n  { id: 'c7', client: 'Rapid Flow Plumbing', channel: 'Meta Ads',   name: 'Water Heater | Lead Form',      utm: 'water_heater_lf',          imp: [400, 900],   ctr: [0.009, 0.018], cvr: [0.03, 0.06], cpc: [1.8, 3.0],  book: 0.25, value: [800, 1800] },\n];\n\nconst HOUR_MS = 3600000;\nconst WINDOW_HOURS = 24;\n// Relative activity by local hour of day (morning and evening peaks).\nconst HOUR_WEIGHT = [0.15, 0.1, 0.08, 0.08, 0.1, 0.2, 0.4, 0.65, 0.85, 1, 1, 0.95, 0.85, 0.8, 0.8, 0.85, 0.9, 0.95, 1, 1, 0.9, 0.7, 0.45, 0.25];\nconst FIRST = ['James', 'Maria', 'Robert', 'Linda', 'Michael', 'Patricia', 'David', 'Jennifer', 'Daniel', 'Elizabeth', 'Carlos', 'Aisha', 'Kevin', 'Grace', 'Brian', 'Sofia', 'Jason', 'Nina', 'Anthony', 'Chloe'];\nconst LAST = ['Smith', 'Garcia', 'Johnson', 'Nguyen', 'Brown', 'Martinez', 'Lee', 'Walker', 'Reyes', 'Hall', 'Young', 'Lopez', 'King', 'Wright', 'Scott', 'Torres', 'Hill', 'Adams', 'Baker', 'Rivera'];\nconst DOMAINS = ['example.com', 'example.net', 'example.org', 'mail.example.com'];\n\nfunction hashStr(s) {\n  let h = 2166136261;\n  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }\n  return h >>> 0;\n}\nfunction rng(seed) {\n  let a = typeof seed === 'string' ? hashStr(seed) : seed >>> 0;\n  return function () {\n    a = (a + 0x6D2B79F5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction between(r, range) { return range[0] + r() * (range[1] - range[0]); }\nfunction pick(r, arr) { return arr[Math.floor(r() * arr.length)]; }\nfunction pad2(n) { return String(n).padStart(2, '0'); }\nfunction round2(n) { return Math.round(n * 100) / 100; }\nfunction isoDate(d) { return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()); }\n\n// The simulated \"world\": what really happened across both ad platforms and the CRM\n// in the last 24 hours. Deterministic for a given hour, so every poll sees the same\n// history and only the current hour grows.\nfunction simulateWorld(nowMs) {\n  const now = Math.floor(nowMs / 5000) * 5000;\n  const currentHour = Math.floor(now / HOUR_MS);\n  const hours = [];\n  const leads = [];\n  for (let hi = currentHour - WINDOW_HOURS + 1; hi <= currentHour; hi++) {\n    const start = hi * HOUR_MS;\n    const frac = hi === currentHour ? (now - start) / HOUR_MS : 1;\n    const w = HOUR_WEIGHT[new Date(start).getHours()];\n    const rows = [];\n    for (const c of CAMPAIGNS) {\n      const r = rng('h' + hi + c.id);\n      const impressionsFull = Math.round(between(r, c.imp) * w);\n      const clicksFull = Math.round(impressionsFull * between(r, c.ctr));\n      const spendFull = clicksFull * between(r, c.cpc);\n      const leadCount = Math.max(0, Math.round(clicksFull * between(r, c.cvr) + (r() - 0.5)));\n      let realised = 0;\n      for (let k = 0; k < leadCount; k++) {\n        const lr = rng('l' + hi + c.id + k);\n        const ts = start + Math.floor(lr() * HOUR_MS);\n        if (ts > now) continue;\n        realised++;\n        leads.push(makeLead(lr, c, ts, hi + c.id + k));\n      }\n      rows.push({\n        campaign: c,\n        impressions: Math.round(impressionsFull * frac),\n        clicks: Math.round(clicksFull * frac),\n        spend: round2(spendFull * frac),\n        leads: realised,\n        overReport: r() < 0.1 ? 1 : 0,\n      });\n    }\n    // Organic website-form leads (no ad spend).\n    const or = rng('o' + hi);\n    const organicCount = Math.round(or() * 1.4 * w);\n    for (let k = 0; k < organicCount; k++) {\n      const lr = rng('ol' + hi + k);\n      const ts = start + Math.floor(lr() * HOUR_MS);\n      if (ts <= now) leads.push(makeLead(lr, null, ts, 'o' + hi + k));\n    }\n    hours.push({ start, rows });\n  }\n  return { now, hours, leads };\n}\n\nfunction makeLead(r, c, ts, key) {\n  const first = pick(r, FIRST);\n  const last = pick(r, LAST);\n  const booked = r() < (c ? c.book : 0.3);\n  const valueRange = c ? c.value : [200, 900];\n  return {\n    id: 'ct_' + hashStr('lead' + key).toString(36),\n    key,\n    campaign: c,\n    ts,\n    first,\n    last,\n    email: (first + '.' + last + Math.floor(r() * 90 + 10)).toLowerCase() + '@' + pick(r, DOMAINS),\n    phone: '555' + String(Math.floor(r() * 9000000 + 1000000)),\n    booked,\n    value: booked ? Math.round(between(r, valueRange)) : 0,\n  };\n}\n\n// Joins CRM leads to ad campaigns through the UTM lookup table and models\n// campaign-level and hour-level fact tables.\nfunction transformData(cleaned) {\n  const t0 = Date.now();\n  const byUtm = {};\n  CAMPAIGNS.forEach(function (c) { byUtm[c.utm] = c; });\n  const facts = {};\n  const factFor = function (campaign, channel, client) {\n    const k = channel + '|' + campaign;\n    if (!facts[k]) facts[k] = { campaign, channel, client, spend: 0, impressions: 0, clicks: 0, platformLeads: 0, leads: 0, booked: 0, revenue: 0 };\n    return facts[k];\n  };\n  const hourKeys = [];\n  const hourly = {};\n  const nowHour = Math.floor(Date.now() / HOUR_MS);\n  for (let hi = nowHour - WINDOW_HOURS + 1; hi <= nowHour; hi++) {\n    hourKeys.push(hi * HOUR_MS);\n    hourly[hi * HOUR_MS] = { start: hi * HOUR_MS, spend: 0, leads: { 'Meta Ads': 0, 'Google Ads': 0, Organic: 0 }, booked: 0 };\n  }\n  const bucket = function (ms) { return Math.floor(ms / HOUR_MS) * HOUR_MS; };\n  for (const a of cleaned.ads) {\n    const f = factFor(a.campaign, a.channel, a.client);\n    f.spend += a.spend; f.impressions += a.impressions; f.clicks += a.clicks; f.platformLeads += a.platformLeads;\n    const h = hourly[bucket(a.hourStart)];\n    if (h) h.spend += a.spend;\n  }\n  let unattributed = 0;\n  const enriched = cleaned.leads.map(function (l) {\n    const c = l.utm ? byUtm[l.utm] : null;\n    let f;\n    if (c) f = factFor(c.name, c.channel, c.client);\n    else if (l.channel === 'Organic') f = factFor('Website Form', 'Organic', 'All clients');\n    else { unattributed++; f = factFor('(unattributed ' + l.channel + ' leads)', l.channel, 'Missing UTM'); }\n    f.leads++; if (l.booked) { f.booked++; f.revenue += l.value; }\n    const h = hourly[bucket(l.ts)];\n    if (h) { h.leads[l.channel]++; if (l.booked) h.booked++; }\n    return Object.assign({}, l, { campaign: f.campaign, client: f.client });\n  });\n  const campaignFacts = Object.keys(facts).map(function (k) {\n    const f = facts[k];\n    f.spend = round2(f.spend);\n    return f;\n  });\n  return {\n    campaignFacts,\n    hourly: hourKeys.map(function (k) { const h = hourly[k]; h.spend = round2(h.spend); return h; }),\n    leads: enriched,\n    unattributed,\n    quality: cleaned.quality,\n    samples: cleaned.samples,\n    timings: Object.assign({}, cleaned.timings, { transform: Date.now() - t0 }),\n    counts: { adRows: cleaned.ads.length, leadRows: cleaned.leads.length, factRows: campaignFacts.length },\n  };\n}\n\nreturn [{ json: transformData($input.first().json) }];\n"
      },
      "id": "8a79c939-acfc-56ff-8cbf-aa879cf6d7fd",
      "name": "Transform Data",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        320
      ],
      "notes": "UTM join + campaign and hourly fact tables",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// Generated from data-automation/pipeline.js by build_workflow.py. Edit pipeline.js, then rebuild.\n\nconst PIPELINE_VERSION = '1.0.0';\n\n// Campaign config: in production this is a lookup table (Google Sheet / Postgres)\n// that maps UTM values to ad-platform campaigns.\nconst CAMPAIGNS = [\n  { id: 'c1', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Dental Implants | Lead Form',    utm: 'dental_implants_lf',       imp: [500, 1200],  ctr: [0.012, 0.022], cvr: [0.05, 0.08], cpc: [2.0, 3.2],  book: 0.30, value: [400, 1200] },\n  { id: 'c2', client: 'Coastline Dental',   channel: 'Google Ads', name: 'Dental Implants | Search',       utm: 'dental_implants_search',   imp: [120, 300],   ctr: [0.05, 0.09],   cvr: [0.08, 0.12], cpc: [6, 11],     book: 0.40, value: [400, 1200] },\n  { id: 'c3', client: 'Coastline Dental',   channel: 'Meta Ads',   name: 'Invisalign | Reels',             utm: 'invisalign_reels',         imp: [800, 1700],  ctr: [0.008, 0.016], cvr: [0.03, 0.06], cpc: [1.5, 2.6],  book: 0.20, value: [600, 1400] },\n  { id: 'c4', client: 'Gleam Auto Care',    channel: 'Meta Ads',   name: 'Ceramic Coating | Promo',        utm: 'ceramic_coating_promo',    imp: [500, 1200],  ctr: [0.010, 0.020], cvr: [0.04, 0.07], cpc: [1.2, 2.2],  book: 0.35, value: [300, 700] },\n  { id: 'c5', client: 'Gleam Auto Care',    channel: 'Google Ads', name: 'Car Detailing Near Me | Search', utm: 'detailing_search',         imp: [100, 250],   ctr: [0.06, 0.10],   cvr: [0.08, 0.14], cpc: [2.0, 3.5],  book: 0.45, value: [150, 320] },\n  { id: 'c6', client: 'Rapid Flow Plumbing', channel: 'Google Ads', name: 'Emergency Plumber | Search',    utm: 'emergency_plumber_search', imp: [90, 220],    ctr: [0.07, 0.12],   cvr: [0.10, 0.16], cpc: [9, 16],     book: 0.50, value: [300, 800] },\n  { id: 'c7', client: 'Rapid Flow Plumbing', channel: 'Meta Ads',   name: 'Water Heater | Lead Form',      utm: 'water_heater_lf',          imp: [400, 900],   ctr: [0.009, 0.018], cvr: [0.03, 0.06], cpc: [1.8, 3.0],  book: 0.25, value: [800, 1800] },\n];\n\nconst HOUR_MS = 3600000;\nconst WINDOW_HOURS = 24;\n// Relative activity by local hour of day (morning and evening peaks).\nconst HOUR_WEIGHT = [0.15, 0.1, 0.08, 0.08, 0.1, 0.2, 0.4, 0.65, 0.85, 1, 1, 0.95, 0.85, 0.8, 0.8, 0.85, 0.9, 0.95, 1, 1, 0.9, 0.7, 0.45, 0.25];\nconst FIRST = ['James', 'Maria', 'Robert', 'Linda', 'Michael', 'Patricia', 'David', 'Jennifer', 'Daniel', 'Elizabeth', 'Carlos', 'Aisha', 'Kevin', 'Grace', 'Brian', 'Sofia', 'Jason', 'Nina', 'Anthony', 'Chloe'];\nconst LAST = ['Smith', 'Garcia', 'Johnson', 'Nguyen', 'Brown', 'Martinez', 'Lee', 'Walker', 'Reyes', 'Hall', 'Young', 'Lopez', 'King', 'Wright', 'Scott', 'Torres', 'Hill', 'Adams', 'Baker', 'Rivera'];\nconst DOMAINS = ['example.com', 'example.net', 'example.org', 'mail.example.com'];\n\nfunction hashStr(s) {\n  let h = 2166136261;\n  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }\n  return h >>> 0;\n}\nfunction rng(seed) {\n  let a = typeof seed === 'string' ? hashStr(seed) : seed >>> 0;\n  return function () {\n    a = (a + 0x6D2B79F5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction between(r, range) { return range[0] + r() * (range[1] - range[0]); }\nfunction pick(r, arr) { return arr[Math.floor(r() * arr.length)]; }\nfunction pad2(n) { return String(n).padStart(2, '0'); }\nfunction round2(n) { return Math.round(n * 100) / 100; }\nfunction isoDate(d) { return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()); }\n\n// The simulated \"world\": what really happened across both ad platforms and the CRM\n// in the last 24 hours. Deterministic for a given hour, so every poll sees the same\n// history and only the current hour grows.\nfunction simulateWorld(nowMs) {\n  const now = Math.floor(nowMs / 5000) * 5000;\n  const currentHour = Math.floor(now / HOUR_MS);\n  const hours = [];\n  const leads = [];\n  for (let hi = currentHour - WINDOW_HOURS + 1; hi <= currentHour; hi++) {\n    const start = hi * HOUR_MS;\n    const frac = hi === currentHour ? (now - start) / HOUR_MS : 1;\n    const w = HOUR_WEIGHT[new Date(start).getHours()];\n    const rows = [];\n    for (const c of CAMPAIGNS) {\n      const r = rng('h' + hi + c.id);\n      const impressionsFull = Math.round(between(r, c.imp) * w);\n      const clicksFull = Math.round(impressionsFull * between(r, c.ctr));\n      const spendFull = clicksFull * between(r, c.cpc);\n      const leadCount = Math.max(0, Math.round(clicksFull * between(r, c.cvr) + (r() - 0.5)));\n      let realised = 0;\n      for (let k = 0; k < leadCount; k++) {\n        const lr = rng('l' + hi + c.id + k);\n        const ts = start + Math.floor(lr() * HOUR_MS);\n        if (ts > now) continue;\n        realised++;\n        leads.push(makeLead(lr, c, ts, hi + c.id + k));\n      }\n      rows.push({\n        campaign: c,\n        impressions: Math.round(impressionsFull * frac),\n        clicks: Math.round(clicksFull * frac),\n        spend: round2(spendFull * frac),\n        leads: realised,\n        overReport: r() < 0.1 ? 1 : 0,\n      });\n    }\n    // Organic website-form leads (no ad spend).\n    const or = rng('o' + hi);\n    const organicCount = Math.round(or() * 1.4 * w);\n    for (let k = 0; k < organicCount; k++) {\n      const lr = rng('ol' + hi + k);\n      const ts = start + Math.floor(lr() * HOUR_MS);\n      if (ts <= now) leads.push(makeLead(lr, null, ts, 'o' + hi + k));\n    }\n    hours.push({ start, rows });\n  }\n  return { now, hours, leads };\n}\n\nfunction makeLead(r, c, ts, key) {\n  const first = pick(r, FIRST);\n  const last = pick(r, LAST);\n  const booked = r() < (c ? c.book : 0.3);\n  const valueRange = c ? c.value : [200, 900];\n  return {\n    id: 'ct_' + hashStr('lead' + key).toString(36),\n    key,\n    campaign: c,\n    ts,\n    first,\n    last,\n    email: (first + '.' + last + Math.floor(r() * 90 + 10)).toLowerCase() + '@' + pick(r, DOMAINS),\n    phone: '555' + String(Math.floor(r() * 9000000 + 1000000)),\n    booked,\n    value: booked ? Math.round(between(r, valueRange)) : 0,\n  };\n}\n\n// Builds the JSON payload the dashboard renders: KPIs, breakdowns, insights.\nfunction analyzeData(model) {\n  const t0 = Date.now();\n  const sum = function (arr, k) { return arr.reduce(function (s, x) { return s + (x[k] || 0); }, 0); };\n  const div = function (a, b) { return b ? a / b : null; };\n  const F = model.campaignFacts;\n  const paid = F.filter(function (f) { return f.channel !== 'Organic'; });\n  const kpis = {\n    spend: round2(sum(F, 'spend')), impressions: sum(F, 'impressions'), clicks: sum(F, 'clicks'),\n    leads: sum(F, 'leads'), paidLeads: sum(paid, 'leads'), booked: sum(F, 'booked'), revenue: sum(F, 'revenue'),\n  };\n  kpis.cpl = round2(div(kpis.spend, kpis.paidLeads) || 0);\n  kpis.ctr = div(kpis.clicks, kpis.impressions) || 0;\n  kpis.bookingRate = div(kpis.booked, kpis.leads) || 0;\n  kpis.roas = round2(div(sum(paid, 'revenue'), kpis.spend) || 0);\n\n  const channels = ['Meta Ads', 'Google Ads', 'Organic'].map(function (ch) {\n    const rows = F.filter(function (f) { return f.channel === ch; });\n    const spend = round2(sum(rows, 'spend'));\n    const leads = sum(rows, 'leads');\n    const platformLeads = sum(rows, 'platformLeads');\n    const revenue = sum(rows, 'revenue');\n    return {\n      channel: ch, spend, leads, platformLeads, booked: sum(rows, 'booked'), revenue,\n      cpl: spend ? round2(div(spend, leads) || 0) : null,\n      roas: spend ? round2(revenue / spend) : null,\n    };\n  });\n\n  const campaigns = F.filter(function (f) { return f.channel !== 'Organic'; }).map(function (f) {\n    return Object.assign({}, f, {\n      cpl: f.leads && f.spend ? round2(f.spend / f.leads) : null,\n      ctr: f.impressions ? f.clicks / f.impressions : 0,\n      bookingRate: f.leads ? f.booked / f.leads : 0,\n      roas: f.spend ? round2(f.revenue / f.spend) : null,\n    });\n  }).sort(function (a, b) { return b.spend - a.spend; });\n\n  const insights = [];\n  campaigns.forEach(function (c) {\n    const ch = channels.find(function (x) { return x.channel === c.channel; });\n    c.flag = null;\n    if (c.campaign.indexOf('(unattributed') === 0) return;\n    if (c.cpl !== null && ch.cpl && c.cpl > ch.cpl * 1.5 && c.spend > 50) {\n      c.flag = 'high-cpl';\n      insights.push({ level: 'warning', title: 'High cost per lead', text: c.campaign + ' (' + c.client + ') has a $' + c.cpl.toFixed(2) + ' cost per lead, ' + Math.round((c.cpl / ch.cpl - 1) * 100) + '% above the ' + c.channel + ' average. Review targeting or creative.' });\n    } else if (c.leads === 0 && c.spend > 40) {\n      c.flag = 'no-leads';\n      insights.push({ level: 'critical', title: 'Spend with no leads', text: c.campaign + ' spent $' + c.spend.toFixed(2) + ' with no CRM leads in 24h. Check the form, tracking and UTM tags.' });\n    } else if (c.roas !== null && c.roas >= 4) {\n      c.flag = 'top';\n    }\n  });\n  const best = campaigns.filter(function (c) { return c.roas !== null && c.leads > 0; }).sort(function (a, b) { return b.roas - a.roas; })[0];\n  if (best) insights.unshift({ level: 'good', title: 'Opportunity', text: best.campaign + ' is the top performer at ' + best.roas.toFixed(1) + 'x ROAS ($' + best.revenue.toLocaleString('en-US') + ' booked from $' + best.spend.toFixed(0) + ' spend). Consider shifting budget here.' });\n  channels.filter(function (c) { return c.spend; }).forEach(function (c) {\n    if (!c.leads) return;\n    const gap = (c.platformLeads - c.leads) / c.leads;\n    if (gap > 0.08) insights.push({ level: 'info', title: 'Tracking gap', text: c.channel + ' reports ' + c.platformLeads + ' leads but the CRM received ' + c.leads + ' (' + Math.round(gap * 100) + '% over-reported). Use CRM leads as the source of truth for cost per lead.' });\n  });\n  if (model.unattributed > 0) insights.push({ level: 'info', title: 'Missing UTMs', text: model.unattributed + ' paid leads arrived without a utm_campaign value and could not be matched to a campaign. Fix the UTM template on those ads.' });\n  const q = model.quality;\n  insights.push({ level: q.score >= 90 ? 'good' : 'warning', title: 'Data quality', text: 'Data quality score ' + q.score + '%: removed ' + q.duplicatesRemoved + ' duplicates and ' + q.testLeadsRemoved + ' test leads, fixed ' + q.fixes + ' field issues before analysis.' });\n\n  const feed = model.leads.slice().sort(function (a, b) { return b.ts - a.ts; }).slice(0, 10).map(function (l) {\n    const parts = l.name.split(' ');\n    return { name: parts[0] + ' ' + (parts[1] || '').charAt(0) + '.', campaign: l.campaign, client: l.client, channel: l.channel, ts: l.ts, booked: l.booked, value: l.value };\n  });\n\n  const timings = Object.assign({}, model.timings, { analyze: Date.now() - t0 });\n  const ex = q.bySource;\n  return {\n    version: PIPELINE_VERSION,\n    generatedAt: new Date().toISOString(),\n    windowHours: WINDOW_HOURS,\n    pipeline: [\n      { key: 'extract', label: 'Extract', detail: ex.meta_ads + ' Meta \u00b7 ' + ex.google_ads + ' Google \u00b7 ' + ex.ghl + ' GHL rows', rows: q.rawRows, ms: Math.max(0, (timings.extract.meta_ads || 0) + (timings.extract.google_ads || 0) + (timings.extract.ghl || 0)) },\n      { key: 'clean', label: 'Clean', detail: (q.duplicatesRemoved + q.testLeadsRemoved) + ' removed \u00b7 ' + q.fixes + ' fixed', rows: q.cleanRows, ms: timings.clean },\n      { key: 'transform', label: 'Transform', detail: model.counts.factRows + ' campaign facts \u00b7 ' + model.hourly.length + ' hourly buckets', rows: model.counts.factRows, ms: timings.transform },\n      { key: 'analyze', label: 'Analyze', detail: '8 KPIs \u00b7 ' + insights.length + ' insights', rows: insights.length, ms: timings.analyze },\n    ],\n    kpis,\n    channels,\n    campaigns,\n    hourly: model.hourly,\n    funnel: [\n      { stage: 'Impressions', value: kpis.impressions },\n      { stage: 'Clicks', value: kpis.clicks },\n      { stage: 'Paid leads', value: kpis.paidLeads },\n      { stage: 'Booked', value: sum(paid, 'booked') },\n    ],\n    quality: q,\n    samples: model.samples,\n    feed,\n    insights,\n  };\n}\n\nreturn [{ json: Object.assign(analyzeData($input.first().json), { source: 'n8n' }) }];\n"
      },
      "id": "f6f13011-55a4-59ab-b2ef-1e5f56e911ae",
      "name": "Analyze & Build KPIs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        320
      ],
      "notes": "KPIs, channel/campaign breakdowns, insights",
      "notesInFlow": true
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json }}",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              },
              {
                "name": "Cache-Control",
                "value": "no-store"
              }
            ]
          }
        }
      },
      "id": "a348597a-a9db-586e-a29a-b374dc99a0cd",
      "name": "Respond to Dashboard",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1520,
        320
      ]
    },
    {
      "parameters": {
        "content": "## Real-time dashboard connection\nThe dashboard polls this webhook every 5-60 s (GET).\nEach poll runs the full pipeline and returns fresh JSON.\n\n1. Activate the workflow.\n2. Copy the **Production URL** from the webhook node.\n3. Paste it into the dashboard's **Connect n8n** panel.",
        "width": 520,
        "height": 280,
        "color": 7
      },
      "id": "2a94dd8c-2842-5275-a242-9a7be76bd079",
      "name": "Note: How it connects",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -60,
        -220
      ]
    },
    {
      "parameters": {
        "content": "## Swap sample extract nodes for real APIs\n- **Meta:** HTTP Request `GET graph.facebook.com/v21.0/act_{id}/insights` (Facebook Graph API credential)\n- **Google Ads:** HTTP Request `POST googleads.googleapis.com/.../googleAds:searchStream` (OAuth2 + developer token)\n- **GHL:** HighLevel node or HTTP Request `GET services.leadconnectorhq.com/contacts/`\n\nKeep the output fields the same and the Clean/Transform/Analyze nodes work unchanged.",
        "width": 560,
        "height": 280,
        "color": 5
      },
      "id": "f2bd22c9-2e65-5b65-afdf-2f662f630862",
      "name": "Note: Going to production",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        500,
        -220
      ]
    },
    {
      "parameters": {
        "content": "**Extract** 3 sources -> **Merge** -> **Clean** (dedupe, emails, E.164 phones, dates, source labels, test leads) -> **Transform** (UTM lookup join, fact tables) -> **Analyze** (CPL, ROAS, booking rate, anomalies, insights) -> **Respond**",
        "width": 760,
        "height": 160,
        "color": 4
      },
      "id": "2bc62110-6660-5599-a3c4-621f67329ec3",
      "name": "Note: Stages",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        760,
        560
      ]
    }
  ],
  "connections": {
    "Dashboard Poll (Webhook)": {
      "main": [
        [
          {
            "node": "Extract: Meta Ads Insights",
            "type": "main",
            "index": 0
          },
          {
            "node": "Extract: Google Ads Report",
            "type": "main",
            "index": 0
          },
          {
            "node": "Extract: GHL CRM Contacts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract: Meta Ads Insights": {
      "main": [
        [
          {
            "node": "Merge Sources",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract: Google Ads Report": {
      "main": [
        [
          {
            "node": "Merge Sources",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Extract: GHL CRM Contacts": {
      "main": [
        [
          {
            "node": "Merge Sources",
            "type": "main",
            "index": 2
          }
        ]
      ]
    },
    "Merge Sources": {
      "main": [
        [
          {
            "node": "Clean Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean Data": {
      "main": [
        [
          {
            "node": "Transform Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Transform Data": {
      "main": [
        [
          {
            "node": "Analyze & Build KPIs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze & Build KPIs": {
      "main": [
        [
          {
            "node": "Respond to Dashboard",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveDataSuccessExecution": "none"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "tags": []
}
