{
  "name": "Monthly SEO report email for a client, with a clicks chart (GSC Magic)",
  "nodes": [
    {
      "id": "6964b5ca-612b-40fc-a483-ccac8eafea13",
      "name": "1st of every month at 07:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "months",
              "triggerAtDayOfMonth": 1,
              "triggerAtHour": 7
            }
          ]
        }
      }
    },
    {
      "id": "63ed40fe-fab8-4f60-a0c2-499c827c3f8c",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        308,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "87522bf4-5ad7-4822-a266-003b2ba4c371",
              "name": "agencyName",
              "value": "Your Agency",
              "type": "string"
            },
            {
              "id": "4741b06c-2724-4cfb-a5cb-41516c4dcde0",
              "name": "senderEmail",
              "value": "reports@your-agency.com",
              "type": "string"
            },
            {
              "id": "c6018049-0d8a-4962-ae8b-b0d11c55a16b",
              "name": "brandColor",
              "value": "#2563eb",
              "type": "string"
            },
            {
              "id": "92f18bf8-ea0c-4792-a0e2-5b8e473e4bc6",
              "name": "reviewMode",
              "value": true,
              "type": "boolean"
            },
            {
              "id": "0d6f3a7c-b714-44af-a659-28783e938296",
              "name": "reviewEmail",
              "value": "you@your-agency.com",
              "type": "string"
            },
            {
              "id": "96436900-b46e-421b-ae3a-664d1d6c7ef9",
              "name": "clientSite",
              "value": "example.com",
              "type": "string"
            },
            {
              "id": "c4340bff-d4e4-4d0f-adf7-64668199bee9",
              "name": "clientName",
              "value": "Example Inc.",
              "type": "string"
            },
            {
              "id": "c973802d-eb51-4e80-a525-62487c3ca691",
              "name": "clientEmail",
              "value": "client@example.com",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "ad54eedd-1e2c-4773-acfe-deb9377ea985",
      "name": "Read client and last month",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        616,
        0
      ],
      "parameters": {
        "jsCode": "const cfg = $('Settings').first().json;\nconst client = { site: String(cfg.clientSite ?? '').trim(), name: String(cfg.clientName ?? '').trim(), email: String(cfg.clientEmail ?? '').trim() };\n\nconst now = new Date();\nconst start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1));\nconst end = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0));\nconst iso = (d) => d.toISOString().slice(0, 10);\nconst monthName = start.toLocaleDateString('en-GB', { month: 'long', year: 'numeric', timeZone: 'UTC' });\nconst emailOk = (s) => String(s || '').split(',').every((x) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(x.trim()));\n\nreturn [{ json: {\n  site: client.site,\n  client: client.name || client.site || 'your client',\n  email: client.email,\n  valid: Boolean(client.site) && emailOk(client.email),\n  startDate: iso(start), endDate: iso(end), monthName,\n} }];\n"
      }
    },
    {
      "id": "f82cfc6b-b3d8-41b1-a644-6c90bd72502d",
      "name": "Client details complete?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        924,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "16363b93-f53e-405e-abff-d6b274b745b7",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "49423379-b5f1-4c82-af3f-976b3b00ff56",
      "name": "Explain the missing details",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        924,
        220
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// ---- 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';\nreturn { json: { ok: false, to: cfg.reviewEmail, subject: 'Report not sent: ' + ($json.client || 'unnamed client') + ' (' + $json.monthName + ')',\n  html: emailLayout({ accent, eyebrow: cfg.agencyName, title: 'Report not sent', subtitle: $json.monthName,\n    preheader: 'Client details are missing in Settings',\n    body: callout('<b>Client details are missing in Settings</b>, so no report was built and no GSC Magic calls were used.', 'warn')\n      + section('Check these fields', table([{ label: 'Field' }, { label: 'Current value' }], [\n        ['<b>clientSite</b>', esc($json.site || 'empty')],\n        ['<b>clientEmail</b>', esc($json.email || 'empty') + ' (one address, or several separated by commas)'],\n      ])),\n    footer: 'Sent by your n8n workflow, not to the client.' }) } };\n"
      }
    },
    {
      "id": "a63b5cc9-6802-4073-a514-1ab53b89127e",
      "name": "GSC Magic: daily clicks with chart",
      "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: 'gsc_query_analytics', arguments: { site: $json.site, dimensions: ['date'], start_date: $json.startDate, end_date: $json.endDate, limit: 31, data_state: 'final', chart: true } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "f5df26bf-4a89-4695-a159-9b12f5f1a922",
      "name": "Keep chart and totals",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "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\nconst c = $('Read client and last month').item.json;\nconst res = unwrap($json);\nif (!res.ok) return { json: { ...c, error: res.error } };\nconst rows = res.data.rows || [];\nconst impressions = rows.reduce((s, r) => s + r.impressions, 0);\nconst position = impressions ? rows.reduce((s, r) => s + r.position * r.impressions, 0) / impressions : null;\nconst out = { json: { ...c, days: rows.length, daily: rows.map((r) => [r.date, r.clicks]), avgPosition: position === null ? null : Math.round(position * 10) / 10 } };\nif (res.image) out.binary = { chart: { data: res.image.data, mimeType: res.image.mimeType || 'image/png', fileName: 'clicks-' + c.startDate.slice(0, 7) + '.png', fileExtension: 'png' } };\nreturn out;\n"
      }
    },
    {
      "id": "a59a1e56-78cd-47ab-ade8-4cb67a820b16",
      "name": "GSC Magic: top movers",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1848,
        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: 'report_traffic_drops', arguments: { site: $('Read client and last month').item.json.site, start_date: $('Read client and last month').item.json.startDate, end_date: $('Read client and last month').item.json.endDate, dimension: 'page', limit: 5 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "8e16ce07-1cd9-461f-a60e-db5eec083ffe",
      "name": "GSC Magic: opportunities",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2156,
        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: 'report_quick_wins', arguments: { site: $('Read client and last month').item.json.site, start_date: $('Read client and last month').item.json.startDate, end_date: $('Read client and last month').item.json.endDate, min_impressions: 50, limit: 3 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "ba20c359-7029-43c1-a883-1f9978806134",
      "name": "Write the report email",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2464,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "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 base = $('Keep chart and totals').item;\nconst c = base.json;\nconst moversRes = unwrap($('GSC Magic: top movers').item.json);\nconst winsRes = unwrap($json);\nconst to = cfg.reviewMode ? cfg.reviewEmail : c.email;\nconst day = (s) => new Date(s + 'T00:00:00Z').toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' });\n\nconst problem = c.error ? c.error : !moversRes.ok ? moversRes.error : null;\nif (problem) {\n  return { json: { ok: false, to: cfg.reviewEmail, subject: 'Report not sent: ' + c.client + ' (' + c.monthName + ')',\n    html: emailLayout({ accent, eyebrow: cfg.agencyName, title: 'Report not sent', subtitle: c.client + ' (' + c.site + '), ' + c.monthName,\n      preheader: 'The ' + c.monthName + ' report for ' + c.client + ' was not built',\n      body: callout('<b>The ' + esc(c.monthName) + ' report for ' + esc(c.client) + ' was not built.</b><br>' + esc(problem), 'bad')\n        + section('What to do', numbered(['Fix the cause above (token, plan limit or Search Console access).', 'Run the workflow again with <b>Execute workflow</b>.'])),\n      footer: 'Sent by your n8n workflow, not to the client.' }) } };\n}\n\nconst m = moversRes.data;\nconst now = m.totals_current, prev = m.totals_previous;\n\n// Daily clicks drawn with table cells, so it shows without images.\nconst daily = c.daily || [];\nconst max = Math.max(1, ...daily.map((d) => d[1]));\nconst chart = daily.length < 2 ? '' : '<div style=\"border:1px solid ' + K.line + ';border-radius:10px;padding:14px 14px 8px;margin:18px 0 0;\">'\n  + '<div style=\"font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:' + K.muted + ';font-weight:700;margin:0 0 10px;\">Clicks per day</div>'\n  + '<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\"><tr>'\n  + daily.map((d) => { const h = Math.max(2, Math.round((d[1] / max) * 90)); return '<td valign=\"bottom\" style=\"padding:0 1px;height:92px;\"><div title=\"' + esc(d[0] + ': ' + d[1]) + '\" style=\"height:' + h + 'px;background:' + accent + ';border-radius:2px 2px 0 0;font-size:0;line-height:0;\">&nbsp;</div></td>'; }).join('')\n  + '</tr></table>'\n  + '<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\"><tr>'\n  + '<td style=\"font-size:11px;color:' + K.faint + ';padding-top:4px;\">' + esc(day(daily[0][0])) + '</td>'\n  + '<td align=\"right\" style=\"font-size:11px;color:' + K.faint + ';padding-top:4px;\">peak ' + fmt(max) + ' clicks - ' + esc(day(daily[daily.length - 1][0])) + '</td></tr></table></div>';\n\nconst pageRows = (rows, sign) => rows.filter((r) => sign * r.clicks_delta > 0).map((r) => [\n  link(r.key, short(urlPath(r.key), 46), accent),\n  '<span style=\"color:' + K.muted + ';\">' + fmt(r.clicks_before) + ' to ' + fmt(r.clicks_after) + '</span>',\n  pill((r.clicks_delta > 0 ? '+' : '') + r.clicks_delta, sign > 0 ? 'good' : 'bad'),\n]);\nconst gained = pageRows(m.gainers || [], 1);\nconst lost = pageRows(m.losers || [], -1);\nconst cols = [{ label: 'Page' }, { label: 'Clicks', align: 'right' }, { label: 'Change', align: 'right' }];\nconst opps = winsRes.ok ? winsRes.data.rows || [] : [];\n\nconst headline = !prev.clicks ? 'Your first month with data in this report.'\n  : now.clicks >= prev.clicks ? 'Clicks from Google grew ' + Math.round(((now.clicks - prev.clicks) / prev.clicks) * 100) + '% compared with the period before.'\n  : 'Clicks from Google fell ' + Math.round(((prev.clicks - now.clicks) / prev.clicks) * 100) + '% compared with the period before. The pages below show where.';\n\nconst html = emailLayout({\n  accent, eyebrow: cfg.agencyName, title: c.client + ': ' + c.monthName, subtitle: 'Google Search report for ' + c.site,\n  preheader: fmt(now.clicks) + ' clicks in ' + c.monthName + '. ' + headline,\n  body: '<div style=\"font-size:15px;margin:0 0 14px;\">' + esc(headline) + '</div>'\n    + kpis([\n      { label: 'Clicks', value: fmt(now.clicks), badge: change(now.clicks, prev.clicks) },\n      { label: 'Impressions', value: fmt(now.impressions), badge: change(now.impressions, prev.impressions) },\n      { label: 'CTR', value: (now.ctr * 100).toFixed(1) + '%', badge: change(now.ctr, prev.ctr) },\n      { label: 'Avg position', value: c.avgPosition ?? '-', badge: pill('lower is better', 'neutral') },\n    ])\n    + chart\n    + (gained.length ? section('Pages that gained', table(cols, gained)) : '')\n    + (lost.length ? section('Pages that lost', table(cols, lost)) : '')\n    + (opps.length ? section('Opportunities for next month', table(\n      [{ label: 'Query' }, { label: 'Page' }, { label: 'Position', align: 'right' }, { label: 'Gain', align: 'right' }],\n      opps.map((r) => [esc(r.query), link(r.page, short(urlPath(r.page), 30), accent), String(r.position), pill('+' + r.potential_extra_clicks, 'good')])),\n      'Queries close to page one. Gain = extra clicks a month at position 3.') : '')\n    + callout('Questions about these numbers? Just reply to this email.', 'info'),\n  footer: esc(cfg.agencyName) + '. Changes compare ' + (m.current ? esc(day(m.current.startDate) + ' to ' + day(m.current.endDate)) : 'the month')\n    + ' with ' + (m.previous ? esc(day(m.previous.startDate) + ' to ' + day(m.previous.endDate)) : 'the period before') + '. Data: Google Search Console. The daily chart is also attached as an image.',\n});\n\nreturn {\n  json: { ok: true, to, subject: (cfg.reviewMode ? '[Review] ' : '') + c.client + ': SEO report for ' + c.monthName, html },\n  binary: base.binary,\n};\n"
      }
    },
    {
      "id": "7b2c22a5-8a58-45a8-af5b-6eef0dd0531b",
      "name": "Report built?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2772,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "6963fc5b-00aa-4434-ac57-293f152c5e0f",
              "leftValue": "={{ $json.ok }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "fa01f235-8098-4ff2-acb4-b13045a87a62",
      "name": "Send the report",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        3080,
        -100
      ],
      "parameters": {
        "fromEmail": "={{ $('Settings').first().json.senderEmail }}",
        "toEmail": "={{ $json.to }}",
        "subject": "={{ $json.subject }}",
        "emailFormat": "html",
        "html": "={{ $json.html }}",
        "options": {
          "appendAttribution": false,
          "attachments": "chart"
        }
      }
    },
    {
      "id": "9c72d001-e6f0-43e8-aa61-d8749230db09",
      "name": "Tell me it failed",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        3080,
        160
      ],
      "parameters": {
        "fromEmail": "={{ $('Settings').first().json.senderEmail }}",
        "toEmail": "={{ $json.to }}",
        "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,
        -412
      ],
      "parameters": {
        "content": "## Step 1: Configure\n- **agencyName**: shown in the email header and signature.\n- **senderEmail**: the From address (must be allowed by your SMTP server).\n- **brandColor**: your accent color as a hex code, e.g. `#2563eb`. Used for the top bar, links and the chart.\n- **reviewMode**: `true` sends the report to **reviewEmail**; `false` sends it to the client.\n- **clientSite**: the client's Search Console property or domain.\n- **clientName**: the name used in the email.\n- **clientEmail**: one address, or several separated by commas.",
        "width": 488,
        "height": 822,
        "color": 7
      }
    },
    {
      "id": "41f790c9-db12-4db4-af2b-de6299759eb6",
      "name": "Step 2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        576,
        -412
      ],
      "parameters": {
        "content": "## Step 2: Check the client\nReads the client from Settings and works out last month's dates. Missing details get a \"not sent\" email and cost no calls.",
        "width": 488,
        "height": 822,
        "color": 7
      }
    },
    {
      "id": "9c585151-0129-4dc1-ac1e-c14e0e86d8cc",
      "name": "Step 3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1192,
        -412
      ],
      "parameters": {
        "content": "## Step 3: Pull the month\nThree calls: daily clicks with a chart, top movers against the previous period, opportunities.",
        "width": 1104,
        "height": 822,
        "color": 7
      }
    },
    {
      "id": "4f01150f-1741-4e8a-a32b-c094c1574747",
      "name": "Step 4",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2424,
        -412
      ],
      "parameters": {
        "content": "## Step 4: Write and send\nBuilds the email with the chart attached. Review mode sends it to you; a failed report gets a \"not sent\" email.",
        "width": 796,
        "height": 822,
        "color": 7
      }
    },
    {
      "id": "9a62af03-61c1-457d-a05e-8127b257f06d",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -740,
        -412
      ],
      "parameters": {
        "content": "## Monthly client SEO report by email\nOn the 1st of every month this workflow writes your client an email about the month that just ended: clicks, impressions, CTR and average position against the previous period, the pages that gained and lost the most, three opportunities for next month, and a PNG chart of daily clicks drawn by GSC Magic.\n\n**Who it is for:** agencies and freelancers who send clients a monthly update and want it to go out on time without building it in a dashboard tool.\n\n**How it works**\n1. Reads the client from **Settings** and works out last month's dates.\n2. Three reports: daily clicks with a chart, top movers vs the previous period, quick wins for next month.\n3. Builds a plain, mobile-friendly HTML email with your agency name.\n4. **Review mode** (on by default) sends every report to you instead of the client. Turn it off when you trust the output.\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**, add an SMTP credential to both email nodes (or swap in Gmail / Outlook).\n5. Execute once with review mode on, read the emails, then 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, 1 site). For more clients, duplicate the workflow; each copy needs the client's site in your GSC Magic plan.\n\n### Errors and limits\n- Missing client details (no GSC Magic calls are spent), a wrong property or a GSC Magic error: you get a \"Report not sent\" email with the reason instead of the report.\n- Changes compare the month with the same number of days right before it.\n- The chart is a PNG attachment (most email clients block inline images from unknown senders).\n- Search Console finalizes data 2 to 3 days late, so the last days of the month can still grow slightly after the 1st.",
        "width": 640,
        "height": 909
      }
    }
  ],
  "connections": {
    "1st of every month at 07:00": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Read client and last month",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read client and last month": {
      "main": [
        [
          {
            "node": "Client details complete?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Client details complete?": {
      "main": [
        [
          {
            "node": "GSC Magic: daily clicks with chart",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Explain the missing details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Explain the missing details": {
      "main": [
        [
          {
            "node": "Tell me it failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: daily clicks with chart": {
      "main": [
        [
          {
            "node": "Keep chart and totals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Keep chart and totals": {
      "main": [
        [
          {
            "node": "GSC Magic: top movers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: top movers": {
      "main": [
        [
          {
            "node": "GSC Magic: opportunities",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: opportunities": {
      "main": [
        [
          {
            "node": "Write the report email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the report email": {
      "main": [
        [
          {
            "node": "Report built?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Report built?": {
      "main": [
        [
          {
            "node": "Send the report",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Tell me it failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "active": false
}
