{
  "name": "Product launch desk",
  "nodes": [
    {
      "id": "4c1b0f85-9d69-4525-8c91-18971c1ba936",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -870,
        -100
      ],
      "parameters": {
        "content": "## Product launch desk\nChecks stock, store page and creative before a launch, schedules the approved post, and saves Shopify order counts at 24 and 72 hours.\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=product-launch-desk\n- A Shopify admin token that can read products and orders\n- A Notion launch calendar, a Drive folder for creative and a Trello board\n- Notion, Google Drive, Google Sheets and Trello logins. Gmail, only for the 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, Shopify shop domain, launch 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 an approved launch gets scheduled.",
        "height": 910,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "87194c22-b17f-5d55-aee7-f329a26d994c",
      "name": "Scheduled review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 30
            }
          ]
        }
      }
    },
    {
      "id": "63640785-10dc-5877-b815-dab84c8a01fe",
      "name": "Run the review now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        210
      ],
      "parameters": {}
    },
    {
      "id": "3794c732-38b8-5772-a36a-de26af7b9182",
      "name": "Pack settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        230,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b0fbac59-b6b3-58b0-9c47-ce7d0851a13a",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "8a7e9158-2f96-556a-a99b-873c41f91c4b",
              "name": "Shopify shop domain",
              "type": "string",
              "value": ""
            },
            {
              "id": "06084868-1bb8-5d79-9cb1-f5309b9dde07",
              "name": "Launch data source ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "da07e739-0a31-5362-b4ff-11cb38411ebe",
              "name": "Drive root folder ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "d5142027-65cc-534c-b1fe-754ed6c79807",
              "name": "Sprkly profile ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "ce0ea847-6929-54d1-96df-547876f90e0a",
              "name": "Trello board ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "cb24fa2b-a193-5f91-bdae-755628fbbb38",
              "name": "Trello work list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "e15aae5c-f907-5ab0-8cef-95d120379aee",
              "name": "Digest recipient (optional)",
              "type": "string",
              "value": ""
            }
          ]
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "dbb80b75-14de-52df-8124-ed87dad44841",
      "name": "Check pack settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const required = [\"Spreadsheet ID\", \"Shopify shop domain\", \"Launch 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": "e4eb6685-747b-5b40-8f84-583760ac42c8",
      "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": "4cc82b5b-2a76-5d1d-ba01-1d9b9d83e092",
      "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\"], \"Product Launch Desk Ledger\": [\"Work Key\", \"Title\", \"State\", \"Details\", \"Due\", \"Source URL\", \"Card ID\", \"Card URL\", \"Checked At\", \"Shopify Product ID\", \"Campaign\", \"Product URL\", \"Creative URL\", \"Post ID\", \"Posting State\", \"Live URL\", \"Published At\", \"Orders 24h\", \"Orders 72h\"], \"Product Launch 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": "f31dc1ed-a0d1-52d0-b2b7-9dece824bd15",
      "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": "d7261485-e654-5d2a-9b4d-b352df212b8a",
              "leftValue": "={{ $json.requests.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "70b19acd-3d67-5c9c-b11f-909fa1ecca1f",
      "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": "a41c9c43-3876-5acb-bce5-21121e42ab33",
      "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": "Product Launch Desk Ledger"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "8dbaf6a0-23b3-5c58-a07b-ee130a024d44",
      "name": "Set up the source",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1070,
        305
      ],
      "parameters": {
        "content": "## Set up the source\n\nNotion properties · **Shopify Product ID**, **Creative ID**, **Caption** text, **Launch At** date with time, **Approved** checkbox. Shopify scopes · **read_products** and **read_orders**. The product needs a storefront URL and available stock. Use an image-capable Sprkly profile.",
        "width": 966,
        "height": 145,
        "color": 4
      }
    },
    {
      "id": "ec08d5a9-d693-5bab-9e8d-81aabe7ad5fc",
      "name": "Read the Notion launch 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[\"Launch 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": "c2bb013e-2793-554d-9dce-1315d0d9fbab",
      "name": "Read the launch 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": "957a9385-17f7-56df-bbed-05cc74bdc8c0",
      "name": "Read Shopify launch products",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        690,
        520
      ],
      "parameters": {
        "url": "={{ 'https://'+ $(\"Check pack settings\").first().json[\"Shopify shop domain\"] +'/admin/api/2026-07/graphql.json' }}",
        "method": "POST",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "body",
                    "name": "variables",
                    "value": "={{ {...({}),cursor:$response.body?.data?.connection?.pageInfo?.endCursor ?? null} }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !$response.body?.data?.connection?.pageInfo?.hasNextPage }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 400
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "shopifyAccessTokenApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ ({query:\"query Products($cursor:String){connection:products(first:80,after:$cursor){pageInfo{hasNextPage endCursor} nodes{id status totalInventory onlineStoreUrl} } }\",variables:{} }) }}"
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "e1d1101f-8e50-51d8-a9be-667dcbdad4dc",
      "name": "Read Shopify campaign orders",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        920,
        520
      ],
      "parameters": {
        "url": "={{ 'https://'+ $(\"Check pack settings\").first().json[\"Shopify shop domain\"] +'/admin/api/2026-07/graphql.json' }}",
        "method": "POST",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "body",
                    "name": "variables",
                    "value": "={{ {...({filter:\"created_at:>=\" + $now.minus({days:14}).toISODate() }),cursor:$response.body?.data?.connection?.pageInfo?.endCursor ?? null} }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !$response.body?.data?.connection?.pageInfo?.hasNextPage }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 400
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "shopifyAccessTokenApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ ({query:\"query Orders($cursor:String,$filter:String!){connection:orders(first:20,after:$cursor,query:$filter){pageInfo{hasNextPage endCursor} nodes{id createdAt cancelledAt customerJourneySummary{ready lastVisit{utmParameters{campaign} } } } } }\",variables:{filter:\"created_at:>=\" + $now.minus({days:14}).toISODate() } }) }}"
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "02ba331b-b332-535d-adf0-ee2c3429d3fb",
      "name": "Read recent Sprkly receipts",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        1150,
        520
      ],
      "parameters": {
        "resource": "post",
        "operation": "getAll",
        "returnAll": true,
        "filters": {
          "updatedAfter": "={{ $now.minus({days:14}).toISO() }}"
        },
        "simplify": true
      },
      "alwaysOutputData": true
    },
    {
      "id": "36dbbcdf-9177-52c3-8177-c69901a63f75",
      "name": "Collect known Sprkly post IDs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1380,
        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": "b51f331f-3376-55f8-9de9-5de3ae5d66c9",
      "name": "There are post receipts to check",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        0,
        770
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "2d0831ee-b0c4-56e1-9c0e-4b0fba26a36d",
              "leftValue": "={{ $json.ids.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "819609fb-f532-5f4c-be5e-f7434cbc1a78",
      "name": "Expand known post IDs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        230,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.ids.map(id=>({json:{id}}));"
      }
    },
    {
      "id": "0c1b030c-76f5-59a5-af69-4ee486c874c8",
      "name": "Read tracked Sprkly posts",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        460,
        770
      ],
      "parameters": {
        "resource": "post",
        "operation": "get",
        "postId": "={{ $json.id }}",
        "simplify": true
      }
    },
    {
      "id": "00467edb-212a-5fe3-a9e0-3c53d5cd5d45",
      "name": "Continue to work review",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        690,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{ready:true}}];"
      }
    },
    {
      "id": "3e2ae286-4fdb-511c-8a26-2e5962d18ac1",
      "name": "Decide which work needs attention",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        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 pages=notion('Read the Notion launch calendar');\nconst assets=new Map(drive('Read the launch Drive folder').map(f=>[f.id,f]));\nconst orders=shop('Read Shopify campaign orders');\nconst products=new Map(shop('Read Shopify launch products').map(p=>[p.id,p]));\nconst findReceipt=receipts('launch');\nconst candidates=[], jobs=[];\nfor(const page of pages){\n  const p=n=>property(page,n), key=page.id, raw=str(p('Shopify Product ID')), item=products.get(raw.startsWith('gid://')?raw:'gid://shopify/Product/'+raw);\n  const old=prior.get(key)||{}, post=findReceipt(key,str(old['Post ID'])), id=str(post?.id||old['Post ID']), stateName=lower(post?.status||old['Posting State']);\n  const scheduled=str(p('Launch At')), due=dueDate(scheduled), caption=str(p('Caption')), asset=assets.get(str(p('Creative ID')));\n  const campaign='launch-'+key.replace(/-/g,'');\n  const productUrl=publicUrl(item?.onlineStoreUrl);\n  const tracked=productUrl?productUrl+(productUrl.includes('?')?'&':'?')+'utm_source=social&utm_medium=organic&utm_campaign='+campaign:'';\n  const live=['posted','published'].includes(stateName)&&!post?.deleted;\n  const published=str(post?.publishedAt||old['Published At']);\n  const min=Date.parse(published),elapsed=Number.isFinite(min)?($now.toMillis()-min)/36e5:0;\n  const missing=[!item?'Shopify product':'',item&&item.status!=='ACTIVE'?'active product':'',item&&!productUrl?'published storefront page':'',item&&!(item.totalInventory>0)?'available inventory':'',\n    !asset?.mimeType?.startsWith('image/')?'approved image in Drive':'',!caption?'caption':'',!Number.isFinite(Date.parse(scheduled))?'valid launch date':''].filter(Boolean);\n  const expired=Number.isFinite(Date.parse(scheduled))&&Date.parse(scheduled)<$now.plus({minutes:5}).toMillis();\n  const window=hours=>orders.filter(o=>{\n    const time=Date.parse(o.createdAt);\n    return !o.cancelledAt&&time>=min&&time<min+hours*36e5;\n  });\n  const last24=age(24,'Orders 24h'),last72=age(72,'Orders 72h');\n  function age(h,k){\n    if(!live||elapsed<h)return '';\n    if(str(old[k])!=='')return old[k];\n    if(elapsed>14*24)return '';\n    const inside=window(h);\n    if(inside.some(o=>o.customerJourneySummary?.ready===false))return '';\n    return inside.filter(o=>o.customerJourneySummary?.lastVisit?.utmParameters?.campaign===campaign).length;\n  }\n  const detail=live?(last72!==''?'72-hour order check complete':elapsed>14*24?'Attribution review window expired before a snapshot was recorded':'Live · waiting for attribution window or Shopify session data'):id?(post?.deleted?'Post was deleted in Sprkly':stateName==='failed'?'Sprkly reported a publishing failure':'Scheduled · checking live receipt'):\n   missing.length?'Launch blocked · '+missing.join(', '):p('Approved')!==true?'Awaiting approval':expired?'Move the launch date forward':'Ready to schedule';\n  const state=(live&&last72!=='')?'Completed':post?.deleted||stateName==='failed'||(live&&elapsed>14*24)||(!id&&(missing.length||expired))?'Blocked':'Pending';\n  const extra={'Shopify Product ID':raw,'Campaign':campaign,'Product URL':tracked,'Creative URL':driveLink(asset),'Post ID':id,\n    'Posting State':stateName,'Live URL':str(post?.permalink||old['Live URL']),'Published At':published,\n    'Orders 24h':last24,'Orders 72h':last72};\n  jobs.push(job(key,titleOf(page),state,detail,live?'':due,page.url,extra));\n  if(!id&&p('Approved')===true&&!missing.length&&!expired)candidates.push({key,title:titleOf(page),fileId:asset.id,caption:caption+'\\n\\n'+tracked,scheduled:new Date(scheduled).toISOString()});\n}\ncandidates.sort((a,b)=>a.scheduled.localeCompare(b.scheduled)||a.key.localeCompare(b.key));\nreturn result(jobs,'The 24- and 72-hour snapshots count orders associated with the launch campaign on Shopify’s last recorded visit.',{candidate:candidates[0]||null});"
      }
    },
    {
      "id": "c506c1af-0bff-5ae2-86d2-73cf49c77244",
      "name": "An approved post is ready",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1150,
        770
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "99c98eb9-2787-53c2-a3ad-deba88909da5",
              "leftValue": "={{ Boolean($json.candidate) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "0175955e-251c-5268-b8ab-e1039bd80a85",
      "name": "Prepare the one approved post",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1380,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const c=$json.candidate;return [{json:{...c,externalId:\"launch-\"+c.key}}];"
      }
    },
    {
      "id": "52b34e61-e654-5d82-bebd-d9f046b0f221",
      "name": "Download the approved Drive asset",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        0,
        1020
      ],
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.fileId }}"
        },
        "options": {}
      }
    },
    {
      "id": "15268c98-9409-584a-9016-04a4d4ed1f41",
      "name": "Upload the approved media",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        230,
        1020
      ],
      "parameters": {
        "resource": "media",
        "operation": "upload",
        "binaryPropertyName": "data"
      }
    },
    {
      "id": "5d986f45-ccea-55ce-942d-0649c6e2af3f",
      "name": "Schedule the approved post",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        460,
        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": "da6569ee-a783-5c98-9a3b-428ce244bb19",
      "name": "Apply the scheduling result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        690,
        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": "bc55a9de-4279-5eae-af70-07d141b26377",
      "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": "32f6579b-5fd5-5808-92a3-5d49b82baaa3",
      "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": "e818114c-ef90-5a00-bc71-2cb125f93778",
      "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:product-launch-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": "2ba35cf0-33fb-511d-a911-ec4dd0ea7b77",
      "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": "538f21fb-15bd-59e5-9d2d-aca98b89e59f",
      "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": "7e46d502-06be-5509-a298-9f6554280c7a",
              "leftValue": "={{ $json.writes.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "3e6bd05e-851e-5924-8b75-5d2c4246fe9d",
      "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": "2794382c-d0d2-5b22-bf61-3b54c4abd2f4",
      "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": "8478be37-17e1-5f09-95c0-85add9627635",
      "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": "f351afd8-c45a-5168-b609-eba9ab28729e",
      "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": "fb6301f8-44dd-5afb-a73a-a59f76c7e4d7",
              "leftValue": "={{ $json.rows.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "2a1a8186-300e-588f-98ce-97461f9a56a2",
      "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": "0c8a049d-11fe-5ed9-98bc-0784d819b8f8",
      "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": "Product Launch 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\"] ?? \"\" }}",
            "Shopify Product ID": "={{ $json[\"Shopify Product ID\"] ?? \"\" }}",
            "Campaign": "={{ $json[\"Campaign\"] ?? \"\" }}",
            "Product URL": "={{ $json[\"Product URL\"] ?? \"\" }}",
            "Creative URL": "={{ $json[\"Creative URL\"] ?? \"\" }}",
            "Post ID": "={{ $json[\"Post ID\"] ?? \"\" }}",
            "Posting State": "={{ $json[\"Posting State\"] ?? \"\" }}",
            "Live URL": "={{ $json[\"Live URL\"] ?? \"\" }}",
            "Published At": "={{ $json[\"Published At\"] ?? \"\" }}",
            "Orders 24h": "={{ $json[\"Orders 24h\"] ?? \"\" }}",
            "Orders 72h": "={{ $json[\"Orders 72h\"] ?? \"\" }}"
          },
          "matchingColumns": [
            "Work Key"
          ],
          "schema": []
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "928799bc-6395-55f0-8b3b-da48dc6ece38",
      "name": "Summarize completed and pending work",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1700
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const title = \"Product Launch 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": "e7fc5670-63ac-5bbe-967b-e0b396bb9bfc",
      "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": "Product Launch 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": "d9eb8650-8f33-50e7-9d41-4a1a1f6ddae9",
      "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": "d25ddd75-aa76-5ca1-8002-48c85be4bc1a",
              "leftValue": "={{ Boolean($(\"Check pack settings\").first().json[\"Digest recipient (optional)\"]) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "a8a9bb64-616d-5f17-ac42-cc2250ca45db",
      "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": "749836b0-0420-5e16-82e6-5649d77d13e5",
      "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": "39447c2b-3eb2-53f8-9799-6c2bfc43cfcb",
              "leftValue": "={{ !$json.messages?.length }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "d20db98f-c117-5ba0-b328-f8f96492f725",
      "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": "f0bcb448-9fc9-57f8-af28-274086d85f18",
      "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": "0c6687d0-02dd-4b6f-979a-3d74fb3a1c8c",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -830,
        890
      ],
      "parameters": {}
    },
    {
      "id": "109c3e27-e753-474b-82d9-4c51947a658f",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -610,
        890
      ],
      "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": "737ff51d-d378-4399-907b-b26df668348a",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -390,
        890
      ],
      "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 launch calendar",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the Notion launch calendar": {
      "main": [
        [
          {
            "node": "Read the launch Drive folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the launch Drive folder": {
      "main": [
        [
          {
            "node": "Read Shopify launch products",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Shopify launch products": {
      "main": [
        [
          {
            "node": "Read Shopify campaign orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Shopify campaign orders": {
      "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": {}
}
