{
  "name": "Video production desk",
  "nodes": [
    {
      "id": "cd83c34c-274c-47e5-865c-a8dc6c0a7001",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -870,
        -100
      ],
      "parameters": {
        "content": "## Video production desk\nChecks each video, thumbnail, caption and date on your Notion calendar, schedules the approved one, and keeps Trello and your sheet current.\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=video-production-desk\n- A Notion production calendar, a Drive folder for videos and a Trello board\n- Notion, Google Drive, Google Sheets and Trello logins\n- Gmail, only for the daily digest\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Start with a blank Google Sheet. The first run makes its own tabs.\n2. Fill **Pack settings**: sheet ID, production data source ID, Drive folder ID, sprkly profile ID, Trello board and list IDs.\n3. Add each login where a step asks. Use the same one in every step for that app. Set your time zone in Workflow settings.\n4. Failure alert: put your chat ID in **Write the failure alert** and your bot in **Send the failure alert**. Then in Workflow settings, set Error workflow to this workflow.\n\n### Test it\n- Click Test workflow with **Run the review now** picked.\n- The sheet gets its tabs and a dated report row. Only a Notion entry marked approved gets scheduled.",
        "height": 884,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "0002062d-9bb8-58fc-9d5a-d4239a516ae8",
      "name": "Scheduled review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 20
            }
          ]
        }
      }
    },
    {
      "id": "da9f41cb-cdd4-5f07-98ec-e46a62f25b5f",
      "name": "Run the review now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        210
      ],
      "parameters": {}
    },
    {
      "id": "02a23dac-fa22-5a16-b9b1-6f6713877190",
      "name": "Pack settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        230,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "4591be4a-af9d-5af2-917b-b4fd0822f306",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "57cca98a-94f1-53f3-8ee8-5f1bb64ccca4",
              "name": "Production data source ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "29ae0fcc-8aa7-5bc4-ba0f-8466a564dcd6",
              "name": "Drive root folder ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "f3db6e58-5bb7-54c8-acd2-9de16a5b690d",
              "name": "Sprkly profile ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "f26499b3-cb0c-592e-b2f1-d59567ba8500",
              "name": "Trello board ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "729d33d7-7ecc-5a2c-ad2e-e682941cdafc",
              "name": "Trello work list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "7b66a8ae-a0e7-57bd-98ac-2d83343edbc4",
              "name": "Digest recipient (optional)",
              "type": "string",
              "value": ""
            }
          ]
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "c28290c5-23fb-5651-98c2-0307c6e0620a",
      "name": "Check pack settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const required = [\"Spreadsheet ID\", \"Production data source ID\", \"Drive root folder ID\", \"Sprkly profile ID\", \"Trello board ID\", \"Trello work list ID\"];\nconst raw = $input.first().json;\nconst config = Object.fromEntries(Object.entries(raw).map(([key, value])=>[key,typeof value==='string'?value.trim():value]));\nconst missing = required.filter(key=>!config[key]);\nif (missing.length) throw new Error('Fill in Pack settings: '+missing.join(', '));\nfor(const key of ['Spreadsheet ID','Trello board ID','Trello work list ID','Drive root folder ID']){\n  if(config[key]&&!/^[A-Za-z0-9_-]+$/.test(config[key])) throw new Error(key+' must be an ID, without a URL.');\n}\nfor(const [key,value] of Object.entries(config)){\n  if(key.endsWith('data source ID')&&value&&!/^(?:[a-f0-9]{32}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/i.test(value)) throw new Error(key+' must be a Notion data source ID.');\n}\nif(config['Shopify shop domain']&&!/^[a-z0-9][a-z0-9-]*\\.myshopify\\.com$/i.test(config['Shopify shop domain'])) throw new Error('Use your shop-name.myshopify.com domain.');\nif(config['Digest recipient (optional)']&&!/^[^@\\s,]+@[^@\\s,]+\\.[^@\\s,]+$/.test(config['Digest recipient (optional)'])) throw new Error('Use one internal digest email address.');\nfor(const key of ['Stall after days','Review window days','Reminder lead days']){\n  if(config[key]!==undefined&&(!Number.isInteger(config[key])||config[key]<1||config[key]>59))throw new Error(key+' must be a whole number from 1 to 59.');\n}\nreturn [{json:config}];"
      }
    },
    {
      "id": "3dce32af-368b-5097-934d-86f0e2c4acbb",
      "name": "Inspect the workbook tabs",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        690,
        0
      ],
      "parameters": {
        "url": "={{ 'https://sheets.googleapis.com/v4/spreadsheets/'+$(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}",
        "method": "GET",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "sheets(properties(sheetId,title))"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "11a138c0-8b4d-5eb8-a1a9-23371b98cced",
      "name": "Plan missing tabs and headers",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const tabs = {\"Published Posts\": [\"Notion Page ID\", \"Post ID\", \"Sprkly Post ID\", \"Status\", \"Platform\", \"Account ID\", \"External ID\", \"Published At\", \"Live URL\", \"Issue\"], \"Video Production Desk Ledger\": [\"Work Key\", \"Title\", \"State\", \"Details\", \"Due\", \"Source URL\", \"Card ID\", \"Card URL\", \"Checked At\", \"Video URL\", \"Thumbnail URL\", \"Post ID\", \"Posting State\", \"Live URL\"], \"Video Production Desk Report\": [\"Report Date\", \"Completed\", \"Pending\", \"Blocked\", \"Overdue\", \"Attention\", \"Summary\", \"Checked At\"]};\nconst existing=$input.first().json.sheets;\nif(!Array.isArray(existing)) throw new Error('Sheets did not return a readable workbook.');\nconst titles=new Set(existing.map(s=>s.properties?.title));\nconst ids=new Set(existing.map(s=>s.properties?.sheetId));\nconst requests=[];\nlet id=621100;\nfor(const [title,columns] of Object.entries(tabs)){\n  if(titles.has(title)) continue;\n  while(ids.has(id)) id++;\n  const sheetId=id++;\n  requests.push({addSheet:{properties:{title,sheetId,gridProperties:{frozenRowCount:1,columnCount:Math.max(26,columns.length)}}}});\n  requests.push({updateCells:{start:{sheetId,rowIndex:0,columnIndex:0},rows:[{values:columns.map(stringValue=>({userEnteredValue:{stringValue},userEnteredFormat:{textFormat:{bold:true}}}))}],fields:'userEnteredValue,userEnteredFormat'}});\n}\nreturn [{json:{requests}}];"
      }
    },
    {
      "id": "933e5f87-7388-5b68-a84b-fbdc2a0af7fb",
      "name": "Workbook needs tabs",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1150,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "02ce90a5-ca1b-5a13-a7ed-3ec15b4a561b",
              "leftValue": "={{ $json.requests.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "5310e889-2c7e-5d05-baa8-5e3172c75dad",
      "name": "Create tabs and headers together",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1380,
        -100
      ],
      "parameters": {
        "url": "={{ 'https://sheets.googleapis.com/v4/spreadsheets/'+$(\"Check pack settings\").first().json[\"Spreadsheet ID\"]+':batchUpdate' }}",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {requests:$json.requests} }}"
      }
    },
    {
      "id": "92556b39-3d2c-5f24-8698-2a9ab056a475",
      "name": "Read the saved ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        0,
        520
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}"
        },
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Video Production Desk Ledger"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "200879b5-3da6-5d3f-a2ea-ea39db45cb40",
      "name": "Set up the source",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1070,
        305
      ],
      "parameters": {
        "content": "## Set up the source\n\nNotion properties · **Video ID**, **Thumbnail ID**, **Caption** text, **Publish At** date with a time, **Approved** checkbox. Use one video-capable Sprkly profile. The thumbnail is checked in Drive as a production requirement.",
        "width": 966,
        "height": 145,
        "color": 4
      }
    },
    {
      "id": "425a0160-c1c4-583e-a6c9-e8dc0f9102c6",
      "name": "Read the Notion production calendar",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        230,
        520
      ],
      "parameters": {
        "url": "={{ 'https://api.notion.com/v1/data_sources/'+$(\"Check pack settings\").first().json[\"Production data source ID\"]+'/query' }}",
        "method": "POST",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "body",
                    "name": "start_cursor",
                    "value": "={{ $response.body?.next_cursor || undefined }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ $response.body.has_more !== true }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 400
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "notionApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {page_size:100} }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "2025-09-03"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "2b48defb-b430-590a-8be6-15be417b4362",
      "name": "Read the production Drive folder",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        460,
        520
      ],
      "parameters": {
        "url": "https://www.googleapis.com/drive/v3/files",
        "method": "GET",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "qs",
                    "name": "pageToken",
                    "value": "={{ $response.body?.nextPageToken || undefined }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !$response.body.nextPageToken }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 400
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"'\"+$(\"Check pack settings\").first().json[\"Drive root folder ID\"]+\"' in parents and trashed = false\" }}"
            },
            {
              "name": "pageSize",
              "value": "1000"
            },
            {
              "name": "fields",
              "value": "nextPageToken,incompleteSearch,files(id,name,mimeType,webViewLink,parents,md5Checksum,appProperties,description,trashed)"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            },
            {
              "name": "includeItemsFromAllDrives",
              "value": "true"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "709fd506-e1a4-5ed9-bf95-3d6f5fed59be",
      "name": "Read recent Sprkly receipts",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        690,
        520
      ],
      "parameters": {
        "resource": "post",
        "operation": "getAll",
        "returnAll": true,
        "filters": {
          "updatedAfter": "={{ $now.minus({days:14}).toISO() }}"
        },
        "simplify": true
      },
      "alwaysOutputData": true
    },
    {
      "id": "3c1ae312-2066-5ece-870e-984edfe531af",
      "name": "Collect known Sprkly post IDs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        520
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const recent=new Set($('Read recent Sprkly receipts').all().map(i=>String(i.json.id)));\nconst ids=$('Read the saved ledger').all().filter(i=>!recent.has(String(i.json['Post ID']))&&\n  (!['posted','published'].includes(i.json['Posting State'])||!i.json['Live URL'])).map(i=>i.json['Post ID']);\nconst all=[...new Set(ids.map(x=>String(x||'').trim()).filter(Boolean))].sort();\nreturn [{json:{ids:all}}];"
      }
    },
    {
      "id": "3f7b5c8d-142e-5fcb-a047-dfcce7de0c39",
      "name": "There are post receipts to check",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1150,
        520
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "b5d651eb-da1d-5097-9104-722861fc7f1f",
              "leftValue": "={{ $json.ids.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "16a311e2-89d0-52d2-85e1-e7a35e5c5d8e",
      "name": "Expand known post IDs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1380,
        520
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.ids.map(id=>({json:{id}}));"
      }
    },
    {
      "id": "4fd5ebeb-bc73-50c2-a149-e4facaa74d11",
      "name": "Read tracked Sprkly posts",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        0,
        770
      ],
      "parameters": {
        "resource": "post",
        "operation": "get",
        "postId": "={{ $json.id }}",
        "simplify": true
      }
    },
    {
      "id": "65127746-ecce-58de-bda4-0f27af72b8b6",
      "name": "Continue to work review",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        230,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{ready:true}}];"
      }
    },
    {
      "id": "ba1e5b71-6bee-5899-8ff1-dd9a197cef7a",
      "name": "Decide which work needs attention",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const config=$('Check pack settings').first().json;\nconst today=$now.toISODate();\nconst stamp=$now.toISO();\nconst str=value=>String(value??'').trim();\nconst lower=value=>str(value).toLowerCase();\nconst rows=(name,key)=>$(name).all().map(x=>x.json).filter(x=>x[key]!==undefined && str(x[key])!=='');\nconst yes=value=>['true','yes','1','approved'].includes(lower(value));\nconst validId=value=>/^[A-Za-z0-9_-]+$/.test(str(value));\nconst publicUrl=value=>/^https:\\/\\/[a-z0-9][\\w.-]*\\.[a-z]{2,}(?:[:/?#]|$)/i.test(str(value))?str(value):'';\nconst email=value=>/^[^@\\s,]+@[^@\\s,]+\\.[^@\\s,]+$/.test(str(value))?str(value):'';\nconst prior=new Map(rows('Read the saved ledger','Work Key').map(row=>[str(row['Work Key']),row]));\nfunction unique(values,label){\n  const keys=values.map(lower);\n  if(new Set(keys).size!==keys.length) throw new Error(label+' must be unique.');\n}\nfunction notion(name){\n  const pages=$(name).all().map(i=>i.json);\n  if(!pages.length||pages.some(p=>!Array.isArray(p.results))||pages.at(-1).has_more) throw new Error('Notion read was incomplete. Try again before updating work.');\n  return pages.flatMap(p=>p.results).filter(p=>p.object==='page'&&!p.archived&&!p.in_trash);\n}\nfunction property(page,key){\n  const p=page.properties?.[key];\n  if(!p)return '';\n  const v=p[p.type];\n  if(p.type==='title'||p.type==='rich_text') return (v||[]).map(t=>t.plain_text??t.text?.content??'').join('');\n  if(p.type==='select'||p.type==='status') return v?.name??'';\n  if(p.type==='date') return v?.start??'';\n  return v??'';\n}\nfunction titleOf(page){\n  const title=Object.keys(page.properties||{}).find(key=>page.properties[key].type==='title');\n  return str(property(page,title))||'Untitled';\n}\nfunction drive(name){\n  const pages=$(name).all().map(i=>i.json);\n  if(!pages.length||pages.some(p=>p.incompleteSearch||!Array.isArray(p.files))||pages.at(-1).nextPageToken) throw new Error('Drive returned an incomplete listing.');\n  return pages.flatMap(p=>p.files);\n}\nfunction shop(name){\n  const pages=$(name).all().map(i=>i.json);\n  const error=pages.find(p=>p.errors?.length);\n  if(error) throw new Error('Shopify GraphQL: '+error.errors.map(x=>x.message).join(', '));\n  if(!pages.length||pages.some(p=>!p.data?.connection||!Array.isArray(p.data.connection.nodes))||pages.at(-1).data.connection.pageInfo?.hasNextPage) throw new Error('Shopify returned an incomplete list.');\n  return pages.flatMap(p=>p.data.connection.nodes);\n}\nconst dueDate=value=>/^\\d{4}-\\d{2}-\\d{2}/.test(str(value))?str(value).slice(0,10):'';\nconst driveLink=f=>f?.webViewLink||(f?.id?'https://drive.google.com/open?id='+encodeURIComponent(f.id):'');\nconst money=(n,c)=>Number.isFinite(n)?n.toFixed(2)+' '+c:'';\nconst shopLink=(resource,id)=>'https://'+config['Shopify shop domain']+'/admin/'+resource+'/'+str(id).split('/').at(-1);\nfunction job(key,title,state,details,due='',url='',extra={},track=true){\n  return {key:str(key),title:str(title),state,details:str(details),due:str(due),url:str(url),extra,track};\n}\nconst result=(jobs,summary='',more={})=>[{json:{jobs,summary,...more}}];\n\nfunction receipts(prefix){\n  const history=$('Read recent Sprkly receipts').all().map(i=>i.json);\n  const tracked=$('Read tracked Sprkly posts').isExecuted?$('Read tracked Sprkly posts').all().map(i=>i.json):[];\n  const byId=new Map([...history,...tracked].filter(p=>p.id).map(p=>[str(p.id),p]));\n  const byKey=new Map();\n  for(const post of byId.values()){\n    let key=str(post.externalId);\n    const suffix=':'+post.platforms?.[0]+':'+post.profileIds?.[0];\n    if(post.platforms?.[0]&&post.profileIds?.[0]&&key.endsWith(suffix))key=key.slice(0,-suffix.length);\n    if(!key.startsWith(prefix+'-'))continue;\n    if(byKey.has(key)&&byKey.get(key).id!==post.id)throw new Error('More than one Sprkly post shares external ID '+key);\n    byKey.set(key,post);\n  }\n  return (key,id)=>byId.get(id)||byKey.get(prefix+'-'+key);\n}\n\nconst files=new Map(drive('Read the production Drive folder').map(f=>[f.id,f]));\nconst findReceipt=receipts('video');\nconst jobs=[];\nconst candidates=[];\nfor(const page of notion('Read the Notion production calendar')){\n  const p=n=>property(page,n), key=page.id;\n  const video=files.get(str(p('Video ID'))), image=files.get(str(p('Thumbnail ID')));\n  const caption=str(p('Caption')), scheduled=str(p('Publish At')), approved=p('Approved')===true;\n  const old=prior.get(key)||{}, post=findReceipt(key,str(old['Post ID'])), id=str(post?.id||old['Post ID']);\n  const published=['posted','published'].includes(lower(post?.status||old['Posting State']))&&!post?.deleted;\n  const missing=[!video?.mimeType?.startsWith('video/')?'video file':'',!image?.mimeType?.startsWith('image/')?'thumbnail':'',!caption?'caption':'',!Number.isFinite(Date.parse(scheduled))?'valid publish date':''].filter(Boolean);\n  const expired=Number.isFinite(Date.parse(scheduled))&&Date.parse(scheduled)<$now.plus({minutes:5}).toMillis();\n  const details=published?'Confirmed live':id?(post?.deleted?'Post was deleted in Sprkly':str(post?.status)||'Checking Sprkly receipt'):missing.length?'Missing '+missing.join(', '):!approved?'Ready for approval':expired?'Choose a publish time at least five minutes ahead':'Ready to schedule';\n  const state=published?'Completed':post?.deleted||lower(post?.status)==='failed'||(!id&&(missing.length||expired))?'Blocked':'Pending';\n  const extra={'Video URL':driveLink(video),'Thumbnail URL':driveLink(image),'Post ID':id,'Posting State':str(post?.status||old['Posting State']),'Live URL':str(post?.permalink||old['Live URL'])};\n  // Thumbnail presence is a production check. Platform-specific thumbnail upload is not performed.\n  jobs.push(job(key,titleOf(page),state,details,dueDate(scheduled),page.url,extra));\n  if(!id&&approved&&!missing.length&&!expired) candidates.push({key,title:titleOf(page),fileId:video.id,caption,scheduled:new Date(scheduled).toISOString()});\n}\ncandidates.sort((a,b)=>a.scheduled.localeCompare(b.scheduled)||a.key.localeCompare(b.key));\nreturn result(jobs,'Production kit checked against Drive and confirmed post receipts.',{candidate:candidates[0]||null});"
      }
    },
    {
      "id": "88244383-ac2b-5bf7-a2a3-8db387e63af8",
      "name": "An approved post is ready",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        690,
        770
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "5202ce83-a614-5cc0-a83f-6cd3b63107f8",
              "leftValue": "={{ Boolean($json.candidate) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "b27f65f9-260f-53f1-838c-ef29373993c3",
      "name": "Prepare the one approved post",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const c=$json.candidate;return [{json:{...c,externalId:\"video-\"+c.key}}];"
      }
    },
    {
      "id": "c91f07a1-10d2-5196-8443-5751656de740",
      "name": "Download the approved Drive asset",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        1150,
        770
      ],
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.fileId }}"
        },
        "options": {}
      }
    },
    {
      "id": "d6310590-85ab-599d-84a1-25b5b5bfdb40",
      "name": "Upload the approved media",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        1380,
        770
      ],
      "parameters": {
        "resource": "media",
        "operation": "upload",
        "binaryPropertyName": "data"
      }
    },
    {
      "id": "5b71056d-87a9-535c-8533-e33784340ca5",
      "name": "Schedule the approved post",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        0,
        1020
      ],
      "parameters": {
        "resource": "post",
        "operation": "create",
        "accountMode": "list",
        "profileIds": "={{ [$(\"Check pack settings\").first().json[\"Sprkly profile ID\"]] }}",
        "caption": "={{ $(\"Prepare the one approved post\").first().json[\"caption\"] }}",
        "scheduledTime": "={{ $(\"Prepare the one approved post\").first().json[\"scheduled\"] }}",
        "mediaIds": "={{ $json.mediaId }}",
        "postNow": false,
        "output": "resultRow",
        "additionalFields": {
          "title": "={{ $(\"Prepare the one approved post\").first().json[\"title\"] }}",
          "externalId": "={{ $(\"Prepare the one approved post\").first().json[\"externalId\"] }}",
          "requireExternalId": true
        }
      }
    },
    {
      "id": "2436cb2e-18c1-5845-82a1-6730f65fd01f",
      "name": "Apply the scheduling result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        230,
        1020
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$(\"Decide which work needs attention\").first().json;\nif($('Schedule the approved post').isExecuted){\n  const sent=$('Schedule the approved post').first().json;\n  const work=data.jobs.find(j=>j.key===data.candidate.key);\n  if(!work)throw new Error('Could not match scheduled post to input record.');\n  if(sent.ok&&sent.postId){\n    work.extra['Post ID']=sent.postId;\n    work.extra['Posting State']=sent.status==='Failed'?'failed':'scheduled';\n    work.state=sent.status==='Failed'?'Blocked':'Pending';\n    work.details=sent.status==='Failed'?'Sprkly reported a publishing failure':'Scheduled · awaiting a confirmed live receipt';\n  }else{\n    work.state='Blocked';work.details=String(sent.error||'Sprkly did not confirm a post ID.').slice(0,500);\n  }\n}\nreturn [{json:data}];"
      }
    },
    {
      "id": "9df59486-334d-5a3e-bf4a-b96bfb9e1dfe",
      "name": "Collect confirmed live posts",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        1250
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$(\"Apply the scheduling result\").first().json;\nconst recent=$('Read recent Sprkly receipts').all().map(i=>i.json);\nconst tracked=$('Read tracked Sprkly posts').isExecuted?$('Read tracked Sprkly posts').all().map(i=>i.json):[];\nconst ids=new Map(data.jobs.filter(r=>r.extra['Post ID']).map(r=>[String(r.extra['Post ID']),r.key]));\nconst posts=new Map([...recent,...tracked].filter(p=>ids.has(String(p.id))).map(p=>[String(p.id),p]));\nconst rows=[...posts.values()].filter(p=>['posted','published'].includes(p.status)&&p.id&&!p.deleted).map(p=>({\n  'Notion Page ID':ids.get(String(p.id))||'','Post ID':String(p.id),'Sprkly Post ID':String(p.id),Status:'Published',\n  Platform:(p.platforms||[]).join(', '),'Account ID':(p.profileIds||[]).join(', '),'External ID':p.externalId||'',\n  'Published At':p.publishedAt||'','Live URL':p.permalink||'',Issue:''\n}));\nreturn rows.map(json=>({json}));"
      }
    },
    {
      "id": "16da8d1e-d261-521b-8a6b-e0bb123de47c",
      "name": "Log confirmed publication by post ID",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1130,
        1250
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}"
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "insertInNewColumn",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Published Posts"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "Post ID"
          ],
          "schema": []
        }
      }
    },
    {
      "id": "522c2bc8-1d25-5881-93cb-189382f5a8e3",
      "name": "Prepare tracker updates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const decisionNode = \"Apply the scheduling result\";\nconst prefix = \"[sprkly:video-production-desk:\";\nconst cardsNode = \"Read the Trello board\";\nconst data=$(decisionNode).first().json;\nconst config=$('Check pack settings').first().json;\nconst prior=new Map($('Read the saved ledger').all().filter(i=>i.json['Work Key']).map(i=>[String(i.json['Work Key']),i.json]));\nconst cards=cardsNode?$(cardsNode).first().json.body:[];\nif(!Array.isArray(cards)) throw new Error('Trello did not return a card list.');\nconst byId=new Map(cards.map(c=>[c.id,c]));\nconst byMark=new Map();\nfor(const c of cards){\n  const text=String(c.desc||'');\n  if(c.idList!==config['Trello work list ID']&&!text.includes(prefix))continue;\n  const marker=text.split('\\n').find(line=>line.startsWith(prefix)&&line.endsWith(']'));\n  if(!marker)continue;\n  if(byMark.has(marker)) throw new Error('Two Trello cards share '+marker+'. Keep one workflow marker.');\n  byMark.set(marker,c);\n}\nconst writes=[], records=[];\nconst seen=new Set();\nfor(const j of data.jobs){\n  if(!j.key||seen.has(j.key)) throw new Error('Duplicate or missing work key: '+j.key);\n  seen.add(j.key);\n  const old=prior.get(j.key)||{};\n  const marker=prefix+encodeURIComponent(j.key)+']';\n  const finish='[/sprkly-work]';\n  let card=byId.get(old['Card ID'])||byMark.get(marker);\n  const done=j.cardDone??j.state==='Completed';\n  const changes={};\n  if(j.track&&cardsNode&&(card||j.forceCard||(!done&&['Pending','Blocked'].includes(j.state)))){\n    if(!card&&old['Card ID']) throw new Error('Previously tracked Trello card was not found for '+j.key+'. Check the board or restore the card.');\n    const title=j.title.slice(0,240);\n    const block=[marker,'State: '+j.state,j.details.slice(0,2500),j.url,finish].filter(Boolean).join('\\n');\n    const oldDesc=String(card?.desc||'');\n    const start=oldDesc.indexOf(marker);\n    const end=start>=0?oldDesc.indexOf(finish,start):-1;\n    const desc=start>=0&&end>=0?oldDesc.slice(0,start)+block+oldDesc.slice(end+finish.length):(oldDesc?oldDesc+'\\n\\n':'')+block;\n    const date=/^\\d{4}-\\d{2}-\\d{2}$/.test(j.due)?j.due+'T17:00:00.000Z':j.due;\n    const due=date&&Number.isFinite(Date.parse(date))?new Date(date).toISOString():null;\n    if(!card)Object.assign(changes,{name:title,desc,idList:config['Trello work list ID'],dueComplete:done,...(due?{due}:{})});\n    else if(!card.closed){\n      if(card.desc!==desc)changes.desc=desc;\n      if(j.cardDone!==false&&!!card.dueComplete!==done)changes.dueComplete=done;\n      if(due&&Date.parse(card.due)!==Date.parse(due))changes.due=due;\n    }\n    if(Object.keys(changes).length) writes.push({key:j.key,cardId:card?.id||'',payload:changes});\n  }\n  records.push({job:j,cardId:card?.id||old['Card ID']||'',cardUrl:card?.shortUrl||old['Card URL']||'',marker});\n}\nreturn [{json:{...data,writes,records}}];"
      }
    },
    {
      "id": "1303d351-168a-563f-8b5d-dabf9ee27201",
      "name": "Read the Trello board",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -230,
        1380
      ],
      "parameters": {
        "url": "={{ 'https://api.trello.com/1/boards/'+$(\"Check pack settings\").first().json[\"Trello board ID\"]+'/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,desc,idList,due,dueComplete,closed,shortUrl"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "c27ed52f-9001-5c7f-87e4-fbec5af4828e",
      "name": "Trello needs changes",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        220,
        1380
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ddb86681-e1b4-5be1-b62b-44b0f546b411",
              "leftValue": "={{ $json.writes.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "83fa25a6-f48c-51df-9ab7-813e3140a85b",
      "name": "Expand changed cards",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        1270
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.writes.map(json=>({json}));"
      }
    },
    {
      "id": "a1619cdb-72cf-5a2d-b7b7-83ae0fc16037",
      "name": "Create or update work cards",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        1270
      ],
      "parameters": {
        "url": "={{ 'https://api.trello.com/1/cards'+($json.cardId?'/'+$json.cardId:'') }}",
        "method": "={{ $json.cardId?'PUT':'POST' }}",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "trelloApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.payload }}"
      }
    },
    {
      "id": "300238de-bd31-5473-a80a-c48d183f6606",
      "name": "Prepare ledger rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        1380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const plan=$('Prepare tracker updates').first().json;\nconst changed=new Map();\nif(plan.writes.length){\n  const responses=$input.all().map(i=>i.json);\n  for(const card of responses){\n    if(!card.id)throw new Error('A Trello update did not return a card ID.');\n    const rec=plan.records.find(r=>r.cardId===card.id||(card.desc||'').includes(r.marker));\n    if(!rec)throw new Error('Could not match updated Trello card '+card.id+' to a work record.');\n    changed.set(rec.job.key,card);\n  }\n  if(changed.size!==plan.writes.length)throw new Error('Trello returned fewer cards than planned.');\n}\nconst rows=plan.records.map(r=>{\n  const j=r.job, card=changed.get(j.key);\n  return {'Work Key':j.key,Title:j.title,State:j.state,Details:j.details,Due:j.due,'Source URL':j.url,\n    'Card ID':card?.id||r.cardId,'Card URL':card?.shortUrl||r.cardUrl,'Checked At':$now.toISO(),...j.extra};\n});\nreturn [{json:{rows,summary:plan.summary}}];"
      }
    },
    {
      "id": "16f6bfa5-519c-57ad-bee5-a9775dc9efe7",
      "name": "Ledger has work records",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1100,
        1380
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "231322c7-ba33-50c9-a1f8-cb4d8d929048",
              "leftValue": "={{ $json.rows.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "4b8b980e-a67d-591d-9188-62b5e2f86a2a",
      "name": "Expand work records",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        1270
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.rows.map(json=>({json}));"
      }
    },
    {
      "id": "c5b6370d-c773-5134-8cb2-20170ffcecd6",
      "name": "Update the work ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1540,
        1270
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}"
        },
        "options": {
          "cellFormat": "RAW",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Video Production Desk Ledger"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Work Key": "={{ $json[\"Work Key\"] ?? \"\" }}",
            "Title": "={{ $json[\"Title\"] ?? \"\" }}",
            "State": "={{ $json[\"State\"] ?? \"\" }}",
            "Details": "={{ $json[\"Details\"] ?? \"\" }}",
            "Due": "={{ $json[\"Due\"] ?? \"\" }}",
            "Source URL": "={{ $json[\"Source URL\"] ?? \"\" }}",
            "Card ID": "={{ $json[\"Card ID\"] ?? \"\" }}",
            "Card URL": "={{ $json[\"Card URL\"] ?? \"\" }}",
            "Checked At": "={{ $json[\"Checked At\"] ?? \"\" }}",
            "Video URL": "={{ $json[\"Video URL\"] ?? \"\" }}",
            "Thumbnail URL": "={{ $json[\"Thumbnail URL\"] ?? \"\" }}",
            "Post ID": "={{ $json[\"Post ID\"] ?? \"\" }}",
            "Posting State": "={{ $json[\"Posting State\"] ?? \"\" }}",
            "Live URL": "={{ $json[\"Live URL\"] ?? \"\" }}"
          },
          "matchingColumns": [
            "Work Key"
          ],
          "schema": []
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "806ea741-bff8-5f63-8251-9f53fc26872b",
      "name": "Summarize completed and pending work",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1700
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const title = \"Video Production Desk\";\nconst data=$('Prepare ledger rows').first().json;\nconst today=$now.toISODate();\nconst completed=data.rows.filter(r=>r.State==='Completed').length;\nconst pending=data.rows.filter(r=>r.State==='Pending').length;\nconst blocked=data.rows.filter(r=>r.State==='Blocked').length;\nconst overdue=data.rows.filter(r=>r.State!=='Completed'&&r.Due&&r.Due.slice(0,10)<today).length;\nconst attention=data.rows.filter(r=>r.State==='Blocked'||(r.State==='Pending'&&r.Due&&r.Due.slice(0,10)<today));\nconst lines=attention.slice(0,20).map(r=>'- '+r.Title+' · '+r.Details+(r['Card URL']?'\\n  '+r['Card URL']:''));\nconst summary='Completed '+completed+' · Pending '+pending+' · Blocked '+blocked+' · Overdue '+overdue;\nreturn [{json:{'Report Date':today,Completed:completed,Pending:pending,Blocked:blocked,Overdue:overdue,Attention:attention.length,Summary:data.summary||summary,\n  'Checked At':$now.toISO(),digestSubject:title+' ['+today+']',digestBody:[summary,data.summary,...lines].filter(Boolean).join('\\n\\n')}}];"
      }
    },
    {
      "id": "f890267f-ccdc-59e1-b096-459ee7b110de",
      "name": "Save the dated work report",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        220,
        1700
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}"
        },
        "options": {
          "cellFormat": "RAW",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Video Production Desk Report"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Report Date": "={{ $json[\"Report Date\"] ?? \"\" }}",
            "Completed": "={{ $json[\"Completed\"] ?? \"\" }}",
            "Pending": "={{ $json[\"Pending\"] ?? \"\" }}",
            "Blocked": "={{ $json[\"Blocked\"] ?? \"\" }}",
            "Overdue": "={{ $json[\"Overdue\"] ?? \"\" }}",
            "Attention": "={{ $json[\"Attention\"] ?? \"\" }}",
            "Summary": "={{ $json[\"Summary\"] ?? \"\" }}",
            "Checked At": "={{ $json[\"Checked At\"] ?? \"\" }}"
          },
          "matchingColumns": [
            "Report Date"
          ],
          "schema": []
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "8d05e973-ab64-57c4-b42a-081180b7b2b7",
      "name": "A digest recipient is set",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        440,
        1700
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "b1f40e65-252d-5e05-b8a3-7dd5b50ac52b",
              "leftValue": "={{ Boolean($(\"Check pack settings\").first().json[\"Digest recipient (optional)\"]) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "7121869f-272f-5142-967f-e56013942fda",
      "name": "Check Gmail for today’s digest",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        1700
      ],
      "parameters": {
        "url": "https://gmail.googleapis.com/gmail/v1/users/me/messages",
        "method": "GET",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "gmailOAuth2",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ 'in:sent subject:\"'+ $('Summarize completed and pending work').first().json.digestSubject+'\"' }}"
            },
            {
              "name": "maxResults",
              "value": "1"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "c651b1b7-84a4-5cad-85a8-67b7641baaee",
      "name": "Today’s digest is new",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        880,
        1700
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "fede0cfa-daa5-5fb4-b668-e82f475405bb",
              "leftValue": "={{ !$json.messages?.length }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "9650d986-b0d7-5f8c-8c2f-220e99a6fb81",
      "name": "Email the internal work digest",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1100,
        1700
      ],
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $(\"Check pack settings\").first().json[\"Digest recipient (optional)\"] }}",
        "subject": "={{ $('Summarize completed and pending work').first().json.digestSubject }}",
        "emailType": "text",
        "message": "={{ $('Summarize completed and pending work').first().json.digestBody }}",
        "options": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "df542cee-abea-5440-b9e4-42c1be5316f5",
      "name": "Work ledger and daily report",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -90,
        1555
      ],
      "parameters": {
        "content": "## Work ledger and daily report\n\nThe ledger records completed, pending and blocked work with source links. The report stores one snapshot per day. Trello cards are matched by stable work key. Existing descriptions outside the workflow section stay editable. An optional Gmail digest uses one subject per workflow per day.",
        "width": 1315,
        "height": 117,
        "color": 6
      }
    },
    {
      "id": "1dd9dc49-4680-4fe2-ba5c-f4a20c39bfe5",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -830,
        864
      ],
      "parameters": {}
    },
    {
      "id": "e7c391d3-b71c-4cd7-aad6-9eb6dacaf4e7",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -610,
        864
      ],
      "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": "4b64b726-27b1-459c-ad41-62e3477b0a7c",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -390,
        864
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Scheduled review": {
      "main": [
        [
          {
            "node": "Pack settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pack settings": {
      "main": [
        [
          {
            "node": "Check pack settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check pack settings": {
      "main": [
        [
          {
            "node": "Inspect the workbook tabs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inspect the workbook tabs": {
      "main": [
        [
          {
            "node": "Plan missing tabs and headers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Plan missing tabs and headers": {
      "main": [
        [
          {
            "node": "Workbook needs tabs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run the review now": {
      "main": [
        [
          {
            "node": "Pack settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workbook needs tabs": {
      "main": [
        [
          {
            "node": "Create tabs and headers together",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read the saved ledger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create tabs and headers together": {
      "main": [
        [
          {
            "node": "Read the saved ledger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the saved ledger": {
      "main": [
        [
          {
            "node": "Read the Notion production calendar",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the Notion production calendar": {
      "main": [
        [
          {
            "node": "Read the production Drive folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the production Drive folder": {
      "main": [
        [
          {
            "node": "Read recent Sprkly receipts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read recent Sprkly receipts": {
      "main": [
        [
          {
            "node": "Collect known Sprkly post IDs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect known Sprkly post IDs": {
      "main": [
        [
          {
            "node": "There are post receipts to check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "There are post receipts to check": {
      "main": [
        [
          {
            "node": "Expand known post IDs",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Continue to work review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand known post IDs": {
      "main": [
        [
          {
            "node": "Read tracked Sprkly posts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read tracked Sprkly posts": {
      "main": [
        [
          {
            "node": "Continue to work review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Continue to work review": {
      "main": [
        [
          {
            "node": "Decide which work needs attention",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide which work needs attention": {
      "main": [
        [
          {
            "node": "An approved post is ready",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "An approved post is ready": {
      "main": [
        [
          {
            "node": "Prepare the one approved post",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Apply the scheduling result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare the one approved post": {
      "main": [
        [
          {
            "node": "Download the approved Drive asset",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download the approved Drive asset": {
      "main": [
        [
          {
            "node": "Upload the approved media",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload the approved media": {
      "main": [
        [
          {
            "node": "Schedule the approved post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule the approved post": {
      "main": [
        [
          {
            "node": "Apply the scheduling result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply the scheduling result": {
      "main": [
        [
          {
            "node": "Collect confirmed live posts",
            "type": "main",
            "index": 0
          },
          {
            "node": "Read the Trello board",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect confirmed live posts": {
      "main": [
        [
          {
            "node": "Log confirmed publication by post ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the Trello board": {
      "main": [
        [
          {
            "node": "Prepare tracker updates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare tracker updates": {
      "main": [
        [
          {
            "node": "Trello needs changes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trello needs changes": {
      "main": [
        [
          {
            "node": "Expand changed cards",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare ledger rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand changed cards": {
      "main": [
        [
          {
            "node": "Create or update work cards",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create or update work cards": {
      "main": [
        [
          {
            "node": "Prepare ledger rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare ledger rows": {
      "main": [
        [
          {
            "node": "Ledger has work records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ledger has work records": {
      "main": [
        [
          {
            "node": "Expand work records",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Summarize completed and pending work",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand work records": {
      "main": [
        [
          {
            "node": "Update the work ledger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update the work ledger": {
      "main": [
        [
          {
            "node": "Summarize completed and pending work",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Summarize completed and pending work": {
      "main": [
        [
          {
            "node": "Save the dated work report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save the dated work report": {
      "main": [
        [
          {
            "node": "A digest recipient is set",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "A digest recipient is set": {
      "main": [
        [
          {
            "node": "Check Gmail for today’s digest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Gmail for today’s digest": {
      "main": [
        [
          {
            "node": "Today’s digest is new",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Today’s digest is new": {
      "main": [
        [
          {
            "node": "Email the internal work digest",
            "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": {}
}
