{
  "name": "Weekly email report of visits from ChatGPT, Perplexity, Gemini and other AI assistants (GA4 + GSC Magic)",
  "nodes": [
    {
      "id": "9deaee89-e723-43a2-a4ba-d82b41bb9cbd",
      "name": "Every Monday at 08:30",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8,
              "triggerAtMinute": 30
            }
          ]
        }
      }
    },
    {
      "id": "dac28ba1-6c60-4c7b-aad5-9d127401d0f1",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        308,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b459d664-24f3-4822-a150-0cd2cf70e50b",
              "name": "ga4PropertyId",
              "value": "123456789",
              "type": "string"
            },
            {
              "id": "5f0a732b-164c-4e89-ac74-462c4f219403",
              "name": "siteName",
              "value": "example.com",
              "type": "string"
            },
            {
              "id": "deda5fb3-cb79-43b8-a5eb-cfffc5bb7af7",
              "name": "recipientEmail",
              "value": "you@example.com",
              "type": "string"
            },
            {
              "id": "4741b06c-2724-4cfb-a5cb-41516c4dcde0",
              "name": "senderEmail",
              "value": "reports@example.com",
              "type": "string"
            },
            {
              "id": "6e545397-c4ee-49b3-af6d-aec9a99f87fe",
              "name": "senderName",
              "value": "Your Agency",
              "type": "string"
            },
            {
              "id": "c6018049-0d8a-4962-ae8b-b0d11c55a16b",
              "name": "brandColor",
              "value": "#2563eb",
              "type": "string"
            },
            {
              "id": "8367508e-666a-449a-a235-4f3d29732735",
              "name": "aiSourcesRegex",
              "value": "chatgpt\\.com|chat\\.openai\\.com|perplexity\\.ai|perplexity|gemini\\.google\\.com|bard\\.google\\.com|claude\\.ai|copilot\\.microsoft\\.com|copilot\\.com|you\\.com|poe\\.com|phind\\.com|deepseek\\.com|chat\\.deepseek\\.com|grok\\.com|meta\\.ai|chat\\.mistral\\.ai|edgeservices\\.bing\\.com",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "00fb85b3-6dff-4561-ac9a-589f3ceffd28",
      "name": "GSC Magic: AI sessions this week",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        616,
        0
      ],
      "onError": "continueRegularOutput",
      "parameters": {
        "method": "POST",
        "url": "https://mcp.gscmagic.com/mcp",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'ga_run_report', arguments: { property: $('Settings').first().json.ga4PropertyId, dimensions: ['sessionSource'], metrics: ['sessions', 'engagedSessions', 'keyEvents'], start_date: '7daysAgo', end_date: 'yesterday', dimension_filters: [{ field: 'sessionSource', match_type: 'FULL_REGEXP', value: $('Settings').first().json.aiSourcesRegex }], order_by: [{ field: 'sessions', desc: true }], limit: 50 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "d1190e39-6c12-4c59-a674-e98ccc4593ca",
      "name": "GSC Magic: AI sessions week before",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        924,
        0
      ],
      "onError": "continueRegularOutput",
      "parameters": {
        "method": "POST",
        "url": "https://mcp.gscmagic.com/mcp",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'ga_run_report', arguments: { property: $('Settings').first().json.ga4PropertyId, dimensions: ['sessionSource'], metrics: ['sessions', 'engagedSessions', 'keyEvents'], start_date: '14daysAgo', end_date: '8daysAgo', dimension_filters: [{ field: 'sessionSource', match_type: 'FULL_REGEXP', value: $('Settings').first().json.aiSourcesRegex }], order_by: [{ field: 'sessions', desc: true }], limit: 50 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "cb768015-9589-4880-a3dd-e75d9c981232",
      "name": "GSC Magic: AI landing pages",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1232,
        0
      ],
      "onError": "continueRegularOutput",
      "parameters": {
        "method": "POST",
        "url": "https://mcp.gscmagic.com/mcp",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'ga_run_report', arguments: { property: $('Settings').first().json.ga4PropertyId, dimensions: ['sessionSource', 'landingPage'], metrics: ['sessions', 'engagedSessions', 'keyEvents'], start_date: '7daysAgo', end_date: 'yesterday', dimension_filters: [{ field: 'sessionSource', match_type: 'FULL_REGEXP', value: $('Settings').first().json.aiSourcesRegex }], order_by: [{ field: 'sessions', desc: true }], limit: 100 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "3f1a7393-46ea-4e96-a3be-49f8c1da1782",
      "name": "Write the email",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        0
      ],
      "parameters": {
        "jsCode": "// Turns a GSC Magic response (MCP JSON-RPC) into { ok, data, error, image }.\nfunction unwrap(res) {\n  const result = res && res.result;\n  if (result && Array.isArray(result.content)) {\n    const text = result.content.filter((b) => b.type === 'text').map((b) => b.text).join('\\n');\n    if (result.isError) return { ok: false, error: text || 'GSC Magic reported an error' };\n    let data;\n    try { data = JSON.parse(text); } catch (e) { data = { text }; }\n    const image = result.content.find((b) => b.type === 'image' && b.data);\n    return { ok: true, data, image };\n  }\n  const err = res && res.error;\n  const message = typeof err === 'string' ? err : (err && (err.message || err.description)) || 'No response from GSC Magic';\n  if (/401|unauthori[sz]ed|Authorization failed/i.test(message)) {\n    return { ok: false, error: 'GSC Magic rejected the access token (wrong, expired or revoked). Create a new one in the GSC Magic dashboard: Connect > Access tokens.' };\n  }\n  return { ok: false, error: String(message) };\n}\n\n// ---- email kit: layout and components (inline styles, works in Gmail, Outlook, Apple Mail) ----\nconst K = { ink: '#111827', muted: '#6b7280', faint: '#9ca3af', line: '#e5e7eb', bg: '#f3f4f6', soft: '#f9fafb',\n  good: '#166534', goodBg: '#dcfce7', bad: '#b91c1c', badBg: '#fee2e2', warn: '#92400e', warnBg: '#fef3c7', info: '#1e40af', infoBg: '#dbeafe' };\nconst FONT = \"-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif\";\nconst esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\nconst fmt = (n) => (n === null || n === undefined || Number.isNaN(Number(n)) ? '-' : Number(n).toLocaleString('en-US'));\nconst urlPath = (u) => String(u).replace(/^https?:\\/\\/[^/]+/i, '') || '/';\nconst short = (s, n) => (String(s).length > n ? String(s).slice(0, n - 1) + '...' : String(s));\nfunction pill(text, tone) {\n  const c = { good: [K.good, K.goodBg], bad: [K.bad, K.badBg], warn: [K.warn, K.warnBg], info: [K.info, K.infoBg] }[tone] || [K.muted, K.bg];\n  return '<span style=\"display:inline-block;padding:2px 8px;border-radius:999px;background:' + c[1] + ';color:' + c[0] + ';font-size:12px;font-weight:700;line-height:18px;white-space:nowrap;\">' + esc(text) + '</span>';\n}\nfunction change(now, before, goodWhenUp = true) {\n  if (!before) return now ? pill('new', 'info') : '';\n  const d = Math.round(((now - before) / before) * 100);\n  if (d === 0) return pill('0%', 'neutral');\n  return pill((d > 0 ? '+' : '') + d + '%', (d > 0) === goodWhenUp ? 'good' : 'bad');\n}\nfunction link(url, text, accent) {\n  return '<a href=\"' + esc(url) + '\" style=\"color:' + accent + ';text-decoration:none;font-weight:600;\">' + esc(text) + '</a>';\n}\nfunction kpis(items) {\n  const w = Math.floor(100 / items.length);\n  return '<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:separate;border-spacing:8px 0;margin:4px -8px 0;\"><tr>'\n    + items.map((k) => '<td width=\"' + w + '%\" valign=\"top\" style=\"background:' + K.soft + ';border:1px solid ' + K.line + ';border-radius:10px;padding:14px 12px;\">'\n      + '<div style=\"font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:' + K.muted + ';font-weight:700;\">' + esc(k.label) + '</div>'\n      + '<div style=\"font-size:22px;font-weight:800;margin:4px 0 6px;color:' + K.ink + ';\">' + esc(k.value) + '</div>'\n      + '<div style=\"min-height:20px;\">' + (k.badge || '') + '</div></td>').join('')\n    + '</tr></table>';\n}\nfunction section(title, body, note) {\n  return '<div style=\"margin:30px 0 0;\"><div style=\"font-size:17px;font-weight:800;color:' + K.ink + ';margin:0 0 4px;\">' + esc(title) + '</div>'\n    + (note ? '<div style=\"font-size:13px;color:' + K.muted + ';margin:0 0 12px;\">' + note + '</div>' : '<div style=\"height:8px\"></div>') + body + '</div>';\n}\nfunction table(cols, rows) {\n  const th = cols.map((c) => '<td align=\"' + (c.align || 'left') + '\" style=\"padding:8px 10px;font-size:11px;letter-spacing:.05em;text-transform:uppercase;color:' + K.muted + ';font-weight:700;border-bottom:1px solid ' + K.line + ';\">' + esc(c.label) + '</td>').join('');\n  const tr = rows.map((r) => '<tr>' + r.map((cell, i) => '<td align=\"' + (cols[i].align || 'left') + '\" valign=\"top\" style=\"padding:10px;font-size:14px;border-bottom:1px solid ' + K.line + ';\">' + cell + '</td>').join('') + '</tr>').join('');\n  return '<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\"><tr>' + th + '</tr>' + tr + '</table>';\n}\nfunction bar(share, accent) {\n  const p = Math.max(2, Math.min(100, Math.round(share * 100)));\n  return '<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\"><tr>'\n    + '<td width=\"' + p + '%\" style=\"background:' + accent + ';height:6px;line-height:6px;font-size:0;border-radius:3px;\">&nbsp;</td>'\n    + (p < 100 ? '<td style=\"background:' + K.line + ';height:6px;line-height:6px;font-size:0;border-radius:3px;\">&nbsp;</td>' : '') + '</tr></table>';\n}\nfunction callout(html, tone) {\n  const c = { good: [K.good, K.goodBg], bad: [K.bad, K.badBg], warn: [K.warn, K.warnBg] }[tone] || [K.info, K.infoBg];\n  return '<div style=\"background:' + c[1] + ';border-left:4px solid ' + c[0] + ';border-radius:8px;padding:14px 16px;margin:18px 0 0;font-size:14px;color:' + K.ink + ';\">' + html + '</div>';\n}\nfunction bullets(items) {\n  return '<table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">' + items.map((t) => '<tr><td valign=\"top\" style=\"padding:3px 8px 3px 0;color:' + K.muted + ';\">&#9679;</td><td style=\"padding:3px 0;font-size:14px;\">' + t + '</td></tr>').join('') + '</table>';\n}\nfunction numbered(items) {\n  return '<table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">' + items.map((t, i) => '<tr><td valign=\"top\" style=\"padding:4px 10px 4px 0;\"><span style=\"display:inline-block;width:22px;height:22px;line-height:22px;border-radius:11px;background:' + K.bg + ';color:' + K.ink + ';font-size:12px;font-weight:800;text-align:center;\">' + (i + 1) + '</span></td><td style=\"padding:5px 0;font-size:14px;\">' + t + '</td></tr>').join('') + '</table>';\n}\nfunction emailLayout(o) {\n  const a = o.accent || '#2563eb';\n  return '<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><meta name=\"color-scheme\" content=\"light\"></head>'\n    + '<body style=\"margin:0;padding:0;background:' + K.bg + ';\">'\n    + '<div style=\"display:none;max-height:0;overflow:hidden;opacity:0;\">' + esc(o.preheader || '') + '</div>'\n    + '<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:' + K.bg + ';\"><tr><td align=\"center\" style=\"padding:28px 12px;\">'\n    + '<table role=\"presentation\" width=\"600\" cellpadding=\"0\" cellspacing=\"0\" style=\"width:100%;max-width:600px;background:#ffffff;border:1px solid ' + K.line + ';border-radius:14px;font-family:' + FONT + ';color:' + K.ink + ';\">'\n    + '<tr><td style=\"background:' + a + ';height:6px;line-height:6px;font-size:0;border-radius:14px 14px 0 0;\">&nbsp;</td></tr>'\n    + '<tr><td style=\"padding:26px 28px 6px;\">'\n    + '<div style=\"font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:' + a + ';font-weight:800;\">' + esc(o.eyebrow || '') + '</div>'\n    + '<div style=\"font-size:24px;line-height:1.25;font-weight:800;margin:6px 0 4px;\">' + esc(o.title) + '</div>'\n    + (o.subtitle ? '<div style=\"font-size:14px;color:' + K.muted + ';\">' + esc(o.subtitle) + '</div>' : '')\n    + '</td></tr>'\n    + '<tr><td style=\"padding:10px 28px 28px;font-size:15px;line-height:1.55;\">' + o.body + '</td></tr>'\n    + '<tr><td style=\"padding:16px 28px 20px;border-top:1px solid ' + K.line + ';font-size:12px;line-height:1.5;color:' + K.muted + ';\">' + (o.footer || '') + '</td></tr>'\n    + '</table></td></tr></table></body></html>';\n}\n// ---- end of email kit ----\n\nconst cfg = $('Settings').first().json;\nconst accent = /^#[0-9a-f]{6}$/i.test(String(cfg.brandColor)) ? cfg.brandColor : '#2563eb';\nconst now = unwrap($('GSC Magic: AI sessions this week').first().json);\nconst prev = unwrap($('GSC Magic: AI sessions week before').first().json);\nconst land = unwrap($('GSC Magic: AI landing pages').first().json);\nconst week = (from, to) => { const d = (n) => { const x = new Date(Date.now() - n * 86400000); return x.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }); }; return d(from) + ' to ' + d(to); };\nconst period = week(7, 1) + ' vs ' + week(14, 8);\nconst footer = esc(cfg.senderName) + '. Data: Google Analytics 4, sessions whose source is an AI assistant, through GSC Magic. Visits from assistant apps that pass no referrer show up as direct traffic, so the real number is higher.';\n\nconst failed = [now, prev, land].find((r) => !r.ok);\nif (failed) {\n  return [{ json: { subject: 'AI assistant traffic report failed for ' + cfg.siteName, html: emailLayout({\n    accent, eyebrow: cfg.senderName, title: 'Report failed', subtitle: 'AI assistant traffic for ' + cfg.siteName,\n    preheader: 'The GA4 report for AI assistant traffic could not be built',\n    body: callout('<b>The GA4 report failed.</b><br>' + esc(failed.error), 'bad')\n      + section('Usual causes', bullets(['<b>ga4PropertyId</b> in Settings is wrong (it is a number like 123456789).', 'The Google account behind GSC Magic has no access to this GA4 property, or Analytics access was not granted.', 'The GSC Magic token was revoked or the daily call limit was reached.'])),\n    footer: 'Sent by your n8n workflow.' }) } }];\n}\n\nconst ASSISTANTS = [\n  ['ChatGPT', /chatgpt|openai/], ['Perplexity', /perplexity/], ['Gemini', /gemini|bard/], ['Claude', /claude/],\n  ['Copilot', /copilot|edgeservices\\.bing/], ['DeepSeek', /deepseek/], ['Grok', /grok/], ['Meta AI', /meta\\.ai/],\n  ['Mistral', /mistral/], ['You.com', /you\\.com/], ['Poe', /poe\\.com/], ['Phind', /phind/],\n];\nconst nameOf = (source) => (ASSISTANTS.find(([, re]) => re.test(source)) || [source])[0];\nconst group = (rows) => {\n  const out = {};\n  for (const r of rows || []) {\n    const k = nameOf(String(r.sessionSource));\n    out[k] = out[k] || { sessions: 0, engaged: 0, keyEvents: 0 };\n    out[k].sessions += Number(r.sessions) || 0;\n    out[k].engaged += Number(r.engagedSessions) || 0;\n    out[k].keyEvents += Number(r.keyEvents) || 0;\n  }\n  return out;\n};\nconst cur = group(now.data.rows);\nconst old = group(prev.data.rows);\nconst sum = (g, k) => Object.values(g).reduce((s, x) => s + x[k], 0);\nconst tNow = sum(cur, 'sessions'), tOld = sum(old, 'sessions');\nconst engagedNow = sum(cur, 'engaged'), engagedOld = sum(old, 'engaged');\nconst keyNow = sum(cur, 'keyEvents'), keyOld = sum(old, 'keyEvents');\nconst rate = (e, s) => (s ? Math.round((e / s) * 100) : 0);\n\nif (!tNow && !tOld) {\n  return [{ json: { subject: 'AI assistant traffic: no visits this week (' + cfg.siteName + ')', html: emailLayout({\n    accent, eyebrow: cfg.senderName, title: 'AI assistant traffic', subtitle: cfg.siteName + ' - ' + period,\n    preheader: 'No sessions from AI assistants in the last two weeks',\n    body: callout('No sessions from ChatGPT, Perplexity, Gemini, Claude, Copilot or other assistants in the last two weeks.', 'info')\n      + section('Ways to get cited by AI assistants', bullets(['Answer the main question of each page in its first paragraph.', 'Make sure your pages are indexed in Bing as well as Google: Copilot answers from Bing\\'s index.', 'Add clear facts, numbers and dates that an assistant can quote.'])),\n    footer }) } }];\n}\n\nconst names = [...new Set([...Object.keys(cur), ...Object.keys(old)])].sort((a, b) => ((cur[b] || {}).sessions || 0) - ((cur[a] || {}).sessions || 0));\nconst assistantRows = names.map((n) => {\n  const a = cur[n] || { sessions: 0, engaged: 0, keyEvents: 0 };\n  const b = old[n] || { sessions: 0 };\n  const share = tNow ? a.sessions / tNow : 0;\n  return [\n    '<b>' + esc(n) + '</b><div style=\"margin-top:6px;\">' + bar(share, accent) + '</div>',\n    fmt(a.sessions) + '<div style=\"font-size:12px;color:' + K.muted + ';\">' + Math.round(share * 100) + '% of AI</div>',\n    change(a.sessions, b.sessions),\n    rate(a.engaged, a.sessions) + '%',\n    fmt(a.keyEvents),\n  ];\n});\n\nconst byPage = {};\nfor (const r of land.data.rows || []) {\n  const p = String(r.landingPage || '(not set)');\n  byPage[p] = byPage[p] || { sessions: 0, from: {} };\n  byPage[p].sessions += Number(r.sessions) || 0;\n  const who = nameOf(String(r.sessionSource));\n  byPage[p].from[who] = (byPage[p].from[who] || 0) + (Number(r.sessions) || 0);\n}\nconst top = Object.entries(byPage).sort((a, b) => b[1].sessions - a[1].sessions).slice(0, 8);\nconst pageRows = top.map(([p, v]) => [\n  esc(short(p, 48)),\n  Object.entries(v.from).sort((a, b) => b[1] - a[1]).map(([w]) => pill(w, 'neutral')).join(' '),\n  fmt(v.sessions),\n]);\n\nconst leader = names[0];\nconst headline = tOld\n  ? 'AI assistants sent ' + fmt(tNow) + ' sessions this week, ' + (tNow >= tOld ? 'up ' : 'down ') + Math.abs(Math.round(((tNow - tOld) / tOld) * 100)) + '% on the week before. ' + leader + ' sent the most.'\n  : 'AI assistants sent ' + fmt(tNow) + ' sessions this week, the first in this two-week window. ' + leader + ' sent the most.';\n\nconst html = emailLayout({\n  accent, eyebrow: cfg.senderName, title: 'AI assistant traffic', subtitle: cfg.siteName + ' - ' + period,\n  preheader: headline,\n  body: '<div style=\"font-size:15px;margin:0 0 14px;\">' + esc(headline) + '</div>'\n    + kpis([\n      { label: 'AI sessions', value: fmt(tNow), badge: change(tNow, tOld) },\n      { label: 'Engaged', value: rate(engagedNow, tNow) + '%', badge: tOld ? (() => { const pts = rate(engagedNow, tNow) - rate(engagedOld, tOld); return pill((pts > 0 ? '+' : '') + pts + ' pts', pts > 0 ? 'good' : pts < 0 ? 'bad' : 'neutral'); })() : '' },\n      { label: 'Key events', value: fmt(keyNow), badge: change(keyNow, keyOld) },\n      { label: 'Assistants', value: fmt(Object.keys(cur).length), badge: pill('sending visits', 'info') },\n    ])\n    + section('By assistant', table([{ label: 'Assistant' }, { label: 'Sessions', align: 'right' }, { label: 'vs last week', align: 'right' }, { label: 'Engaged', align: 'right' }, { label: 'Key events', align: 'right' }], assistantRows),\n      'Engaged = share of sessions GA4 counts as engaged (10+ seconds, a key event or 2+ page views).')\n    + (pageRows.length ? section('Where they land', table([{ label: 'Landing page' }, { label: 'From' }, { label: 'Sessions', align: 'right' }], pageRows),\n      'These pages are being cited or linked by AI assistants. Keep them accurate and up to date.') : ''),\n  footer,\n});\n\nreturn [{ json: { subject: 'AI assistant traffic: ' + fmt(tNow) + ' sessions this week (' + cfg.siteName + ')', html } }];\n"
      }
    },
    {
      "id": "54bc91ca-92c4-46d8-a45f-3fe754fee12d",
      "name": "Send the report",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1848,
        0
      ],
      "parameters": {
        "fromEmail": "={{ $('Settings').first().json.senderEmail }}",
        "toEmail": "={{ $('Settings').first().json.recipientEmail }}",
        "subject": "={{ $json.subject }}",
        "emailFormat": "html",
        "html": "={{ $json.html }}",
        "options": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "7edbd534-615a-42a5-a0ba-c9ef02e5a7e2",
      "name": "Step 1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -333
      ],
      "parameters": {
        "content": "## Step 1: Configure\n- **ga4PropertyId**: the numeric GA4 property id.\n- **siteName**: shown in the email title.\n- **recipientEmail**: one address, or several separated by commas.\n- **senderEmail**: the From address (must be allowed by your SMTP server).\n- **senderName**: your agency or company name, shown at the top of the email.\n- **brandColor**: accent color as a hex code, e.g. `#2563eb`.\n- **aiSourcesRegex**: GA4 `sessionSource` values that count as AI assistants (full match). Add a source with `|newsource\\.com`.",
        "width": 488,
        "height": 523,
        "color": 7
      }
    },
    {
      "id": "d1e08a7b-6cd0-454c-ae8f-c217c16b85f8",
      "name": "Step 2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        576,
        -333
      ],
      "parameters": {
        "content": "## Step 2: Pull AI assistant sessions from GA4\nThree GA4 reports through GSC Magic: sessions from AI assistants this week, the week before, and their landing pages.",
        "width": 796,
        "height": 523,
        "color": 7
      }
    },
    {
      "id": "bb0e8f86-1a6f-466a-aab6-d463b0b2e719",
      "name": "Step 3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1500,
        -333
      ],
      "parameters": {
        "content": "## Step 3: Email the report\nGroups sources into assistants, compares the weeks and emails sessions, engagement, key events and where the visits land.",
        "width": 488,
        "height": 523,
        "color": 7
      }
    },
    {
      "id": "04d90a11-df9d-40f5-ac57-91fadf4b7ee2",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -740,
        -333
      ],
      "parameters": {
        "content": "## Weekly AI assistant traffic report by email\nSearch Console does not show clicks from ChatGPT, Perplexity, Claude, Gemini or Copilot. Google Analytics 4 does, if you know which sources to look for. Every Monday this workflow pulls those sessions from GA4, compares them with the week before and emails a short report: which assistants send visitors, how engaged they are and which pages they land on.\n\n**Who it is for:** GEO / AEO agencies that send clients a weekly number for \"are AI assistants sending us traffic?\", and site owners who prefer email to Slack.\n\n**How it works**\n1. Three GA4 reports through GSC Magic: AI sessions this week, the week before, and landing pages this week.\n2. Groups sources into assistants (chatgpt.com and chat.openai.com count as ChatGPT, and so on).\n3. Emails totals, change, engagement rate, key events, a share bar per assistant and the top landing pages.\n\n**Requirements:** a GA4 property connected to the Google account behind GSC Magic (GSC Magic asks for Analytics read access when you connect Google), and an SMTP account (or swap in Gmail / Outlook).\n\n**Connect GSC Magic** (about 2 minutes)\n1. In the [GSC Magic dashboard](https://app.gscmagic.com) open **Connect > Access tokens** and create a token. Copy the `gsm_...` value (shown once).\n2. Open the first node whose name starts with **GSC Magic:**, and under **Credential for Bearer Auth** create a new credential. Paste the token into **Bearer Token**. In every other **GSC Magic:** node, select that same credential.\n3. Never paste the token into a URL, a prompt or a Code node.\n\n**Then**\n4. Fill in **Settings**: the GA4 property id (GA4 > Admin > Property details, a number like 123456789), who gets the email and who sends it.\n5. Add an SMTP credential to **Send the report**, execute once, check the email, activate.\n\nSchedule times use the workflow time zone (Workflow settings > Timezone), which defaults to the instance time zone.\n\n**Calls per run:** 3. Works on the Free plan (10 calls a day).\n\nPrefer Slack? The Slack version of this template does the same with a Slack message.\n\n### Errors and limits\n- If any of the three reports fails (wrong property id, no Analytics access, plan limit), you get one email with the reason instead of a partial report.\n- No AI visits in two weeks: you still get a short email saying so, with three ideas to get cited.\n- Weeks are GA4 relative dates (`7daysAgo` to `yesterday`) in the property's time zone.\n- Mobile apps of some assistants open links without a referrer, so the real number is higher than what GA4 can attribute.",
        "width": 640,
        "height": 1055
      }
    }
  ],
  "connections": {
    "Every Monday at 08:30": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "GSC Magic: AI sessions this week",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: AI sessions this week": {
      "main": [
        [
          {
            "node": "GSC Magic: AI sessions week before",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: AI sessions week before": {
      "main": [
        [
          {
            "node": "GSC Magic: AI landing pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: AI landing pages": {
      "main": [
        [
          {
            "node": "Write the email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the email": {
      "main": [
        [
          {
            "node": "Send the report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "active": false
}
