{
  "name": "Approved calendar video to sprkly and Trello",
  "nodes": [
    {
      "id": "8733604a-05d6-438b-b442-d38dde3181c8",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1400,
        -1230
      ],
      "parameters": {
        "content": "## Approved calendar video to sprkly and Trello\nOne approved Drive video from your sheet is checked, scheduled in sprkly, and its Trello card moves along.\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=approved-calendar-drive-to-sprkly-and-trello\n- Google Sheets, Google Drive and Trello logins\n- A Calendar tab with: Content ID, Status, Title, Caption, Publish At, Drive File ID, Approved SHA256, Profile ID, Post ID, Live URL, Issue, Trello Card ID, Trello Scheduled List ID, Trello Published List ID, Trello Failed List ID, Tracker State\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Pick your sheet in every Google Sheets step. Put its ID in **Published log settings** too.\n2. Add each login where a step asks. Use the same one in every step for that app.\n3. For each video, fill the Drive File ID, its SHA-256 checksum, one sprkly profile ID and a future Publish At with a zone, like 2026-12-01T09:00:00+01:00. Set Status to Approved last.\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- Add one test row with a short MP4 a day away. Run the workflow once.\n- The row gets a Post ID and the card moves to your scheduled list. Delete the test post in sprkly after.",
        "height": 910,
        "width": 560,
        "color": 4
      }
    },
    {
      "name": "Every 15 minutes",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "id": "1422b5fb-8959-4fe9-aaa2-048fc079c4db",
      "position": [
        -760,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 15
            }
          ]
        }
      }
    },
    {
      "name": "Read content calendar",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "0af734a3-7894-4c01-9e49-c2f202dac4b1",
      "position": [
        -520,
        0
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Calendar",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true
    },
    {
      "name": "Choose next approved post",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "19aaa04e-3bea-4726-9375-94af9978c286",
      "position": [
        -280,
        -320
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const rows = $input.all().map(item => item.json);\nconst text = value => String(value ?? '').trim();\nconst key = row => text(row['Content ID']);\nconst ids = new Map();\nfor (const row of rows) if (key(row)) ids.set(key(row), (ids.get(key(row)) ?? 0) + 1);\nconst approved = rows.filter(row => text(row.Status) === 'Approved');\nif (approved.some(row => !key(row) || ids.get(key(row)) !== 1)) {\n  throw new Error('Approved rows need unique Content IDs. Correct the Calendar before scheduling.');\n}\n\nconst now = $now.toMillis();\nconst cutoff = $now.plus({ hours: 48 }).toMillis();\nconst earliest = $now.plus({ minutes: 10 }).toMillis();\nconst candidates = [];\nfor (const row of approved) {\n  const timeText = text(row['Publish At']);\n  const time = DateTime.fromISO(timeText, { setZone: true });\n  const explicitTime = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2})?(?:Z|[+-]\\d{2}:\\d{2})$/.test(timeText);\n  if (time.isValid && explicitTime && time.toMillis() > cutoff) continue;\n\n  const contentId = key(row);\n  const fileId = text(row['Drive File ID']);\n  const hash = text(row['Approved SHA256']).toLowerCase();\n  const profileId = text(row['Profile ID']);\n  const caption = text(row.Caption);\n  const title = text(row.Title);\n  const previousId = text(row['Post ID']);\n  const problems = [];\n  if (!/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,46}[A-Za-z0-9])?$/.test(contentId)) problems.push('Invalid Content ID');\n  if (!/^[A-Za-z0-9_-]+$/.test(fileId)) problems.push('Enter the Drive file ID');\n  if (!/^[a-f0-9]{64}$/.test(hash)) problems.push('Enter the approved video SHA-256');\n  if (!/^[A-Za-z0-9_-]+$/.test(profileId)) problems.push('Choose one sprkly profile ID');\n  if (!title || !caption) problems.push('Add the approved title and caption');\n  if (!time.isValid || !explicitTime) problems.push('Enter Publish At as ISO date and time with an offset');\n  else if (time.toMillis() <= earliest) problems.push('Publish At is past or less than 10 minutes away');\n  if (previousId) problems.push('A Post ID is already recorded. Review it before approving again.');\n  candidates.push({\n    sortTime: time.isValid ? time.toMillis() : now,\n    json: {\n      'Content ID': contentId, 'Post ID': previousId, 'Live URL': text(row['Live URL']),\n      ready: !problems.length, Status: 'Needs Review', Issue: problems.join('; '),\n      fileId, hash, profileId, caption, title, scheduledTime: time.toISO(),\n      externalId: 'caldrive-' + contentId,\n    },\n  });\n}\ncandidates.sort((a, b) => a.sortTime - b.sortTime || a.json['Content ID'].localeCompare(b.json['Content ID']));\nreturn candidates.length ? [{ json: candidates[0].json }] : [];"
      }
    },
    {
      "name": "Approved row is ready",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "id": "39b20c26-acad-4d86-9249-603ab77f32c7",
      "position": [
        -40,
        -320
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ca7bf61a-dd08-419f-9a1b-8a7f6a7299e2",
              "leftValue": "={{ $json.ready === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "name": "Download approved video",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "id": "e6020f7f-df75-4222-b762-c702fe740637",
      "position": [
        200,
        -450
      ],
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "value": "={{ $json.fileId }}",
          "mode": "id"
        },
        "options": {}
      },
      "onError": "continueErrorOutput"
    },
    {
      "name": "Hash the downloaded bytes",
      "type": "n8n-nodes-base.crypto",
      "typeVersion": 1,
      "id": "c09c00e5-4a7c-470c-aa6c-3080c4537ce5",
      "position": [
        440,
        -450
      ],
      "parameters": {
        "action": "hash",
        "type": "SHA256",
        "binaryData": true,
        "binaryPropertyName": "data",
        "dataPropertyName": "fileSha256",
        "encoding": "hex"
      },
      "onError": "continueErrorOutput"
    },
    {
      "name": "Verify the approved video",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "f9733c82-a108-42df-bfa5-2edeaa45258b",
      "position": [
        680,
        -450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const job = $('Choose next approved post').first().json;\nconst file = $('Download approved video').first().binary?.data;\nconst mime = String(file?.mimeType || '').toLowerCase();\nconst checksumMatches = $input.first().json.fileSha256 === job.hash;\nconst mp4 = mime === 'video/mp4' || (mime === 'application/octet-stream' && /\\.mp4$/i.test(file?.fileName || ''));\nconst issue = !mp4 ? 'Drive file must be an MP4 video'\n  : !checksumMatches ? 'The Drive file differs from the approved checksum. Reapprove the final video.'\n  : '';\nconst item = { json: { ...job, ready: !issue, Issue: issue } };\nif (file) item.binary = { data: file };\nreturn [item];"
      }
    },
    {
      "name": "Downloaded video matches",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "id": "b8875b32-2687-4e37-b7da-c89a09420467",
      "position": [
        920,
        -450
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "4f1cccd6-b12e-45a0-844e-9e5205bb9b5e",
              "leftValue": "={{ $json.ready === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "name": "Upload approved video to sprkly",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "id": "d9b1b701-4acb-40a3-a20e-bcaac74fcaee",
      "position": [
        1160,
        -550
      ],
      "parameters": {
        "resource": "media",
        "operation": "upload",
        "binaryPropertyName": "data"
      },
      "onError": "continueErrorOutput"
    },
    {
      "name": "Schedule the approved post",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "id": "04c6e3b8-bc1f-4f84-9586-83635007428c",
      "position": [
        1400,
        -550
      ],
      "parameters": {
        "resource": "post",
        "operation": "create",
        "accountMode": "list",
        "profileIds": "={{ [$(\"Choose next approved post\").first().json.profileId] }}",
        "caption": "={{ $(\"Choose next approved post\").first().json.caption }}",
        "scheduledTime": "={{ $(\"Choose next approved post\").first().json.scheduledTime }}",
        "mediaIds": "={{ $json.mediaId }}",
        "postNow": false,
        "output": "resultRow",
        "additionalFields": {
          "title": "={{ $(\"Choose next approved post\").first().json.title }}",
          "externalId": "={{ $(\"Choose next approved post\").first().json.externalId }}",
          "requireExternalId": true
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "name": "Build scheduling result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "eb48115b-b24f-4623-9497-34a21bab1e10",
      "position": [
        1640,
        -550
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const original = $('Choose next approved post').first().json;\nconst result = $input.first().json;\nconst postId = Array.isArray(result.postIds) && result.postIds.length === 1 ? String(result.postIds[0]) : '';\nconst error = result.error?.message || result.error || 'The scheduler did not return a single post ID';\nconst status = result.ok && postId ? result.status : 'Needs Review';\nreturn [{ json: {\n  'Content ID': original['Content ID'],\n  Status: ['Scheduled', 'Published', 'Failed'].includes(status) ? status : 'Needs Review',\n  'Post ID': postId || String(result.postId || ''),\n  'Live URL': result.link || '',\n  Issue: result.ok && postId && status !== 'Failed' ? '' : String(error).slice(0, 500),\n} }];"
      }
    },
    {
      "name": "Record file or scheduling error",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "8ceb844c-d3a0-4a52-a9ca-4f125c982c92",
      "position": [
        1640,
        -285
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const original = $('Choose next approved post').first().json;\nconst input = $input.first().json;\nconst error = input.error?.message || input.error || input.message || 'Download, verification or upload failed';\nreturn [{ json: { ...original, Status: 'Needs Review', Issue: String(error).slice(0, 500) } }];"
      }
    },
    {
      "name": "Save scheduling result",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "d8153c17-ce98-4bf6-9dae-cfd7eb0ed71d",
      "position": [
        1880,
        -420
      ],
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Calendar",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Content ID": "={{ $json[\"Content ID\"] }}",
            "Status": "={{ $json[\"Status\"] }}",
            "Post ID": "={{ $json[\"Post ID\"] }}",
            "Live URL": "={{ $json[\"Live URL\"] }}",
            "Issue": "={{ $json[\"Issue\"] }}"
          },
          "matchingColumns": [
            "Content ID"
          ],
          "schema": [
            {
              "id": "Content ID",
              "displayName": "Content ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Status",
              "displayName": "Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Post ID",
              "displayName": "Post ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Live URL",
              "displayName": "Live URL",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Issue",
              "displayName": "Issue",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      }
    },
    {
      "name": "Select scheduled posts",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "e3816d0d-0863-4738-a561-a11706b9457d",
      "position": [
        -280,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const rows = $input.all();\nconst keys = rows.map(item => String(item.json['Content ID'] ?? '').trim());\nconst counts = new Map();\nfor (const id of keys) counts.set(id, (counts.get(id) ?? 0) + 1);\nreturn rows.flatMap((item, index) => {\n  const row = item.json;\n  const id = keys[index];\n  return row.Status === 'Scheduled' && id && counts.get(id) === 1 && String(row['Post ID'] ?? '').trim()\n    ? [{ json: { ...row, 'Content ID': id }, pairedItem: index }] : [];\n});"
      }
    },
    {
      "name": "Check the actual post status",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "id": "2098fa85-e950-445e-9ff3-e6fda32b2d67",
      "position": [
        -40,
        0
      ],
      "parameters": {
        "resource": "post",
        "operation": "get",
        "postId": "={{ $json[\"Post ID\"] }}",
        "simplify": true
      },
      "onError": "continueRegularOutput"
    },
    {
      "name": "Build final publishing result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "548c32c1-84e1-4a26-8d4b-c0c32a3b9722",
      "position": [
        200,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.all().flatMap((item, index) => {\n  const post = item.json;\n  const row = $('Select scheduled posts').itemMatching(index).json;\n  if (String(post.id ?? '') !== String(row['Post ID'] ?? '')) return [];\n  const status = post.deleted ? 'Needs Review'\n    : ['posted', 'published'].includes(post.status) ? 'Published'\n    : post.status === 'failed' ? 'Failed' : '';\n  if (!status) return [];\n  return [{ json: {\n    'Content ID': row['Content ID'],\n    Status: status,\n    'Post ID': String(post.id),\n    'Live URL': status === 'Published' ? String(post.permalink || '') : '',\n    Issue: status === 'Failed' ? String(post.failedReason || 'Publishing failed').slice(0, 500)\n      : status === 'Needs Review' ? 'The scheduled post was deleted' : '',\n  }, pairedItem: index }];\n});"
      }
    },
    {
      "name": "Save final publishing result",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "6fbf7cfa-33d7-42e5-986f-7634106d0486",
      "position": [
        440,
        0
      ],
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Calendar",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Content ID": "={{ $json[\"Content ID\"] }}",
            "Status": "={{ $json[\"Status\"] }}",
            "Post ID": "={{ $json[\"Post ID\"] }}",
            "Live URL": "={{ $json[\"Live URL\"] }}",
            "Issue": "={{ $json[\"Issue\"] }}"
          },
          "matchingColumns": [
            "Content ID"
          ],
          "schema": [
            {
              "id": "Content ID",
              "displayName": "Content ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Status",
              "displayName": "Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Post ID",
              "displayName": "Post ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Live URL",
              "displayName": "Live URL",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Issue",
              "displayName": "Issue",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      }
    },
    {
      "name": "Find Trello updates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "7f5ae165-9fda-468f-99ab-fcbfae654e0f",
      "position": [
        -280,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const rows = $input.all();\nconst keys = rows.map(item => String(item.json['Content ID'] ?? '').trim());\nconst counts = new Map();\nfor (const id of keys) counts.set(id, (counts.get(id) ?? 0) + 1);\nreturn rows.flatMap((item, index) => {\n  const row = item.json;\n  const id = keys[index];\n  const status = row.Status;\n  if (!id || counts.get(id) !== 1 || !['Scheduled', 'Published', 'Failed'].includes(status) ||\n      row['Tracker State'] === status) return [];\n  const cardId = String(row['Trello Card ID'] || '').trim();\n  const listId = String(row['Trello ' + status + ' List ID'] || '').trim();\n  if (!cardId || !listId) return [];\n  return [{ json: { 'Content ID': id, 'Tracker State': status, cardId, listId }, pairedItem: index }];\n});"
      }
    },
    {
      "name": "Move the existing Trello card",
      "type": "n8n-nodes-base.trello",
      "typeVersion": 1,
      "id": "4d75269e-0bf3-4e31-b83a-0109c6c92c4f",
      "position": [
        -40,
        300
      ],
      "parameters": {
        "resource": "card",
        "operation": "update",
        "id": {
          "__rl": true,
          "value": "={{ $json.cardId }}",
          "mode": "id"
        },
        "updateFields": {
          "idList": "={{ $json.listId }}"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "name": "Confirm the Trello move",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "8e344f6b-b7c8-4c67-9b66-431d33bb991c",
      "position": [
        200,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.all().flatMap((item, index) => {\n  const target = $('Find Trello updates').itemMatching(index).json;\n  return item.json.id && String(item.json.idList) === target.listId\n    ? [{ json: target, pairedItem: index }] : [];\n});"
      }
    },
    {
      "name": "Save tracker state",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "df5cffe3-b0be-460e-b909-436f49672385",
      "position": [
        440,
        300
      ],
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Calendar",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Content ID": "={{ $json[\"Content ID\"] }}",
            "Tracker State": "={{ $json[\"Tracker State\"] }}"
          },
          "matchingColumns": [
            "Content ID"
          ],
          "schema": [
            {
              "id": "Content ID",
              "displayName": "Content ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Tracker State",
              "displayName": "Tracker State",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      }
    },
    {
      "name": "Note: automatic published post log",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "id": "372b0fca-cef2-56b4-b15c-68755b190209",
      "position": [
        -760,
        -1230
      ],
      "parameters": {
        "content": "## Log posts as they go live\n\nSet **Spreadsheet ID** in **Published log settings**. Use the same Google Sheets credential in the two log steps and your sprkly API credential on **When this workflow's post goes live**.\n\nThe workflow checks each minute for its published posts. It creates **Published Posts** and its headers as needed, then writes one row per Post ID. This branch runs after publication. It leaves the scheduling and source status branches intact.",
        "height": 215,
        "width": 520,
        "color": 5
      }
    },
    {
      "name": "When this workflow's post goes live",
      "type": "n8n-nodes-sprkly.sprklyTrigger",
      "typeVersion": 1,
      "id": "dd55fa4a-2759-568e-94e3-c6a269f476ed",
      "position": [
        -760,
        -980
      ],
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "event": "postPublished",
        "externalIdPrefix": "caldrive-",
        "stripPrefix": false
      }
    },
    {
      "name": "Build published log rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "1fe5c092-468b-51e6-a19a-31cc88c25b0c",
      "position": [
        -520,
        -980
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const prefix = \"caldrive-\";\nconst text = value => typeof value === 'string' || typeof value === 'number' ? String(value).trim() : '';\nconst values = input => Array.isArray(input) ? input.map(text).filter(Boolean) : [];\nconst rows = new Map();\n\nfor (const [index, item] of $input.all().entries()) {\n  const post = item.json;\n  const id = text(post.id);\n  const externalId = text(post.externalId);\n  if (!id || post.deleted || !['posted', 'published'].includes(post.status) ||\n      !externalId.startsWith(prefix) || externalId.length === prefix.length) continue;\n\n  const platforms = values(post.platforms);\n  const accounts = values(post.profileIds);\n  const suffix = ':' + platforms[0] + ':' + accounts[0];\n  const source = platforms.length && accounts.length && externalId.endsWith(suffix)\n    ? externalId.slice(0, -suffix.length) : externalId;\n  if (source.length <= prefix.length) continue;\n  const previous = rows.get(id)?.json;\n  rows.set(id, {\n    json: {\n      'Post ID': id,\n      Status: 'Published',\n      'Published At': text(post.publishedAt) || previous?.['Published At'] || '',\n      Platform: platforms.join(', '),\n      'Account ID': accounts.join(', '),\n      'Source ID': source,\n      'External ID': externalId,\n      'Live URL': text(post.permalink) || text(post.link) || previous?.['Live URL'] || '',\n      'Sprkly URL': 'https://sprkly.app/schedule?utm_source=n8n&utm_medium=workflow&utm_campaign=approved-calendar-drive-to-sprkly-and-trello&post=' + encodeURIComponent(id),\n    },\n    pairedItem: index,\n  });\n}\nreturn [...rows.values()];"
      }
    },
    {
      "name": "Published log settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "id": "2de43af9-a6f5-573a-ad8f-65d9f144200c",
      "position": [
        -280,
        -980
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "68a5637b-c324-5ab0-a619-7c0ec2b62724",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "e4e97dd8-a3fd-58fa-9148-e52105ea03b8",
              "name": "Tab name",
              "type": "string",
              "value": "Published Posts"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      },
      "executeOnce": true
    },
    {
      "name": "Ensure published log tab",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "05ffb24a-ec37-5ac8-82cf-cf66bdf41ae0",
      "position": [
        -40,
        -980
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "create",
        "documentId": {
          "__rl": true,
          "value": "={{ String($json[\"Spreadsheet ID\"]).trim() }}",
          "mode": "id"
        },
        "title": "={{ String($json[\"Tab name\"]).trim() }}",
        "options": {}
      },
      "alwaysOutputData": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "name": "Restore published log rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "2fae1691-b572-5643-bf5d-457876934d71",
      "position": [
        200,
        -980
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Create Sheet has one output for the setup call. Restore every publication in the trigger batch.\nreturn $('Build published log rows').all().map(({ json }) => ({ json, pairedItem: 0 }));"
      }
    },
    {
      "name": "Upsert published post log",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "f7a80054-45b9-548d-a59b-d0af2bd2a168",
      "position": [
        440,
        -980
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "={{ String($(\"Published log settings\").first().json[\"Spreadsheet ID\"]).trim() }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ String($(\"Published log settings\").first().json[\"Tab name\"]).trim() }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "Post ID"
          ],
          "schema": []
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "insertInNewColumn",
          "useAppend": true
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "80a350ce-88c2-4a85-8fd3-cb4e1cd1db73",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -1360,
        -240
      ],
      "parameters": {}
    },
    {
      "id": "3b38b91a-6c6b-4e7a-9b2f-315dee514fbb",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -1140,
        -240
      ],
      "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": "7f2c45e7-42e9-4538-8632-aab5d1a8c396",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -920,
        -240
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Every 15 minutes": {
      "main": [
        [
          {
            "node": "Read content calendar",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read content calendar": {
      "main": [
        [
          {
            "node": "Choose next approved post",
            "type": "main",
            "index": 0
          },
          {
            "node": "Select scheduled posts",
            "type": "main",
            "index": 0
          },
          {
            "node": "Find Trello updates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Choose next approved post": {
      "main": [
        [
          {
            "node": "Approved row is ready",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Approved row is ready": {
      "main": [
        [
          {
            "node": "Download approved video",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Save scheduling result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download approved video": {
      "main": [
        [
          {
            "node": "Hash the downloaded bytes",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record file or scheduling error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Hash the downloaded bytes": {
      "main": [
        [
          {
            "node": "Verify the approved video",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record file or scheduling error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify the approved video": {
      "main": [
        [
          {
            "node": "Downloaded video matches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Downloaded video matches": {
      "main": [
        [
          {
            "node": "Upload approved video to sprkly",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Save scheduling result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload approved video to sprkly": {
      "main": [
        [
          {
            "node": "Schedule the approved post",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record file or scheduling error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule the approved post": {
      "main": [
        [
          {
            "node": "Build scheduling result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record file or scheduling error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build scheduling result": {
      "main": [
        [
          {
            "node": "Save scheduling result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Record file or scheduling error": {
      "main": [
        [
          {
            "node": "Save scheduling result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Select scheduled posts": {
      "main": [
        [
          {
            "node": "Check the actual post status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check the actual post status": {
      "main": [
        [
          {
            "node": "Build final publishing result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build final publishing result": {
      "main": [
        [
          {
            "node": "Save final publishing result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Trello updates": {
      "main": [
        [
          {
            "node": "Move the existing Trello card",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Move the existing Trello card": {
      "main": [
        [
          {
            "node": "Confirm the Trello move",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Confirm the Trello move": {
      "main": [
        [
          {
            "node": "Save tracker state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When this workflow's post goes live": {
      "main": [
        [
          {
            "node": "Build published log rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build published log rows": {
      "main": [
        [
          {
            "node": "Published log settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Published log settings": {
      "main": [
        [
          {
            "node": "Ensure published log tab",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ensure published log tab": {
      "main": [
        [
          {
            "node": "Restore published log rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Restore published log rows": {
      "main": [
        [
          {
            "node": "Upsert published post log",
            "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
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
