{
  "name": "Weekly numbers from sprkly and your sheet",
  "nodes": [
    {
      "id": "0112e638-ab77-4e3d-aeb4-39ec2b742b6e",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -688,
        -120
      ],
      "parameters": {
        "content": "## Weekly numbers from sprkly and your sheet\nEvery Monday it adds up last week: posts per platform from sprkly, against the week before, and the channel numbers you keep in a sheet. One row per channel, one Telegram summary.\n\n### You need\n- The sprkly node: Settings, Community nodes, install `n8n-nodes-sprkly` (self-hosted n8n)\n- A sprkly API key: https://sprkly.app/docs/api?utm_source=n8n&utm_medium=workflow&utm_campaign=analytics-weekly-kpi-rollup\n- A Google Sheets login and one sheet with 2 tabs:\n- Channel Results: Date (YYYY-MM-DD), Channel, Impressions, Clicks, Conversions, Cost\n- Weekly Numbers: Key, Week, Channel, Posts, Posts Week Before, Impressions, Clicks, Conversions, Cost, CTR %, Cost Per Conversion\n- A Telegram bot and your chat ID\n\n### Set it up\n1. Pick your sheet in **Read channel results** and **Save the week**.\n2. Add your sprkly key to **Get posts that went out**. Add your bot to **Send the summary** and your chat ID in **Settings**.\n3. Paste or sync your channel numbers into Channel Results, one row per channel per day. Set your time zone in Workflow settings.\n4. Failure alert: put your chat ID in **Write the failure alert** and your bot in **Send the failure alert**. Then in Workflow settings, set Error workflow to this workflow.\n\n### Test it\n- Click Test workflow with **Run now** picked.\n- Weekly Numbers gets one row per channel and one per platform. Run it again: the rows update, they are not added twice.",
        "height": 962,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "8778a42e-62ea-4dbd-98d2-6a5736b9e6c6",
      "name": "Note: read",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -48,
        -120
      ],
      "parameters": {
        "content": "## Read the week\nThe week is the 7 days before today. Post counts come from sprkly. Reach and sales come from your own sheet, so you keep one set of numbers.",
        "height": 560,
        "width": 1160,
        "color": 7
      }
    },
    {
      "id": "7785a1d8-e2e5-4446-ab09-bc7eb8361893",
      "name": "Note: save",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1128,
        -120
      ],
      "parameters": {
        "content": "## Save and send\nOne row per channel per week, matched by Key, so a second run updates the row. No number is guessed: a channel with no rows is left out.",
        "height": 760,
        "width": 760,
        "color": 7
      }
    },
    {
      "id": "83641f66-9588-40c2-bc20-6e60d62fd093",
      "name": "Every Monday",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8
            }
          ]
        }
      }
    },
    {
      "id": "00a0efd9-3544-470d-b9e0-bc21e4232082",
      "name": "Run now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        200
      ],
      "parameters": {}
    },
    {
      "id": "c1e19454-1f51-46d1-a0e6-f72d9ba330b6",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        100
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_CHAT_ID"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      }
    },
    {
      "id": "0aea8919-3987-47e0-89f7-5c801290bbf9",
      "name": "Get posts that went out",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        480,
        100
      ],
      "parameters": {
        "resource": "post",
        "operation": "getAll",
        "returnAll": true,
        "filters": {
          "status": "posted"
        },
        "simplify": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "ffcba5e7-57bd-4d79-a7db-e82d1c2ad03d",
      "name": "Read channel results",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        720,
        100
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Channel Results",
          "mode": "name"
        },
        "options": {}
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "a58b796f-5ce3-434f-9843-40628c47d54d",
      "name": "Add up the week",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const end = $now.startOf('day');\nconst start = end.minus({ days: 7 });\nconst before = start.minus({ days: 7 });\nconst week = start.toISODate() + ' to ' + end.minus({ days: 1 }).toISODate();\nconst inside = (d, a, b) => d.isValid && d >= a && d < b;\nconst channels = {};\nfor (const { json: r } of $('Read channel results').all()) {\n  const d = DateTime.fromISO(String(r.Date || '').trim());\n  if (!inside(d, start, end)) continue;\n  const k = String(r.Channel || '').trim() || 'No channel';\n  const c = (channels[k] ||= { impressions: 0, clicks: 0, conversions: 0, cost: 0 });\n  c.impressions += Number(r.Impressions) || 0; c.clicks += Number(r.Clicks) || 0;\n  c.conversions += Number(r.Conversions) || 0; c.cost += Number(r.Cost) || 0;\n}\nconst posts = $('Get posts that went out').all().map(i => i.json).filter(p => p.id && !p.deleted && p.publishedAt);\nconst countPosts = (a, b) => {\n  const m = {};\n  for (const p of posts) { if (!inside(DateTime.fromISO(p.publishedAt), a, b)) continue; for (const pl of (p.platforms && p.platforms.length ? p.platforms : ['unknown'])) m[pl] = (m[pl] || 0) + 1; }\n  return m;\n};\nconst thisWeek = countPosts(start, end), lastWeek = countPosts(before, start);\nconst rows = Object.entries(channels).map(([k, c]) => ({ json: {\n  Key: week + ' ' + k, Week: week, Channel: k, Posts: '', 'Posts Week Before': '',\n  Impressions: c.impressions, Clicks: c.clicks, Conversions: c.conversions, Cost: Number(c.cost.toFixed(2)),\n  'CTR %': c.impressions ? Number((100 * c.clicks / c.impressions).toFixed(2)) : '',\n  'Cost Per Conversion': c.conversions ? Number((c.cost / c.conversions).toFixed(2)) : '',\n} }));\nfor (const pl of [...new Set([...Object.keys(thisWeek), ...Object.keys(lastWeek)])].sort()) rows.push({ json: {\n  Key: week + ' posts ' + pl, Week: week, Channel: 'Posts on ' + pl, Posts: thisWeek[pl] || 0, 'Posts Week Before': lastWeek[pl] || 0,\n  Impressions: '', Clicks: '', Conversions: '', Cost: '', 'CTR %': '', 'Cost Per Conversion': '',\n} });\nreturn rows;"
      }
    },
    {
      "id": "030bc78c-82d7-4ef8-88fb-f4b7262dd6ec",
      "name": "Save the week",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1200,
        0
      ],
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Weekly Numbers",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Key": "={{ $json[\"Key\"] }}",
            "Week": "={{ $json[\"Week\"] }}",
            "Channel": "={{ $json[\"Channel\"] }}",
            "Posts": "={{ $json[\"Posts\"] }}",
            "Posts Week Before": "={{ $json[\"Posts Week Before\"] }}",
            "Impressions": "={{ $json[\"Impressions\"] }}",
            "Clicks": "={{ $json[\"Clicks\"] }}",
            "Conversions": "={{ $json[\"Conversions\"] }}",
            "Cost": "={{ $json[\"Cost\"] }}",
            "CTR %": "={{ $json[\"CTR %\"] }}",
            "Cost Per Conversion": "={{ $json[\"Cost Per Conversion\"] }}"
          },
          "matchingColumns": [
            "Key"
          ],
          "schema": [
            {
              "id": "Key",
              "displayName": "Key",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Week",
              "displayName": "Week",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Channel",
              "displayName": "Channel",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Posts",
              "displayName": "Posts",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Posts Week Before",
              "displayName": "Posts Week Before",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Impressions",
              "displayName": "Impressions",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Clicks",
              "displayName": "Clicks",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Conversions",
              "displayName": "Conversions",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Cost",
              "displayName": "Cost",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "CTR %",
              "displayName": "CTR %",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Cost Per Conversion",
              "displayName": "Cost Per Conversion",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "04bf78e4-2ae2-47b0-a769-dcbad28a75f9",
      "name": "Write the summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1200,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const rows = $('Add up the week').all().map(i => i.json);\nconst week = rows.length ? rows[0].Week : $now.minus({ days: 7 }).toISODate() + ' to ' + $now.minus({ days: 1 }).toISODate();\nconst postRows = rows.filter(r => String(r.Channel).startsWith('Posts on '));\nconst channelRows = rows.filter(r => !String(r.Channel).startsWith('Posts on '));\nconst lines = [];\nfor (const r of postRows) lines.push('- ' + r.Channel + ': ' + r.Posts + ' (week before: ' + r['Posts Week Before'] + ')');\nfor (const r of channelRows) lines.push('- ' + r.Channel + ': ' + r.Impressions + ' seen, ' + r.Clicks + ' clicks, ' + r.Conversions + ' sales' + (r['Cost Per Conversion'] !== '' ? ', ' + r['Cost Per Conversion'] + ' per sale' : ''));\nconst message = 'Your week, ' + week + '\\n\\n' + (lines.length ? lines.join('\\n') : 'No posts went out and no channel rows were found.');\nreturn [{ json: { message } }];"
      }
    },
    {
      "id": "ae2e6d90-3bc6-4fe0-9152-2506bd3a61b6",
      "name": "Send the summary",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        1440,
        200
      ],
      "parameters": {
        "chatId": "={{ $('Settings').first().json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "0374b662-2659-405a-996b-a60429c7742b",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -648,
        922
      ],
      "parameters": {}
    },
    {
      "id": "01167149-3632-4e0b-8600-08a23446f2e1",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -428,
        922
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_TELEGRAM_CHAT_ID"
            },
            {
              "id": "f2",
              "name": "message",
              "type": "string",
              "value": "={{ 'A workflow stopped.\\n\\nWorkflow: ' + (($json.workflow || {}).name || 'unknown') + '\\nFailed step: ' + (($json.execution || {}).lastNodeExecuted || 'unknown') + '\\nWhy: ' + String((($json.execution || {}).error || {}).message || 'n8n did not give a reason.').slice(0, 300) + (($json.execution || {}).url ? '\\nOpen the run: ' + $json.execution.url : '') }}"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      }
    },
    {
      "id": "7d484c95-73cf-4180-bbe2-49c51cf7cba1",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -208,
        922
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Every Monday": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run now": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Get posts that went out",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get posts that went out": {
      "main": [
        [
          {
            "node": "Read channel results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read channel results": {
      "main": [
        [
          {
            "node": "Add up the week",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add up the week": {
      "main": [
        [
          {
            "node": "Save the week",
            "type": "main",
            "index": 0
          },
          {
            "node": "Write the summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the summary": {
      "main": [
        [
          {
            "node": "Send the summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When this workflow fails": {
      "main": [
        [
          {
            "node": "Write the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the failure alert": {
      "main": [
        [
          {
            "node": "Send the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "tags": []
}
