{
  "name": "Creator weekly desk",
  "nodes": [
    {
      "id": "aede813b-0545-47ea-b4ee-acfcf3f3b810",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -710,
        -530
      ],
      "parameters": {
        "content": "## Creator weekly desk\nEvery Monday a brief built from your own YouTube numbers goes to Notion and Trello. Approved Drive videos get scheduled and logged.\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=creator-weekly-desk\n- A YouTube Data API key, saved as a Query Auth login with the name key\n- Notion, Trello, Google Drive and Google Sheets logins\n- Gmail, only if you want the brief by email\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Fill **Creator settings**: sheet ID, your uploads playlist, up to 8 watchlist playlists, the Notion data source and title field, Trello board and list IDs, and one sprkly profile ID.\n2. Add each login where a step asks. Use the same one in every step for that app.\n3. 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 **Build this week’s brief** picked. A brief shows up in Notion and a card in Trello.\n- Nothing posts until you set a Calendar row to Approved.",
        "height": 858,
        "width": 560,
        "color": 4
      }
    },
    {
      "name": "Every 15 minutes",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "id": "3ee12b17-2329-5bbe-8fb1-25dff9eff7e4",
      "position": [
        -70,
        175
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 15
            }
          ]
        }
      }
    },
    {
      "name": "Read content calendar",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "39b7c4bc-ad32-587c-82d9-a7c837f2e28b",
      "position": [
        1380,
        1850
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "sheetName": {
          "__rl": true,
          "value": "Calendar",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true
    },
    {
      "name": "Choose next approved post",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "7a3c2661-4eba-5c2a-a8f4-8fb17b575819",
      "position": [
        1620,
        1530
      ],
      "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: 'creatorops-' + 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": "b5e921ae-37af-5324-b413-c81498f61391",
      "position": [
        1860,
        1530
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "3db8aca3-ad99-5fe0-8250-ec805e631f69",
              "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": "5a2fc2d7-667b-5554-879c-10edb702ab3a",
      "position": [
        2100,
        1400
      ],
      "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": "0863606b-c76a-5233-bb51-c8749b2b809c",
      "position": [
        2340,
        1400
      ],
      "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": "561047c2-0b07-5a01-b3aa-9e9cc02d964a",
      "position": [
        2580,
        1400
      ],
      "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": "ff78c64e-ee68-5f60-a387-0abc1d6d62d4",
      "position": [
        2820,
        1400
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "3884162d-6099-58fb-9031-e479ea5746b7",
              "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": "3594a7a6-4e95-587a-8d1b-ef3946218cfc",
      "position": [
        3060,
        1300
      ],
      "parameters": {
        "resource": "media",
        "operation": "upload",
        "binaryPropertyName": "data"
      },
      "onError": "continueErrorOutput"
    },
    {
      "name": "Schedule the approved post",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "id": "4861ea59-35e5-587f-accc-b010b691213b",
      "position": [
        3300,
        1300
      ],
      "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": "4110a657-adc5-50a5-a783-6bb073b44725",
      "position": [
        3540,
        1300
      ],
      "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": "3d614b63-2d9b-5a0a-8889-100360d72953",
      "position": [
        3540,
        1565
      ],
      "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": "66051a83-8bc2-58d1-94ac-d45d71919654",
      "position": [
        3780,
        1430
      ],
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "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": "1a0cfe0d-221e-568d-abc8-8cc6d805b9a7",
      "position": [
        1620,
        1850
      ],
      "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": "38572847-8a00-5a46-988c-4fad1d4f8e28",
      "position": [
        1860,
        1850
      ],
      "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": "824548f6-5ab3-5750-8d5c-b2de68fa7aca",
      "position": [
        2100,
        1850
      ],
      "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": "7e61c07f-8763-543e-80ed-fdf86f043886",
      "position": [
        2340,
        1850
      ],
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "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": "75114cfa-92c9-564b-844f-b769b4787aea",
      "position": [
        1620,
        2150
      ],
      "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": "3395502a-588e-5990-bc95-205db8555a43",
      "position": [
        1860,
        2150
      ],
      "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": "9ee6556b-62a6-577d-bab6-9e2b6fa4ac81",
      "position": [
        2100,
        2150
      ],
      "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": "50485a09-96b5-59f9-84cc-e95d0825e2c9",
      "position": [
        2340,
        2150
      ],
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "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": "When this workflow's post goes live",
      "type": "n8n-nodes-sprkly.sprklyTrigger",
      "typeVersion": 1,
      "id": "56da1f4d-06f5-51e6-9499-e724ca9bed74",
      "position": [
        -70,
        345
      ],
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "event": "postPublished",
        "externalIdPrefix": "creatorops-",
        "stripPrefix": false
      }
    },
    {
      "name": "Build published log rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "cadafd9f-a223-55d0-b80a-8dba4bf2e86d",
      "position": [
        1380,
        870
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const prefix = \"creatorops-\";\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=creator-weekly-desk&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": "58ae6154-dd0b-52db-82da-c30cf4423cc7",
      "position": [
        1620,
        870
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "82511f59-ca6a-5835-9716-36e334c10202",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"] }}"
            },
            {
              "id": "cb9b898c-35a4-57b9-8a7d-b0540acda84d",
              "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": "043f2fc4-ebb7-548b-b6a6-82a0bcbf4f8e",
      "position": [
        1860,
        870
      ],
      "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": "b7c1c01f-92f6-57d2-8027-5ec808e64fa7",
      "position": [
        2100,
        870
      ],
      "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": "e59710f6-ded7-5720-8721-f49966622d1e",
      "position": [
        2340,
        870
      ],
      "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": "2957c773-0388-5844-ab7d-9ef59453eb33",
      "name": "Measure before choosing a format",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1300,
        -530
      ],
      "parameters": {
        "content": "## Measure before choosing a format\n\nOn Monday, scan recent uploads and record YouTube snapshots. Compare median views per day among the creator’s own posts aged 5, 28 days, with at least two per duration bucket. Watchlist uploads provide timely evidence. One draft per week is taken forward.",
        "width": 2090,
        "height": 170,
        "color": 7
      }
    },
    {
      "id": "ff433c0e-f46d-5ba5-90bd-db5787c3957e",
      "name": "Prepare the production handoff",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        3400,
        -530
      ],
      "parameters": {
        "content": "## Prepare the production handoff\n\nThe same brief becomes one Notion page, one Trello card and one Google Sheets Calendar draft. Re-running uses existing work. Use the calendar to approve the final cut.",
        "width": 3550,
        "height": 160,
        "color": 6
      }
    },
    {
      "id": "4aad374d-f5b7-5fcb-bcf3-20374944af9d",
      "name": "Approve the asset and schedule",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1240,
        1030
      ],
      "parameters": {
        "content": "## Approve the asset and schedule\n\nThe Calendar draft carries the account and Trello list IDs. In Sheets, fill Title, Caption, Publish At (ISO with offset), Drive File ID and Approved SHA256, then set Status to Approved. Use a private MP4 within the Sprkly upload limit. If the downloaded bytes differ, the row moves to Needs Review.",
        "width": 2440,
        "height": 160,
        "color": 4
      }
    },
    {
      "id": "063fa1ff-d41b-5b38-ad4a-ef011b604bd9",
      "name": "Confirm publication and keep the records current",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        930,
        460
      ],
      "parameters": {
        "content": "## Confirm publication and keep the records current\n\nThe minute-by-minute event path logs confirmed live posts to Published Posts automatically. The periodic check updates Calendar and Trello statuses. YouTube uploads can show up in later metric snapshots.",
        "width": 2410,
        "height": 155,
        "color": 5
      }
    },
    {
      "id": "d0e2573c-c30d-59da-a082-68e918ed60e4",
      "name": "Plan Monday at 8 AM",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -70,
        -140
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "weeksInterval": 1,
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8,
              "triggerAtMinute": 0
            }
          ]
        }
      }
    },
    {
      "id": "a92a373f-e93a-5f65-9faa-7badb66275d5",
      "name": "Build this week’s brief",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -70,
        20
      ],
      "parameters": {}
    },
    {
      "id": "c73b7935-fbd9-540a-8082-947d4dba0d68",
      "name": "Creator settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        170,
        95
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "4d813fa7-9076-54ba-b6bc-85dbbd41315e",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "d2324488-4476-539f-be57-d0eaef575451",
              "name": "My uploads playlist ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "0c7de429-dfb0-5ef6-b0c2-bd36b6bbbae9",
              "name": "Watchlist playlist IDs",
              "type": "string",
              "value": ""
            },
            {
              "id": "03dd1354-91c5-51c5-a33d-145839d38b2b",
              "name": "Notion data source ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "87af16d4-e05c-5d53-889a-f76a927275b0",
              "name": "Notion title property",
              "type": "string",
              "value": "Name"
            },
            {
              "id": "689c5297-7cfc-5f44-82a5-88da93bf84b2",
              "name": "Trello board ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "b4c09738-4a95-5330-9e62-2f5d968ff5d8",
              "name": "Trello production list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "f6ae0fe3-b05c-504b-8160-9ca9008c1cdb",
              "name": "Trello scheduled list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "f86d60ad-9a88-5aea-9cae-30b41ae219ed",
              "name": "Trello published list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "aa297fd7-0609-5dfa-ac15-0eda93f55f34",
              "name": "Trello failed list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "9189967d-1ce0-57d8-8399-bfb40ff453f2",
              "name": "Sprkly profile ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "79f91378-1c90-5cc2-a6a8-910022d7db01",
              "name": "Digest recipient",
              "type": "string",
              "value": ""
            }
          ]
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "85870221-9e33-5e06-8a32-d28ccdae233a",
      "name": "Publishing interval",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        390,
        95
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "3eab3be5-d5a3-5b9e-a7a1-5e6c7d7977ea",
              "leftValue": "={{ $('Every 15 minutes').isExecuted }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "1a2eb84c-5335-5378-991d-fb2e759efa4c",
      "name": "Publication event",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        620,
        150
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "31e3870a-457c-5679-a4a1-5b35bc9f667f",
              "leftValue": "={{ $(\"When this workflow's post goes live\").isExecuted }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "7251edea-cfff-537d-b268-8b48dba0a221",
      "name": "Recover the publication event batch",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        850,
        730
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $(\"When this workflow's post goes live\").all().map(({json})=>({json}));"
      }
    },
    {
      "id": "37d0a955-1431-53d7-8088-65c6c61dfcd8",
      "name": "Ensure Calendar for publishing",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        850,
        1780
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "create",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "title": "Calendar"
      },
      "alwaysOutputData": true
    },
    {
      "id": "df917847-c10b-563c-adb1-5bf883ad0110",
      "name": "Validate planning settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        850,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const c=$input.first().json;\nconst ids=['Spreadsheet ID','Notion data source ID','Trello board ID','Trello production list ID',\n'Trello scheduled list ID','Trello published list ID','Trello failed list ID','Sprkly profile ID'];\nfor(const k of ids) if(!/^[A-Za-z0-9_-]+$/.test(c[k].trim())) throw new Error('Set '+k+' in Creator settings.');\nconst own=c['My uploads playlist ID'].trim();\nconst watch=[...new Set(c['Watchlist playlist IDs'].split(/[,\\n]/).map(v=>v.trim()).filter(v=>v&&v!==own))];\nif(!/^[A-Za-z0-9_-]{8,100}$/.test(own)||watch.some(v=>!/^[A-Za-z0-9_-]{8,100}$/.test(v))||watch.length>8) throw new Error('Set one uploads playlist and up to eight watchlist playlist IDs.');\nif(!c['Notion title property'].trim()) throw new Error('Set the Notion title property.');\nreturn [{json:{own,watch}}];"
      }
    },
    {
      "id": "379c6a65-997d-5f92-8d1a-e3feb4d954a6",
      "name": "Ensure Calendar for planning",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1090,
        -140
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "create",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "title": "Calendar"
      },
      "alwaysOutputData": true
    },
    {
      "id": "ddfc860a-6890-5c81-9b40-5ac931a228d0",
      "name": "Ensure Creator Signals tab",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1330,
        -140
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "create",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "title": "Creator Signals"
      },
      "alwaysOutputData": true
    },
    {
      "id": "5b81e46f-d9f9-589f-8501-a6bf09598511",
      "name": "Prepare YouTube watchlist requests",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1570,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const {own,watch}=$(\"Validate planning settings\").first().json;return [own,...watch].map(playlist=>({json:{playlist,own:playlist===own}}));"
      }
    },
    {
      "id": "d1669adc-e236-54b4-b7fc-b7f2025b4553",
      "name": "Read recent YouTube uploads",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1810,
        -140
      ],
      "parameters": {
        "url": "https://www.googleapis.com/youtube/v3/playlistItems",
        "method": "GET",
        "options": {
          "timeout": 45000
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "part",
              "value": "contentDetails"
            },
            {
              "name": "maxResults",
              "value": "25"
            },
            {
              "name": "playlistId",
              "value": "={{ $json.playlist }}"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "adb7573a-583b-5383-bd43-1f721864eb07",
      "name": "Collect video IDs in API batches",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2050,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const map=new Map();\nfor(const [i,{json:p}] of $input.all().entries()){\n  if(!Array.isArray(p.items)) throw new Error('YouTube did not return a playlist item list.');\n  const source=$('Prepare YouTube watchlist requests').itemMatching(i).json;\n  for(const item of p.items){\n    const id=item.contentDetails?.videoId;\n    if(/^[A-Za-z0-9_-]{11}$/.test(id||'')&&!map.has(id)) map.set(id,{id,own:source.own,playlist:source.playlist});\n  }\n}\nconst entries=[...map.values()];\nif(!entries.length) throw new Error('The configured playlists have no accessible uploads.');\nconst out=[];\nfor(let i=0;i<entries.length;i+=50) out.push({json:{entries:entries.slice(i,i+50)}});\nreturn out;"
      }
    },
    {
      "id": "65d3a552-6ce5-5565-89ca-b5f51225f63c",
      "name": "Pull current YouTube metrics",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2290,
        -140
      ],
      "parameters": {
        "url": "https://www.googleapis.com/youtube/v3/videos",
        "method": "GET",
        "options": {
          "timeout": 45000
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "part",
              "value": "snippet,contentDetails,statistics"
            },
            {
              "name": "id",
              "value": "={{ $json.entries.map(entry=>entry.id).join(',') }}"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "761e7e67-e6fd-586f-9cb0-0c79938e2bc8",
      "name": "Score comparable posts and capture signals",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2530,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const stamp=$now.toISO();\nconst date=$now.toISODate();\nconst group=new Map([['Under 3 minutes',[]],['3 minutes or longer',[]]]);\nconst videos=[], trends=[];\nconst seen=new Set();\nconst duration=iso=>{\n  const m=String(iso||'').match(/^P(?:(\\d+)D)?T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?$/);\n  return m?Number(m[1]||0)*86400+Number(m[2]||0)*3600+Number(m[3]||0)*60+Number(m[4]||0):0;\n};\nfor(const [i,{json:p}] of $input.all().entries()){\n  if(!Array.isArray(p.items)) throw new Error('YouTube video statistics were unavailable.');\n  const items=$('Collect video IDs in API batches').itemMatching(i).json.entries;\n  const input=new Map(items.map(x=>[x.id,x]));\n  for(const v of p.items){\n    const source=input.get(v.id);\n    if(!source||seen.has(v.id)) continue;\n    seen.add(v.id);\n    const snippet=v.snippet||{}, stats=v.statistics||{};\n    const age=($now.toMillis()-Date.parse(snippet.publishedAt))/86400000;\n    const runtime=duration(v.contentDetails?.duration);\n    const format=runtime?runtime<180?'Under 3 minutes':'3 minutes or longer':'Unclassified';\n    const asCount=value=>/^\\d+$/.test(String(value??''))?Number(value):null;\n    const views=asCount(stats.viewCount);\n    const perDay=views!==null&&age>0?Math.round(views/age*100)/100:null;\n    const url='https://www.youtube.com/watch?v='+v.id;\n    const title=String(snippet.title||'').slice(0,150);\n    videos.push({'Snapshot ID':date+'-'+v.id,'Video ID':v.id,'Captured At':stamp,'Published At':snippet.publishedAt||'',\n      Source:source.own?'My channel':'Watchlist',Channel:snippet.channelTitle||'',Title:title,\n      Format:format,Views:views??'',Likes:asCount(stats.likeCount)??'',Comments:asCount(stats.commentCount)??'',\n      'Views Per Day':perDay??'','Video URL':url});\n    if(source.own&&age>=5&&age<=28&&perDay!==null&&group.has(format)) group.get(format).push({title,url,perDay});\n    if(!source.own&&age>=0&&age<=7&&perDay!==null) trends.push({title,url,perDay});\n  }\n}\nif(!videos.length) throw new Error('No accessible YouTube statistics were returned.');\nconst median=nums=>{const m=Math.floor(nums.length/2);return nums.length%2?nums[m]:(nums[m-1]+nums[m])/2;};\nconst rankings=[...group].filter(([,set])=>set.length>=2).map(([format,set])=>({format,\n  median:median(set.map(x=>x.perDay).sort((a,b)=>a-b)),sample:set.length,\n  top:[...set].sort((a,b)=>b.perDay-a.perDay)[0]})).sort((a,b)=>b.median-a.median||a.format.localeCompare(b.format));\nconst leader=rankings[0];\nconst fmt=leader?.format||'Run a format test';\nconst comparison=rankings.map(x=>x.format+': '+x.median.toFixed(1)+' median views/day ('+x.sample+' videos)').join(' | ');\nconst reason=leader?(comparison+'. Leading example: '+leader.top.url):\n  'Fewer than two comparable posts per eligible format. Run a small format test and review the result in a week.';\nconst picks=trends.sort((a,b)=>b.perDay-a.perDay||a.url.localeCompare(b.url)).slice(0,3);\nconst evidence=picks.map(x=>x.title+': '+x.url+' ('+x.perDay+' views/day)').join('\\n');\nconst key='brief-'+$now.weekYear+'-W'+String($now.weekNumber).padStart(2,'0');\nconst writerBrief=['Plan an original '+fmt+' video. Write a hook, a short shot list, a closing call to action and a short caption.',\n 'Do not copy another creator. Use the titles below as reference only. If the numbers are thin, plan one small format test.',\n 'Decision evidence: '+reason,'Watchlist references:\\n'+(evidence||'No recent watchlist signal.')].join('\\n\\n');\nreturn [{json:{videos,key,format:fmt,reason,evidence,writerBrief}}];"
      }
    },
    {
      "id": "15933e5a-dc1f-5a33-8c42-393298defcb1",
      "name": "Expand video snapshots",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2770,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.first().json.videos.map(json=>({json}));"
      }
    },
    {
      "id": "f343cff1-cfeb-5c61-9c11-5979a4f59dfd",
      "name": "Upsert date and video snapshots",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3010,
        -140
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "insertInNewColumn",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Creator Signals"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "Snapshot ID"
          ],
          "schema": []
        }
      }
    },
    {
      "id": "2a93b232-cd97-5659-b287-3263cd65f294",
      "name": "Read Calendar for existing brief",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3250,
        -140
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Calendar"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "8d39bff3-3aad-57cf-afeb-71bc96840451",
      "name": "Skip a brief already in production",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3490,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const p=$('Score comparable posts and capture signals').first().json;\nif($input.all().some(({json:r})=>String(r['Content ID']||'').trim()===p.key)) return [];\nreturn [{json:{key:p.key,format:p.format,reason:p.reason,evidence:p.evidence,writerBrief:p.writerBrief}}];"
      }
    },
    {
      "id": "bae0e6f7-73c1-5a67-bf5b-29eba834226b",
      "name": "Prepare the original production brief",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3970,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const p=$('Skip a brief already in production').first().json;\nconst parts=['Recommended format: '+p.format,p.reason,p.evidence||'No recent watchlist signal.','Brief for the writer\\n'+p.writerBrief.slice(0,1650)];\nreturn [{json:{...p,title:'['+p.key+'] Weekly content brief',parts}}];"
      }
    },
    {
      "id": "e73429b7-e692-53ff-9b19-dfd5e4f9daa3",
      "name": "Find this week’s Notion brief",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        4210,
        -140
      ],
      "parameters": {
        "url": "={{ 'https://api.notion.com/v1/data_sources/'+$(\"Creator settings\").first().json[\"Notion data source ID\"].trim()+'/query' }}",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "notionApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {page_size:2,filter:{property:$(\"Creator settings\").first().json[\"Notion title property\"],title:{starts_with:'['+$json.key+']'}}} }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "2025-09-03"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "8429ca6c-6577-5445-9727-355eeddd38d9",
      "name": "Reuse or prepare the Notion brief",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4450,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const p=$('Prepare the original production brief').first().json;\nconst q=$input.first().json;\nif(!Array.isArray(q.results)||q.results.length>1||q.has_more) throw new Error('Resolve duplicate Notion briefs for '+p.key);\nconst c=$('Creator settings').first().json;\nconst existing=q.results[0];\nconst body={parent:{type:'data_source_id',data_source_id:c['Notion data source ID'].trim()},\n properties:{[c['Notion title property']]:{title:[{text:{content:p.title}}]}},\n children:p.parts.map(content=>({object:'block',type:'paragraph',paragraph:{rich_text:[{type:'text',text:{content:content.slice(0,1800)}}]}}))};\nreturn [{json:{...p,notionId:existing?.id||'',notionUrl:existing?.url||'',body}}];"
      }
    },
    {
      "id": "96b6ceab-dd2e-5476-b6f1-76fd6ecdba82",
      "name": "Notion brief is new",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        4690,
        -140
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "edaf2ab9-f87e-5133-a3bf-afaf0901395f",
              "leftValue": "={{ !$json.notionId }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "06a3036d-b1af-5a2b-b0f2-7f97471d45b8",
      "name": "Create the Notion production brief",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        4930,
        -220
      ],
      "parameters": {
        "url": "https://api.notion.com/v1/pages",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "notionApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.body }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "2025-09-03"
            }
          ]
        }
      }
    },
    {
      "id": "5ae90e35-a0dd-5948-a3cd-05962e5dec92",
      "name": "Read Trello production board cards",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        5170,
        -140
      ],
      "parameters": {
        "url": "={{ 'https://api.trello.com/1/boards/'+$(\"Creator settings\").first().json[\"Trello board ID\"].trim()+'/cards/all' }}",
        "method": "GET",
        "options": {
          "timeout": 45000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": false
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "trelloApi",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "id,name,closed,shortUrl"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "ec21d8df-87f5-5574-b22a-d84c5ea73bc5",
      "name": "Find or prepare the production card",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        5410,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const p=$('Reuse or prepare the Notion brief').first().json;\nconst notion=$('Create the Notion production brief').isExecuted?$('Create the Notion production brief').first().json:{id:p.notionId,url:p.notionUrl};\nif(!notion.id||!notion.url) throw new Error('Notion did not provide the production brief link.');\nconst board=$input.first().json.body;\nif(!Array.isArray(board)) throw new Error('Trello board response is unavailable.');\nconst matching=board.filter(x=>String(x.name||'').startsWith('['+p.key+']'));\nif(matching.length>1||matching[0]?.closed) throw new Error('Resolve duplicate or closed Trello cards for '+p.key);\nreturn [{json:{...p,notion,card:matching[0],description:'Production brief: '+notion.url+'\\n'+p.format+'\\n'+p.reason}}];"
      }
    },
    {
      "id": "70775694-1320-5116-940a-0643c8ca3c5b",
      "name": "Trello card is new",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        5650,
        -140
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "8923c100-8fc9-5b7b-bc2d-a50db2125328",
              "leftValue": "={{ !$json.card }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "ee29c88a-0a7d-50ed-a26e-3767da3710c4",
      "name": "Create the Trello production card",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        5890,
        -220
      ],
      "parameters": {
        "url": "https://api.trello.com/1/cards",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "trelloApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {idList:$(\"Creator settings\").first().json[\"Trello production list ID\"],name:$json.title,desc:$json.description} }}"
      }
    },
    {
      "id": "fd839023-1b09-55a8-88c8-f490756779f7",
      "name": "Build the approved publishing handoff",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        6130,
        -140
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const p=$('Find or prepare the production card').first().json;\nconst card=$('Create the Trello production card').isExecuted?$('Create the Trello production card').first().json:p.card;\nif(!card?.id) throw new Error('A production card is required for publishing writeback.');\nconst c=$('Creator settings').first().json;\nreturn [{json:{'Content ID':p.key,Status:'Draft',Title:'',Caption:'','Publish At':'','Drive File ID':'',\n  'Approved SHA256':'','Profile ID':c['Sprkly profile ID'],'Post ID':'','Live URL':'',Issue:'',\n  'Notion Brief':p.notion.url,'Recommended Format':p.format,'Recommendation Evidence':p.reason,\n  'Trello Card ID':card.id,'Trello Scheduled List ID':c['Trello scheduled list ID'],\n  'Trello Published List ID':c['Trello published list ID'],'Trello Failed List ID':c['Trello failed list ID'],'Tracker State':''}}];"
      }
    },
    {
      "id": "5319d457-16fc-545c-88bc-d4e38b186178",
      "name": "Create the weekly Calendar draft",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        6370,
        -140
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Creator settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "insertInNewColumn",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Calendar"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "Content ID"
          ],
          "schema": []
        }
      }
    },
    {
      "id": "a94f9ff4-23f2-5d8a-aaab-94be98785006",
      "name": "Brief email recipient set",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        6610,
        -140
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "7c99b746-795a-5cc8-9e74-2f74a77a5840",
              "leftValue": "={{ $(\"Creator settings\").first().json[\"Digest recipient\"].trim().length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "3897c024-ac43-5447-8b8a-d0f78667691b",
      "name": "Email the new brief and next action",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        6850,
        -180
      ],
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $(\"Creator settings\").first().json[\"Digest recipient\"] }}",
        "subject": "={{ 'Creator brief · '+$(\"Skip a brief already in production\").first().json.key }}",
        "emailType": "text",
        "message": "={{ 'Suggested format: '+$(\"Skip a brief already in production\").first().json.format+'\\n'+$(\"Skip a brief already in production\").first().json.reason+'\\n\\nReview the brief: '+$(\"Build the approved publishing handoff\").first().json[\"Notion Brief\"]+'\\nOpen the Calendar row to approve the finished clip.' }}",
        "options": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "f1f9811e-5695-4b07-8cba-dbf83954c1e3",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -670,
        408
      ],
      "parameters": {}
    },
    {
      "id": "3ad68eaf-dc80-4e1d-9e66-dfa775bc4918",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -450,
        408
      ],
      "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": "5961ef2e-1292-46c9-9de7-43291d7765af",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -230,
        408
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "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
          }
        ]
      ]
    },
    "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
          }
        ]
      ]
    },
    "Plan Monday at 8 AM": {
      "main": [
        [
          {
            "node": "Creator settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build this week’s brief": {
      "main": [
        [
          {
            "node": "Creator settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every 15 minutes": {
      "main": [
        [
          {
            "node": "Creator settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When this workflow's post goes live": {
      "main": [
        [
          {
            "node": "Creator settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Creator settings": {
      "main": [
        [
          {
            "node": "Publishing interval",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Publishing interval": {
      "main": [
        [
          {
            "node": "Ensure Calendar for publishing",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Publication event",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ensure Calendar for publishing": {
      "main": [
        [
          {
            "node": "Read content calendar",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Publication event": {
      "main": [
        [
          {
            "node": "Recover the publication event batch",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Validate planning settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Recover the publication event batch": {
      "main": [
        [
          {
            "node": "Build published log rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate planning settings": {
      "main": [
        [
          {
            "node": "Ensure Calendar for planning",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ensure Calendar for planning": {
      "main": [
        [
          {
            "node": "Ensure Creator Signals tab",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ensure Creator Signals tab": {
      "main": [
        [
          {
            "node": "Prepare YouTube watchlist requests",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare YouTube watchlist requests": {
      "main": [
        [
          {
            "node": "Read recent YouTube uploads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read recent YouTube uploads": {
      "main": [
        [
          {
            "node": "Collect video IDs in API batches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect video IDs in API batches": {
      "main": [
        [
          {
            "node": "Pull current YouTube metrics",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pull current YouTube metrics": {
      "main": [
        [
          {
            "node": "Score comparable posts and capture signals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Score comparable posts and capture signals": {
      "main": [
        [
          {
            "node": "Expand video snapshots",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand video snapshots": {
      "main": [
        [
          {
            "node": "Upsert date and video snapshots",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert date and video snapshots": {
      "main": [
        [
          {
            "node": "Read Calendar for existing brief",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Calendar for existing brief": {
      "main": [
        [
          {
            "node": "Skip a brief already in production",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skip a brief already in production": {
      "main": [
        [
          {
            "node": "Prepare the original production brief",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare the original production brief": {
      "main": [
        [
          {
            "node": "Find this week’s Notion brief",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find this week’s Notion brief": {
      "main": [
        [
          {
            "node": "Reuse or prepare the Notion brief",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reuse or prepare the Notion brief": {
      "main": [
        [
          {
            "node": "Notion brief is new",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notion brief is new": {
      "main": [
        [
          {
            "node": "Create the Notion production brief",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read Trello production board cards",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create the Notion production brief": {
      "main": [
        [
          {
            "node": "Read Trello production board cards",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Trello production board cards": {
      "main": [
        [
          {
            "node": "Find or prepare the production card",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find or prepare the production card": {
      "main": [
        [
          {
            "node": "Trello card is new",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trello card is new": {
      "main": [
        [
          {
            "node": "Create the Trello production card",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build the approved publishing handoff",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create the Trello production card": {
      "main": [
        [
          {
            "node": "Build the approved publishing handoff",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build the approved publishing handoff": {
      "main": [
        [
          {
            "node": "Create the weekly Calendar draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create the weekly Calendar draft": {
      "main": [
        [
          {
            "node": "Brief email recipient set",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Brief email recipient set": {
      "main": [
        [
          {
            "node": "Email the new brief and next action",
            "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",
    "saveDataSuccessExecution": "none",
    "saveManualExecutions": false
  },
  "pinData": {}
}
