{
  "name": "Inventory reorder desk",
  "nodes": [
    {
      "id": "1ebe4312-a0ac-4af3-8d4a-6780ece3e963",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -870,
        -100
      ],
      "parameters": {
        "content": "## Inventory reorder desk\nGives your buyer one list of SKUs to reorder from Shopify stock and your supplier rules, and closes the card when stock is back.\n\n### You need\n- A Shopify admin token that can read inventory\n- 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, Trello board and list IDs.\n3. Fill the **Reorder Rules** tab: SKU, Supplier, Supplier Email, Reorder Point, Target Stock, Confirmed Incoming.\n4. Add each login where a step asks. Use the same one in every step for that app. Set your time zone in Workflow settings.\n5. 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. Run it again after you fill the rules.\n- A SKU under its reorder point gets a Trello card.",
        "height": 780,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "2d345e01-87c6-5412-87e0-3b34ca5aa962",
      "name": "Scheduled review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 8,
              "triggerAtMinute": 0
            }
          ]
        }
      }
    },
    {
      "id": "88d88883-c954-5957-b6c4-18590963a1c2",
      "name": "Run the review now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        210
      ],
      "parameters": {}
    },
    {
      "id": "63161ead-ea3d-5b7b-908d-f84b50b5f618",
      "name": "Pack settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        230,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "612b7a67-ffd4-5bfc-81df-55390029abea",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "2ee1b3a8-8243-5b45-9c51-ab673b9e2b17",
              "name": "Shopify shop domain",
              "type": "string",
              "value": ""
            },
            {
              "id": "09b7d876-19ed-55bd-819b-8b044ad7f727",
              "name": "Trello board ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "cbfe83fc-3bee-5d3f-895a-53c38eabe4a2",
              "name": "Trello work list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "cd0b22bf-1b9b-5bc5-8fda-907771c8a019",
              "name": "Digest recipient (optional)",
              "type": "string",
              "value": ""
            }
          ]
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "2740fcb7-68da-5cf2-a18c-a7af97fb6c3d",
      "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\", \"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": "f5a37a5d-af98-515f-99df-fa43b38bd2b0",
      "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": "36f10165-f3a5-5a92-a568-5910c9f6702d",
      "name": "Plan missing tabs and headers",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const tabs = {\"Reorder Rules\": [\"SKU\", \"Supplier\", \"Supplier Email\", \"Reorder Point\", \"Target Stock\", \"Confirmed Incoming\"], \"Inventory Reorder Desk Ledger\": [\"Work Key\", \"Title\", \"State\", \"Details\", \"Due\", \"Source URL\", \"Card ID\", \"Card URL\", \"Checked At\", \"SKU\", \"Supplier\", \"Available Units\", \"Confirmed Incoming\", \"Projected Units\", \"Suggested Reorder Units\", \"Supplier Email\"], \"Inventory Reorder 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": "840a8bdf-d2dd-5baf-9ce6-1916cf52dfd8",
      "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": "678df4e6-2d63-5ea3-bfd6-5b09ebaa00ea",
              "leftValue": "={{ $json.requests.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "6c551c63-dd84-573b-a67a-db3e3619f374",
      "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": "80de8cb9-f516-55a8-b6ca-167f19f0738a",
      "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": "Inventory Reorder Desk Ledger"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "5faccf35-7b76-5816-87e8-05ebcbe40401",
      "name": "Set up the source",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1070,
        305
      ],
      "parameters": {
        "content": "## Set up the source\n\nShopify scope · **read_products**. Use one rule per tracked SKU. Enter confirmed incoming units only for orders yet to be stocked. Suggested units are for manual purchase review.",
        "width": 966,
        "height": 145,
        "color": 4
      }
    },
    {
      "id": "993b835c-dbad-52f1-b1c3-eba0ecebe074",
      "name": "Read Reorder Rules",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        230,
        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": "Reorder Rules"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "25aa26f0-073e-5317-8e20-48200fe3d4dc",
      "name": "Read Shopify inventory variants",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        460,
        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 VariantStock($cursor:String){connection:productVariants(first:80,after:$cursor,query:\\\"product_status:active\\\"){pageInfo{hasNextPage endCursor} nodes{id sku inventoryQuantity product{id status} } } }\",variables:{} }) }}"
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "8c183b27-9a74-5eb4-968b-55874dd6ef17",
      "name": "Decide which work needs attention",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        690,
        520
      ],
      "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\nconst policy=rows('Read Reorder Rules','SKU');\nunique(policy.map(r=>r.SKU),'Reorder rule SKUs');\nconst variants=new Map();\nfor(const v of shop('Read Shopify inventory variants')){\n  const key=lower(v.sku);\n  if(key)variants.set(key,[...(variants.get(key)||[]),v]);\n}\nconst jobs=[];\nfor(const rule of policy){\n  const sku=str(rule.SKU), hits=variants.get(lower(sku))||[], v=hits[0];\n  const threshold=Number(rule['Reorder Point']), target=Number(rule['Target Stock']), incoming=Number(rule['Confirmed Incoming']||0);\n  const amount=v?.inventoryQuantity;\n  const hasRule=str(rule['Reorder Point'])!==''&&str(rule['Target Stock'])!==''&&[threshold,target,incoming].every(x=>Number.isInteger(x)&&x>=0)&&target>threshold;\n  const error=hits.length!==1?'SKU must match exactly one active Shopify variant':amount===null||!Number.isInteger(amount)?'Enable Shopify inventory tracking':!hasRule?'Check reorder point, target and incoming units':(!str(rule.Supplier)?'Assign a supplier':'');\n  const projected=Number.isInteger(amount)&&hasRule?amount+incoming:null;\n  const reorder=!error&&projected<=threshold?target-projected:0;\n  const state=error?'Blocked':reorder>0?'Pending':'Completed';\n  jobs.push(job(sku,'Reorder '+sku,state,error||(reorder?'Request '+reorder+' units from '+str(rule.Supplier):'Projected stock is above the reorder point'),'',v?shopLink('products',v.product.id):'',\n    {'SKU':sku,'Supplier':str(rule.Supplier),'Available Units':amount??'','Confirmed Incoming':hasRule?incoming:'','Projected Units':projected??'','Suggested Reorder Units':reorder,'Supplier Email':email(rule['Supplier Email'])}));\n}\nreturn result(jobs,jobs.filter(j=>j.extra['Suggested Reorder Units']>0).length+' SKUs need an order decision. Incoming units are included in the estimate.');"
      }
    },
    {
      "id": "7122e128-a3d5-56e1-a8aa-f7d199c3b38c",
      "name": "Prepare tracker updates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        880
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const decisionNode = \"Decide which work needs attention\";\nconst prefix = \"[sprkly:inventory-reorder-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": "f0c7bc23-b07b-5b25-9518-92ba84fe780c",
      "name": "Read the Trello board",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -230,
        880
      ],
      "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": "befc788b-2114-5987-a5f4-1b437eeda076",
      "name": "Trello needs changes",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        220,
        880
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "d222a67f-b9d7-5635-80f3-0bcbd22336e2",
              "leftValue": "={{ $json.writes.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "f40ef166-f369-5796-907b-8effa59fa0a2",
      "name": "Expand changed cards",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.writes.map(json=>({json}));"
      }
    },
    {
      "id": "1b051d19-071e-5701-80c9-49db6c49d0c7",
      "name": "Create or update work cards",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        770
      ],
      "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": "53c071d3-eafb-529c-9f96-b99660f1ebf9",
      "name": "Prepare ledger rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        880
      ],
      "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": "634ff865-4e23-5c5f-bb14-bbd9305d85d8",
      "name": "Ledger has work records",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1100,
        880
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "14e9e8f7-757f-54f7-9550-5a1bf03956db",
              "leftValue": "={{ $json.rows.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "e88f2d40-3a0f-5ac3-abf6-e643576a1285",
      "name": "Expand work records",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.rows.map(json=>({json}));"
      }
    },
    {
      "id": "34d669d2-f5fc-5986-8310-3fc4ff724e86",
      "name": "Update the work ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1540,
        770
      ],
      "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": "Inventory Reorder 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\"] ?? \"\" }}",
            "SKU": "={{ $json[\"SKU\"] ?? \"\" }}",
            "Supplier": "={{ $json[\"Supplier\"] ?? \"\" }}",
            "Available Units": "={{ $json[\"Available Units\"] ?? \"\" }}",
            "Confirmed Incoming": "={{ $json[\"Confirmed Incoming\"] ?? \"\" }}",
            "Projected Units": "={{ $json[\"Projected Units\"] ?? \"\" }}",
            "Suggested Reorder Units": "={{ $json[\"Suggested Reorder Units\"] ?? \"\" }}",
            "Supplier Email": "={{ $json[\"Supplier Email\"] ?? \"\" }}"
          },
          "matchingColumns": [
            "Work Key"
          ],
          "schema": []
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "f7c1d424-581d-5ea5-bda3-251773585fe5",
      "name": "Summarize completed and pending work",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const title = \"Inventory Reorder 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": "aca51c28-5d8e-518e-873b-1b742ad84fbf",
      "name": "Save the dated work report",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        220,
        1200
      ],
      "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": "Inventory Reorder 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": "b3d5c049-ed48-5107-94b2-a817e756a014",
      "name": "A digest recipient is set",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        440,
        1200
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "64b6b079-9e76-54f3-b923-7d2961c2dc08",
              "leftValue": "={{ Boolean($(\"Check pack settings\").first().json[\"Digest recipient (optional)\"]) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "9c37a838-32ba-5b49-b625-2238d9f2b257",
      "name": "Check Gmail for today’s digest",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        1200
      ],
      "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": "4e8dfeb5-6fe5-5d6e-8705-b0c6b8839c2b",
      "name": "Today’s digest is new",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        880,
        1200
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "dc01595a-50cf-588e-8597-1e3bb7ccd09e",
              "leftValue": "={{ !$json.messages?.length }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "c07128ea-d1ee-5beb-aa24-ceb71b239629",
      "name": "Email the internal work digest",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1100,
        1200
      ],
      "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": "a51d2a3c-7ba8-5d71-8d44-fa095677da9c",
      "name": "Work ledger and daily report",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -90,
        1055
      ],
      "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": "cbe6156e-60e2-4b47-8fe7-e73acb500397",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -830,
        760
      ],
      "parameters": {}
    },
    {
      "id": "807ea458-1d3e-4493-97bb-a22b55bfe932",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -610,
        760
      ],
      "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": "95550b67-cf7a-499a-94de-3db95011b7ff",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -390,
        760
      ],
      "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 Reorder Rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Reorder Rules": {
      "main": [
        [
          {
            "node": "Read Shopify inventory variants",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Shopify inventory variants": {
      "main": [
        [
          {
            "node": "Decide which work needs attention",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide which work needs attention": {
      "main": [
        [
          {
            "node": "Read the Trello board",
            "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": {}
}
