{
  "name": "Client approval check before posts go out",
  "nodes": [
    {
      "id": "4fa1880a-9973-4b5c-86a3-1e3a82d58459",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -688,
        -120
      ],
      "parameters": {
        "content": "## Client approval check before posts go out\nEvery hour it matches the posts set in sprkly for the next 2 days to your client approval sheet, and tells you about any post whose client has not approved, or whose approval ends first.\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=agency-client-approval-ledger\n- A Google Sheets login and one sheet with 2 tabs:\n- Client Approvals: Client, Accounts, Status, Approved Until, Approved By\n- Approval Checks: Post ID, Client, Account, Goes Out, Problem, Checked At, Link\n- A Telegram bot and your chat ID\n\n### Set it up\n1. Fill Client Approvals: one row per client. Write Accounts as platform:handle, with commas. Status is Approved, Waiting or Paused. Approved Until is YYYY-MM-DD.\n2. Pick your sheet in **Read approvals**, **Read past checks** and **Log the problem**.\n3. Add your sprkly key to the 2 sprkly steps. Add your bot to **Send the alert** and your chat ID in **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- Set a client to Waiting and schedule a test post on one of its accounts. Click Test workflow.\n- You get one alert for that post. Run it again: no second alert for the same problem. It never stops a post: you do that in sprkly.",
        "height": 962,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "0e55c52f-4bc3-4ac8-baec-6342776a3a8e",
      "name": "Note: read",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -48,
        -120
      ],
      "parameters": {
        "content": "## Read the ledger and the queue\nAccount IDs from sprkly turn into platform:handle, so they match the Accounts column. Accounts not on the sheet are skipped.",
        "height": 560,
        "width": 1400,
        "color": 7
      }
    },
    {
      "id": "0b331eb4-6bd4-4314-8e21-cabc0c6d795a",
      "name": "Note: alert",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1392,
        -120
      ],
      "parameters": {
        "content": "## Flag and remember\nEach problem is saved by Post ID. You only hear about a post again when its problem changes.",
        "height": 760,
        "width": 1000,
        "color": 7
      }
    },
    {
      "id": "cdf2b680-c1e1-425f-9299-fc26f695a11e",
      "name": "Every hour",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours",
              "hoursInterval": 1
            }
          ]
        }
      }
    },
    {
      "id": "ee1b1fa1-ca23-43ba-90a4-b04eef20648c",
      "name": "Check now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        200
      ],
      "parameters": {}
    },
    {
      "id": "eda2a6d7-9a2a-46b3-8461-25f91647de4e",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        100
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "hoursAhead",
              "type": "number",
              "value": 48
            },
            {
              "id": "f2",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_CHAT_ID"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      }
    },
    {
      "id": "5ddc90ce-1e87-42a4-b096-7ed2cddf6c7a",
      "name": "Read approvals",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        480,
        100
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Client Approvals",
          "mode": "name"
        },
        "options": {}
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "d0d55f58-261f-4dce-a20f-c5748d711a09",
      "name": "Read past checks",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        720,
        100
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Approval Checks",
          "mode": "name"
        },
        "options": {}
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "77ec1a77-e541-466a-9558-f4cf53aadf48",
      "name": "Get account names",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        960,
        100
      ],
      "parameters": {
        "resource": "account",
        "operation": "getAll",
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "7cf786b3-9909-4a72-9930-687bd6b8cf38",
      "name": "Get scheduled posts",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        1200,
        100
      ],
      "parameters": {
        "resource": "post",
        "operation": "getAll",
        "returnAll": true,
        "filters": {
          "status": "scheduled"
        },
        "simplify": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "e33e589f-7441-4ebc-9052-933af4fbcf78",
      "name": "Find posts without approval",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1440,
        100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const s = $('Settings').first().json;\nconst until = $now.plus({ hours: Number(s.hoursAhead) || 48 });\nconst norm = v => String(v ?? '').trim().replace(/^@/, '').toLowerCase();\nconst accounts = new Map($('Get account names').all().map(a => [a.json.id, a.json]));\nconst clients = $('Read approvals').all().map(i => i.json).filter(r => String(r.Client || '').trim()).map(r => ({\n  client: String(r.Client).trim(),\n  status: String(r.Status || '').trim().toLowerCase(),\n  until: String(r['Approved Until'] || '').trim(),\n  refs: String(r.Accounts || '').split(',').map(x => x.trim()).filter(Boolean).map(ref => {\n    const c = ref.indexOf(':');\n    return c < 1 ? null : { p: norm(ref.slice(0, c)), h: norm(ref.slice(c + 1)) };\n  }).filter(Boolean),\n}));\nconst out = [];\nfor (const { json: post } of $('Get scheduled posts').all()) {\n  if (!post.id || post.deleted || !post.scheduledTime) continue;\n  const when = DateTime.fromISO(post.scheduledTime);\n  if (!when.isValid || when > until) continue;\n  for (const pid of post.profileIds || []) {\n    const acc = accounts.get(pid);\n    if (!acc) continue;\n    const client = clients.find(c => c.refs.some(r => r.p === norm(acc.platform) && r.h === norm(acc.handle)));\n    if (!client) continue;\n    let problem = '';\n    if (client.status !== 'approved') problem = 'Client approval is ' + (client.status || 'missing') + '.';\n    else if (!client.until) problem = 'Approved Until is empty.';\n    else {\n      const end = DateTime.fromISO(client.until).endOf('day');\n      if (!end.isValid) problem = 'Approved Until is not a date.';\n      else if (end < when) problem = 'Approval ends ' + client.until + ', before the post goes out.';\n    }\n    if (problem) out.push({ json: {\n      postId: post.id, client: client.client, account: acc.platform + ':' + acc.handle, goesOut: post.scheduledTime, problem,\n      link: 'https://sprkly.app/schedule?utm_source=n8n&utm_medium=workflow&utm_campaign=agency-client-approval-ledger&post=' + encodeURIComponent(post.id),\n    } });\n  }\n}\nreturn out;"
      }
    },
    {
      "id": "b09ba228-f723-4d1b-8173-c39a3f5e0e28",
      "name": "Log the problem",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1680,
        0
      ],
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Approval Checks",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Post ID": "={{ $json.postId }}",
            "Client": "={{ $json.client }}",
            "Account": "={{ $json.account }}",
            "Goes Out": "={{ $json.goesOut }}",
            "Problem": "={{ $json.problem }}",
            "Checked At": "={{ $now.toISO() }}",
            "Link": "={{ $json.link }}"
          },
          "matchingColumns": [
            "Post ID"
          ],
          "schema": [
            {
              "id": "Post ID",
              "displayName": "Post ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Client",
              "displayName": "Client",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Account",
              "displayName": "Account",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Goes Out",
              "displayName": "Goes Out",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Problem",
              "displayName": "Problem",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Checked At",
              "displayName": "Checked At",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Link",
              "displayName": "Link",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "189c7bf9-ef5b-4503-9486-e49a20ed9129",
      "name": "Write the alert",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1680,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const before = new Map($('Read past checks').all().map(i => [String(i.json['Post ID'] || ''), String(i.json.Problem || '')]));\nconst fresh = $('Find posts without approval').all().map(i => i.json).filter(r => before.get(String(r.postId)) !== r.problem);\nif (fresh.length === 0) return [];\nconst lines = fresh.slice(0, 10).map(r => '- ' + r.client + ', ' + r.account + ', ' + DateTime.fromISO(r.goesOut).toFormat('d LLL HH:mm') + '\\n  ' + r.problem + '\\n  ' + r.link);\nconst message = 'Posts without a client OK: ' + fresh.length + '\\n\\n' + lines.join('\\n') + (fresh.length > 10 ? '\\n...and ' + (fresh.length - 10) + ' more' : '') + '\\n\\nNothing was stopped. Pause or move them in sprkly if you need to.';\nreturn [{ json: { message } }];"
      }
    },
    {
      "id": "06cf8f11-463d-4e89-b5b3-ecea331a9daa",
      "name": "Send the alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        1920,
        200
      ],
      "parameters": {
        "chatId": "={{ $('Settings').first().json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "f8c8bc2a-11ab-4cf0-bb99-18f26179ce5c",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -648,
        922
      ],
      "parameters": {}
    },
    {
      "id": "835e1038-0fa3-4e2c-ba0a-a05690404c3a",
      "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": "82b24857-5165-48f7-8646-d96079d2b6c7",
      "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 hour": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check now": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Read approvals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read approvals": {
      "main": [
        [
          {
            "node": "Read past checks",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read past checks": {
      "main": [
        [
          {
            "node": "Get account names",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get account names": {
      "main": [
        [
          {
            "node": "Get scheduled posts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get scheduled posts": {
      "main": [
        [
          {
            "node": "Find posts without approval",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find posts without approval": {
      "main": [
        [
          {
            "node": "Log the problem",
            "type": "main",
            "index": 0
          },
          {
            "node": "Write the alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the alert": {
      "main": [
        [
          {
            "node": "Send the alert",
            "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": []
}
