{
  "name": "Seller morning desk",
  "nodes": [
    {
      "id": "40266819-7ae8-4868-ac54-2a32f6e7928d",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -640,
        -215
      ],
      "parameters": {
        "content": "## Seller morning desk\nEach morning it matches Shopify orders with ShipBob shipments and returns, writes them to a sheet and emails your action list.\n\n### You need\n- A Shopify admin token (read_orders, read_returns), saved as Header Auth with the name X-Shopify-Access-Token\n- A ShipBob token, saved as Bearer Auth\n- A Google Sheets login. Gmail, only for the email\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Fill **Seller settings**: sheet ID, your myshopify.com host, ShipBob channel ID and reference format.\n2. Add each login where a step asks. Use the same one in every step for that app. Leave the digest address empty while you connect.\n3. Set your time zone in Workflow settings.\n4. Failure alert: put your chat ID in **Write the failure alert** and your bot in **Send the failure alert**. Then in Workflow settings, set Error workflow to this workflow.\n\n### Test it\n- Click Test workflow with **Reconcile now** picked. It writes real rows to your sheet.\n- The Orders and Returns tabs fill in.",
        "height": 780,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "ea6a265c-9bf3-50fe-93c8-014c79c50868",
      "name": "Read all sources",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1200,
        -215
      ],
      "parameters": {
        "content": "## Read all sources\n\nOverlapping Shopify reads recover recent changes. Open orders already in Sheets are checked again, including older orders. The first run also imports the configured lookback.",
        "width": 1430,
        "height": 145,
        "color": 7
      }
    },
    {
      "id": "38e3a1f1-fbec-586f-9923-de412208b99e",
      "name": "Decide and write back",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2660,
        -215
      ],
      "parameters": {
        "content": "## Decide and write back\n\nAn order is marked delivered only after Shopify shows it fulfilled and every active ShipBob parcel has delivery evidence. Each return gets its own record. Refund and exchange decisions stay with the owner. Set Owner Resolved to Yes in Returns after handling a refund or exchange, so that return drops out of the follow-up count.",
        "width": 1180,
        "height": 158,
        "color": 6
      }
    },
    {
      "id": "bafd15b9-191d-5e30-aa81-83f58d8f663c",
      "name": "Email the action list",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        3900,
        -215
      ],
      "parameters": {
        "content": "## Email the action list\n\nAfter Sheets is current, send one internal digest with counts, stalled shipments and return follow-ups. Refunds are handled in Shopify.",
        "width": 650,
        "height": 145,
        "color": 5
      }
    },
    {
      "id": "2b5ab6d0-3e40-5c44-bde0-5e0ad6690dd4",
      "name": "Seller settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        210,
        30
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "c118ea44-2030-5d76-93f5-64521e7f3d97",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "1bdb7ed8-8456-516e-b15b-947502f8b940",
              "name": "Shopify host",
              "type": "string",
              "value": ""
            },
            {
              "id": "15f64efe-c70f-5b60-bc50-49b6264f466d",
              "name": "ShipBob channel ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "a8b5f75a-793b-55fa-b761-5ce8c65c1bd0",
              "name": "ShipBob reference",
              "type": "string",
              "value": "Shopify ID"
            },
            {
              "id": "4873cf59-11b5-5f26-b592-b715c8ca5522",
              "name": "Lookback days",
              "type": "number",
              "value": 7
            },
            {
              "id": "1a00b235-7d2f-5f94-a4f3-f4fce92da19c",
              "name": "Shipment review after days",
              "type": "number",
              "value": 3
            },
            {
              "id": "500651d1-cc89-5a3a-a538-a0ea7d40180d",
              "name": "Digest recipient",
              "type": "string",
              "value": ""
            }
          ]
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "4b295b3f-8b04-5f68-bb8c-72987490363e",
      "name": "Every morning",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        -5
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 8,
              "triggerAtMinute": 0
            }
          ]
        }
      }
    },
    {
      "id": "7d3ddcb0-cd32-5ed2-bad4-1f32c39cafbf",
      "name": "Reconcile now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        180
      ],
      "parameters": {}
    },
    {
      "id": "58d12cbd-4579-51c9-ab68-90d1d418e955",
      "name": "Check setup",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        435,
        30
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const c=$input.first().json;\nif (!/^[A-Za-z0-9_-]+$/.test(c['Spreadsheet ID'].trim())) throw new Error('Set the Spreadsheet ID in Seller settings.');\nif (!/^[a-z0-9][a-z0-9-]*\\.myshopify\\.com$/i.test(c['Shopify host'].trim())) throw new Error('Use the store hostname ending in .myshopify.com.');\nif (!/^\\d+$/.test(c['ShipBob channel ID'].trim())) throw new Error('Set the ShipBob sales channel ID.');\nif (!['Shopify ID','Order name','Order number'].includes(c['ShipBob reference'])) throw new Error('Choose Shopify ID, Order name or Order number for ShipBob reference.');\nif (!Number.isInteger(c['Lookback days']) || c['Lookback days']<1 || c['Lookback days']>30) throw new Error('Lookback days must be a whole number between 1 and 30.');\nif (!Number.isInteger(c['Shipment review after days']) || c['Shipment review after days']<1) throw new Error('Shipment review after days must be a positive whole number.');\nreturn [{json:{...c, since:$now.minus({days:c['Lookback days']}).toUTC().toISO(), stamp:$now.toISO()}}];"
      }
    },
    {
      "id": "a4f96f8d-5c72-55cd-b401-c5ad05395fae",
      "name": "Ensure Orders tab",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        660,
        30
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "create",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Seller settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "title": "Orders"
      },
      "alwaysOutputData": true
    },
    {
      "id": "45d9ccc4-c048-588e-93fc-87cb44baa3b9",
      "name": "Ensure Returns tab",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        885,
        -32
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "create",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Seller settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "title": "Returns"
      },
      "alwaysOutputData": true
    },
    {
      "id": "431aefa8-a38a-55e6-af67-3663da8f3152",
      "name": "Read order ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1110,
        110
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Seller settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Orders"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "e848a0b5-7017-5fd0-b93b-e8abd807a475",
      "name": "Pull recent Shopify orders",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1335,
        30
      ],
      "parameters": {
        "url": "={{ 'https://' + $(\"Seller settings\").first().json[\"Shopify host\"].trim() + '/admin/api/2026-10/graphql.json' }}",
        "method": "POST",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "body",
                    "name": "variables",
                    "value": "={{ { search: 'updated_at:>=\\'' + $(\"Check setup\").first().json[\"since\"] + '\\'', after: $response.body.data?.orders?.pageInfo?.endCursor || null } }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ Boolean($response.body.errors?.length || !$response.body.data?.orders?.pageInfo?.hasNextPage) }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 500
            }
          }
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {query:\"query Recent($search: String!, $after: String) { orders(first: 25, query: $search, sortKey: UPDATED_AT, after: $after) { pageInfo { hasNextPage endCursor } nodes { id name createdAt updatedAt cancelledAt requiresShipping displayFulfillmentStatus displayFinancialStatus returnStatus\\nreturns(first: 8) { pageInfo { hasNextPage } nodes { id name status createdAt refunds(first: 1) { nodes { id } } } } } } }\",variables:{ search: 'updated_at:>=\\'' + $(\"Check setup\").first().json[\"since\"] + '\\'', after: null }} }}"
      },
      "executeOnce": true
    },
    {
      "id": "ccb58426-bd0b-5e5b-a09c-507a0d764c3f",
      "name": "Find older orders still open",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        30
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const pages=$input.all().map(({json})=>json);\nif (!pages.length || pages.some(p=> p.errors?.length || !p.data?.orders?.pageInfo)) throw new Error('Shopify order read failed. Check token and read_orders / read_returns scopes.');\nif (pages.at(-1).data.orders.pageInfo.hasNextPage) throw new Error('The Shopify result exceeds 20 pages. Reduce Lookback days before retrying.');\nconst current=new Set(pages.flatMap(p=>p.data.orders.nodes.map(o=>o.id)));\nconst ledger=$('Read order ledger').all().map(({json})=>json);\nconst ids=[...new Set(ledger.filter(r=>String(r.Refresh).toLowerCase()==='yes')\n  .map(r=>String(r['Order ID']||'')).filter(id=>/^gid:\\/\\/shopify\\/Order\\/\\d+$/.test(id)&&!current.has(id)))];\nconst batches=[];\nfor(let i=0;i<ids.length;i+=20) batches.push({json:{ids:ids.slice(i,i+20)}});\nreturn batches.length?batches:[{json:{ids:[]}}];"
      }
    },
    {
      "id": "60bfa065-1a98-50bb-b9c3-e845c81a5bd1",
      "name": "Refresh those Shopify orders",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1790,
        30
      ],
      "parameters": {
        "url": "={{ 'https://' + $(\"Seller settings\").first().json[\"Shopify host\"].trim() + '/admin/api/2026-10/graphql.json' }}",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {query:\"query Tracked($ids: [ID!]!) { nodes(ids: $ids) { ... on Order { id name createdAt updatedAt cancelledAt requiresShipping displayFulfillmentStatus displayFinancialStatus returnStatus\\nreturns(first: 8) { pageInfo { hasNextPage } nodes { id name status createdAt refunds(first: 1) { nodes { id } } } } } } }\",variables:{ids:$json.ids}} }}"
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "c1c25f12-69c2-5c0d-bf33-47cb1ba8c19f",
      "name": "Match Shopify orders to ShipBob references",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2020,
        30
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const c=$('Check setup').first().json;\nconst orderPages=$('Pull recent Shopify orders').all().map(({json})=>json);\nconst tracked=$input.all().map(({json})=>json);\nif(tracked.some(p=>p.errors?.length || !Array.isArray(p.data?.nodes))) throw new Error('Shopify could not refresh previously tracked orders.');\nconst known=new Map();\nfor(const {json:r} of $('Read order ledger').all()) if(r['Order ID']) known.set(String(r['Order ID']),r);\nconst orders=new Map();\nfor(const order of [...orderPages.flatMap(p=>p.data.orders.nodes),...tracked.flatMap(p=>p.data.nodes)]) {\n  if(order?.id) orders.set(order.id,order);\n}\nconst missing = $('Find older orders still open').all().flatMap(({json})=>json.ids).filter(id=>!orders.has(id));\nconst out=[...orders.values()].map(order=>{\n  const shopId=String(order.id).split('/').at(-1);\n  const reference=c['ShipBob reference']==='Order name'?order.name:\n    c['ShipBob reference']==='Order number'?String(order.name).replace(/^#/, ''):shopId;\n  return {json:{order,previous:known.get(order.id)||{},reference:String(reference||''),unavailable:missing.length}};\n});\nreturn out.length?out:[{json:{empty:true,unavailable:missing.length}}];"
      }
    },
    {
      "id": "8e52e6a0-5da2-59ff-ba11-6506d79044c0",
      "name": "Look up ShipBob shipments",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2260,
        -35
      ],
      "parameters": {
        "url": "https://api.shipbob.com/2026-07/order",
        "method": "GET",
        "options": {
          "timeout": 45000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          },
          "batching": {
            "batch": {
              "batchSize": 5,
              "batchInterval": 1000
            }
          }
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "ReferenceIds",
              "value": "={{ $json.reference }}"
            },
            {
              "name": "Limit",
              "value": "250"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "shipbob_channel_id",
              "value": "={{ $(\"Seller settings\").first().json[\"ShipBob channel ID\"] }}"
            }
          ]
        }
      }
    },
    {
      "id": "51413aee-751e-5074-8a6f-c391da717d3f",
      "name": "Reconcile delivery and return status",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2500,
        30
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const c=$('Check setup').first().json;\nconst cutoff=Date.parse(c.stamp)-c['Shipment review after days']*86400000;\nconst orders=[], returns=[], exceptions=[];\nconst ownerResolved=new Set($('Read return decisions').all()\n .map(({json})=>json).filter(r=>['yes','true','1'].includes(String(r['Owner Resolved']||'').trim().toLowerCase()))\n .map(r=>String(r['Return ID']||'')));\nlet added=0, arrivals=0;\nconst canonical=value=>String(value||'').toLowerCase().replace(/[^a-z0-9]/g,'');\nconst phase=shipment=>canonical(shipment.status);\nconst delivered=shipment=>Number.isFinite(Date.parse(shipment.delivery_date)) || (shipment.status_details||[]).some(d=>canonical(d.name)==='delivered'||Number(d.id)===203);\nfor(const [i,{json:response}] of $input.all().entries()){\n  const {order,previous,reference}=$('Match Shopify orders to ShipBob references').itemMatching(i).json;\n  const ok=response.statusCode>=200&&response.statusCode<300&&Array.isArray(response.body);\n  if([401,403].includes(response.statusCode)) throw new Error('ShipBob rejected the credential or channel. No statuses were written.');\n  const matches=ok?response.body.filter(x=>String(x.reference_id)===reference):[];\n  const sourceOrder=matches.length===1?matches[0]:null;\n  const shipments=(Array.isArray(sourceOrder?.shipments)?sourceOrder.shipments:[]).filter(x=>!['cancelled','canceled'].includes(phase(x)));\n  const count=shipments.filter(delivered).length;\n  const clearDelivery=order.displayFulfillmentStatus==='FULFILLED'&&shipments.length>0&&count===shipments.length;\n  const hasException=shipments.some(x=>['exception','onhold'].includes(phase(x))||(x.status_details||[]).some(d=>/exception|onhold/.test(canonical(d.name))));\n  const held=hasException||(!clearDelivery&&Date.parse(order.createdAt)<cutoff);\n  const issues=[];\n  let delivery=previous['Delivery Status']||'Not confirmed';\n  if(order.cancelledAt) delivery='Cancelled';\n  else if(order.requiresShipping===false) delivery='Not required';\n  else if(!ok) issues.push('ShipBob response unavailable ('+String(response.statusCode||'unknown')+')');\n  else if(matches.length>1) issues.push('Multiple ShipBob records share this reference');\n  else if(matches.length===0&&held) issues.push('ShipBob order reference unmatched');\n  else if(clearDelivery) delivery='Delivered';\n  else if(delivery!=='Delivered'&&shipments.length) delivery=count?'Partially delivered':'Open';\n  if(held&&!order.cancelledAt&&order.requiresShipping!==false&&delivery!=='Delivered') issues.push(hasException?'ShipBob shipment exception':'Open beyond shipment review window');\n  if(!previous['Order ID']) added++;\n  if(delivery==='Delivered'&&previous['Delivery Status']!=='Delivered') arrivals++;\n\n  const list=order.returns?.nodes||[];\n  const incomplete=Boolean(order.returns?.pageInfo?.hasNextPage);\n  if(incomplete) issues.push('Additional returns exist; review this order in Shopify');\n  let openReturns=0;\n  for(const ret of list){\n    const refund=Boolean(ret.refunds?.nodes?.length);\n    const rejected=['CANCELED','CANCELLED','DECLINED'].includes(ret.status);\n    const active=!rejected&&ret.status!=='CLOSED';\n    const review=!rejected&&!refund;\n    const resolved=ownerResolved.has(String(ret.id));\n    if(!resolved&&(active||review)) openReturns++;\n    const action=resolved||rejected?'':refund?'Refund recorded; verify amount if needed':active?'Review return and refund eligibility':'Review refund or exchange outcome';\n    returns.push({'Return ID':ret.id,'Order ID':order.id,'Order':order.name,'Return':ret.name,\n      'Status':ret.status,'Opened':ret.createdAt,'Refund Recorded':refund?'Yes':'No','Owner Action':action,'Owner Resolved':resolved?'Yes':'','Checked At':c.stamp});\n  }\n  if(openReturns) issues.push(openReturns+' return(s) need follow-up');\n  const refresh=!['Delivered','Cancelled','Not required'].includes(delivery)||openReturns>0||incomplete;\n  orders.push({'Order ID':order.id,'Order':order.name,'Ordered At':order.createdAt,'Updated At':order.updatedAt,\n    'Payment':order.displayFinancialStatus,'Fulfillment':order.displayFulfillmentStatus,'Delivery Status':delivery,\n    'ShipBob Reference':reference,'Parcels':ok&&sourceOrder?shipments.length:(previous.Parcels??''),\n    'Delivered Parcels':ok&&sourceOrder?count:(previous['Delivered Parcels']??''),\n    'Return Status':order.returnStatus,'Open Return Checks':openReturns,'Refresh':refresh?'Yes':'No',\n    'Issue':issues.join(' • '),'First Seen':previous['First Seen']||c.stamp,'Checked At':c.stamp});\n  if(issues.length) exceptions.push(order.name+': '+issues.join(' • '));\n}\nconst body=[added+' new to the ledger · '+arrivals+' newly confirmed delivered · '+orders.length+' checked',\n  exceptions.length+' orders need attention',...exceptions.slice(0,20),\n  $('Match Shopify orders to ShipBob references').first().json.unavailable\n    ? $('Match Shopify orders to ShipBob references').first().json.unavailable+' older tracked orders were unavailable in Shopify. Their ledger rows were kept.' : '',\n  exceptions.length>20?'See Orders for the remaining '+(exceptions.length-20)+'.':'',\n  'https://docs.google.com/spreadsheets/d/'+encodeURIComponent(c['Spreadsheet ID'])].filter(Boolean).join('\\n');\nreturn [{json:{orders,returns,body}}];"
      }
    },
    {
      "id": "56ab3a1c-6af7-5465-b57b-8ebae4ed40ad",
      "name": "Expand order ledger rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2740,
        30
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.first().json.orders.map(json=>({json}));"
      }
    },
    {
      "id": "41a92ccb-3cf7-5489-a3bc-d67c2d796be7",
      "name": "Upsert Orders by Shopify ID",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        2980,
        30
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Seller settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "insertInNewColumn",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Orders"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "Order ID"
          ],
          "schema": []
        }
      }
    },
    {
      "id": "91c4968d-19c7-5aa8-bc49-9305d2be2f10",
      "name": "Returns to update",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3220,
        30
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "9c652107-fe97-54be-a21e-da4df576b281",
              "leftValue": "={{ $(\"Reconcile delivery and return status\").first().json.returns.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "2b6dd9d9-d8cb-52af-bcd6-c104f478a71b",
      "name": "Expand each return record",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3460,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $(\"Reconcile delivery and return status\").first().json.returns.map(json=>({json}));"
      },
      "executeOnce": true
    },
    {
      "id": "9afe2c4e-174e-56be-8685-6256f7f0ba45",
      "name": "Upsert Returns by return ID",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3700,
        0
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Seller settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "insertInNewColumn",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Returns"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "Return ID"
          ],
          "schema": []
        }
      }
    },
    {
      "id": "f6dd4582-14f3-5697-9389-036ea0fc3a37",
      "name": "Digest recipient set",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3950,
        30
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a2b1a312-5675-52e1-8a44-e1d2fc77e19d",
              "leftValue": "={{ $(\"Seller settings\").first().json[\"Digest recipient\"].trim().length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "9bcd2e86-2f97-54b6-95af-256a3cac2f3f",
      "name": "Email today’s action list",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        4190,
        0
      ],
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $(\"Seller settings\").first().json[\"Digest recipient\"] }}",
        "subject": "={{ 'Seller morning desk · ' + $now.toISODate() }}",
        "emailType": "text",
        "message": "={{ $(\"Reconcile delivery and return status\").first().json.body }}",
        "options": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "ca7cadcd-9764-52a1-b575-fa561394d295",
      "name": "Shopify orders to reconcile",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2240,
        145
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ebc1ed91-5932-524e-acbb-06477baab8c3",
              "leftValue": "={{ !$json.empty }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "7f331d4f-290a-571c-8c3b-076e47bc3f06",
      "name": "Prepare an empty morning summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2480,
        250
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const cfg=$('Check setup').first().json;\nconst missing=$input.first().json.unavailable;\nconst detail=missing?' · '+missing+' older orders unavailable in Shopify; their rows were kept.':'';\nreturn [{json:{message:'No Shopify orders to reconcile in the configured window'+detail,\n  workspace:'https://docs.google.com/spreadsheets/d/'+encodeURIComponent(cfg['Spreadsheet ID'])}}];"
      }
    },
    {
      "id": "2b0052f6-0ebc-5b20-b28a-fb7358ec69f7",
      "name": "Email an empty-day summary",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2720,
        250
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "2cf0e47c-f956-57cd-868d-147f3ab25e28",
              "leftValue": "={{ $(\"Seller settings\").first().json[\"Digest recipient\"].trim().length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "06ebf6cb-262b-5064-9e56-9aafa448c953",
      "name": "Email the empty-day summary",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2960,
        210
      ],
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $(\"Seller settings\").first().json[\"Digest recipient\"] }}",
        "subject": "={{ 'Seller morning desk · ' + $now.toISODate() }}",
        "emailType": "text",
        "message": "={{ $json.message+'\\n'+$json.workspace }}",
        "options": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "3939416d-6c86-5cfa-af83-3a7bae2938e5",
      "name": "Read return decisions",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1090,
        -55
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Seller settings\").first().json[\"Spreadsheet ID\"].trim() }}"
        },
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Returns"
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "5c17129d-2dc8-4c83-b525-da919083dd36",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -600,
        645
      ],
      "parameters": {}
    },
    {
      "id": "b3925505-07fe-49e0-aa0b-ce0bcfe37c2a",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -380,
        645
      ],
      "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": "3057e5ac-4813-4501-8ebe-b2af51937ee8",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -160,
        645
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Every morning": {
      "main": [
        [
          {
            "node": "Seller settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reconcile now": {
      "main": [
        [
          {
            "node": "Seller settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Seller settings": {
      "main": [
        [
          {
            "node": "Check setup",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check setup": {
      "main": [
        [
          {
            "node": "Ensure Orders tab",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ensure Orders tab": {
      "main": [
        [
          {
            "node": "Ensure Returns tab",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ensure Returns tab": {
      "main": [
        [
          {
            "node": "Read return decisions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read order ledger": {
      "main": [
        [
          {
            "node": "Pull recent Shopify orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pull recent Shopify orders": {
      "main": [
        [
          {
            "node": "Find older orders still open",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find older orders still open": {
      "main": [
        [
          {
            "node": "Refresh those Shopify orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Refresh those Shopify orders": {
      "main": [
        [
          {
            "node": "Match Shopify orders to ShipBob references",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Look up ShipBob shipments": {
      "main": [
        [
          {
            "node": "Reconcile delivery and return status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reconcile delivery and return status": {
      "main": [
        [
          {
            "node": "Expand order ledger rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand order ledger rows": {
      "main": [
        [
          {
            "node": "Upsert Orders by Shopify ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Orders by Shopify ID": {
      "main": [
        [
          {
            "node": "Returns to update",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Returns to update": {
      "main": [
        [
          {
            "node": "Expand each return record",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Digest recipient set",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand each return record": {
      "main": [
        [
          {
            "node": "Upsert Returns by return ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Returns by return ID": {
      "main": [
        [
          {
            "node": "Digest recipient set",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Digest recipient set": {
      "main": [
        [
          {
            "node": "Email today’s action list",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Match Shopify orders to ShipBob references": {
      "main": [
        [
          {
            "node": "Shopify orders to reconcile",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Shopify orders to reconcile": {
      "main": [
        [
          {
            "node": "Look up ShipBob shipments",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare an empty morning summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare an empty morning summary": {
      "main": [
        [
          {
            "node": "Email an empty-day summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email an empty-day summary": {
      "main": [
        [
          {
            "node": "Email the empty-day summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read return decisions": {
      "main": [
        [
          {
            "node": "Read order ledger",
            "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": {}
}
