{
  "name": "Low stock check before you promote",
  "nodes": [
    {
      "id": "b8ae61a1-c338-46d0-ab0a-1f1263360a67",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -688,
        -120
      ],
      "parameters": {
        "content": "## Low stock check before you promote\nEach morning it compares Shopify stock and recent sales with the posts you have scheduled in sprkly, and warns you before you promote something that will sell out.\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=shopify-low-stock-readiness\n- A Shopify admin token that can read products, inventory and orders\n- A Google Sheets login and a Stock Checks tab with: Date, Product, Handle, Stock, Sold Per Day, Days Of Stock, Upcoming Posts, Status\n- A Telegram bot and your chat ID\n\n### Set it up\n1. Add your sprkly key to each sprkly step.\n2. Add your Shopify login to **Read Shopify stock** (Shopify Access Token) and **Read recent orders**.\n3. In **Settings**, set your shop domain (your-store.myshopify.com), how many days ahead to look, your restock time in days and your chat ID.\n4. Pick your sheet in **Log the stock check**. 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- Schedule a test post in sprkly that names a product with little stock. Click Test workflow.\n- You get a warning that names the product and the post. It never changes or stops a post. Delete the test post after.",
        "height": 962,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "13a0b596-229e-49a8-b0d4-3c5e80772e2a",
      "name": "Note: read",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -48,
        -120
      ],
      "parameters": {
        "content": "## Read stock, sales and posts\nStock comes from Shopify. Sales per day come from the orders of the last 30 days. Posts come from sprkly. Nothing is changed.",
        "height": 560,
        "width": 1240,
        "color": 7
      }
    },
    {
      "id": "474e813c-af3e-44b1-91b6-567aab74acf4",
      "name": "Note: warn",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1272,
        -120
      ],
      "parameters": {
        "content": "## Warn before the promo\nA product is low when its stock lasts fewer days than your look-ahead plus your restock time. A post counts when its caption has the product link or name.",
        "height": 760,
        "width": 760,
        "color": 7
      }
    },
    {
      "id": "54a74c90-d9e5-4c48-8cea-f4ddc139708e",
      "name": "Every morning",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "triggerAtHour": 8
            }
          ]
        }
      }
    },
    {
      "id": "5ba60a9b-cd80-4b72-b354-5ac43832bb86",
      "name": "Check now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        200
      ],
      "parameters": {}
    },
    {
      "id": "3c8c65b4-1603-42e5-98d9-4138e71332c1",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        100
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "shopDomain",
              "type": "string",
              "value": "your-store.myshopify.com"
            },
            {
              "id": "f2",
              "name": "daysAhead",
              "type": "number",
              "value": 7
            },
            {
              "id": "f3",
              "name": "leadTimeDays",
              "type": "number",
              "value": 7
            },
            {
              "id": "f4",
              "name": "salesDays",
              "type": "number",
              "value": 30
            },
            {
              "id": "f5",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_CHAT_ID"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      }
    },
    {
      "id": "4edfc66c-85f2-4f50-87e5-ef78e25b2efd",
      "name": "Read Shopify stock",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        480,
        100
      ],
      "parameters": {
        "url": "={{ 'https://' + String($('Settings').first().json.shopDomain).trim() + '/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 title handle} } } }\",variables:{} }) }}"
      }
    },
    {
      "id": "0efbc202-cb2f-42d5-882a-227bb35e2cfc",
      "name": "Read recent orders",
      "type": "n8n-nodes-base.shopify",
      "typeVersion": 1,
      "position": [
        720,
        100
      ],
      "parameters": {
        "authentication": "accessToken",
        "resource": "order",
        "operation": "getAll",
        "returnAll": true,
        "options": {
          "createdAtMin": "={{ $now.minus({ days: Number($('Settings').first().json.salesDays) || 30 }).toISO() }}",
          "status": "any",
          "fields": "id,created_at,cancelled_at,line_items"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "5c733cb4-a0bd-4306-bb1b-c351f8b5bf91",
      "name": "Get scheduled posts",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        960,
        100
      ],
      "parameters": {
        "resource": "post",
        "operation": "getAll",
        "returnAll": true,
        "filters": {
          "status": "scheduled"
        },
        "simplify": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "972819e6-5cbc-4980-8fef-d322965d887e",
      "name": "Find promos at risk",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1200,
        100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const s = $('Settings').first().json;\nconst variants = $('Read Shopify stock').all().flatMap(i => (i.json.data && i.json.data.connection && i.json.data.connection.nodes) || []);\nconst sold = new Map();\nfor (const { json: o } of $('Read recent orders').all()) {\n  if (!o.id || o.cancelled_at) continue;\n  for (const li of o.line_items || []) { const k = String(li.variant_id || ''); if (k) sold.set(k, (sold.get(k) || 0) + (Number(li.quantity) || 0)); }\n}\nconst products = new Map();\nfor (const v of variants) {\n  const p = v.product || {};\n  if (!p.id) continue;\n  const e = products.get(p.id) || { title: String(p.title || ''), handle: String(p.handle || ''), stock: 0, sold: 0 };\n  e.stock += Math.max(0, Number(v.inventoryQuantity) || 0);\n  e.sold += sold.get(String(v.id).split('/').pop()) || 0;\n  products.set(p.id, e);\n}\nconst salesDays = Number(s.salesDays) || 30;\nconst need = (Number(s.daysAhead) || 7) + (Number(s.leadTimeDays) || 7);\nconst until = $now.plus({ days: Number(s.daysAhead) || 7 });\nconst posts = $('Get scheduled posts').all().map(i => i.json)\n  .filter(p => p.id && !p.deleted && p.scheduledTime && DateTime.fromISO(p.scheduledTime) <= until);\nconst out = [];\nfor (const e of products.values()) {\n  const perDay = e.sold / salesDays;\n  const cover = perDay > 0 ? e.stock / perDay : (e.stock > 0 ? Infinity : 0);\n  if (cover >= need) continue;\n  const mentions = posts.filter(p => {\n    const c = String(p.caption || '').toLowerCase();\n    return (e.handle && c.includes('/products/' + e.handle.toLowerCase())) || (e.title.length > 3 && c.includes(e.title.toLowerCase()));\n  });\n  out.push({ json: {\n    product: e.title, handle: e.handle, stock: e.stock, soldPerDay: Number(perDay.toFixed(2)),\n    daysCover: Number.isFinite(cover) ? Number(cover.toFixed(1)) : 'no recent sales',\n    postIds: mentions.map(p => p.id), firstPost: mentions.map(p => p.scheduledTime).sort()[0] || '',\n    status: mentions.length ? 'Hold the promo' : 'Low stock',\n  } });\n}\nreturn out;"
      }
    },
    {
      "id": "1c582b91-0294-4145-bfb5-c77d6b62c755",
      "name": "Log the stock check",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1440,
        0
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Stock Checks",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Date": "={{ $now.toISODate() }}",
            "Product": "={{ $json.product }}",
            "Handle": "={{ $json.handle }}",
            "Stock": "={{ $json.stock }}",
            "Sold Per Day": "={{ $json.soldPerDay }}",
            "Days Of Stock": "={{ $json.daysCover }}",
            "Upcoming Posts": "={{ $json.postIds.join(', ') }}",
            "Status": "={{ $json.status }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Date",
              "displayName": "Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Product",
              "displayName": "Product",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Handle",
              "displayName": "Handle",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Stock",
              "displayName": "Stock",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Sold Per Day",
              "displayName": "Sold Per Day",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Days Of Stock",
              "displayName": "Days Of Stock",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Upcoming Posts",
              "displayName": "Upcoming Posts",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Status",
              "displayName": "Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "b807544d-4ea5-4f73-939f-223bf813a580",
      "name": "Write the warning",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1440,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const rows = $('Find promos at risk').all().map(i => i.json);\nconst hold = rows.filter(r => r.postIds.length);\nif (hold.length === 0) return [];\nconst link = id => 'https://sprkly.app/schedule?utm_source=n8n&utm_medium=workflow&utm_campaign=shopify-low-stock-readiness&post=' + encodeURIComponent(id);\nconst lines = hold.slice(0, 10).map(r => '- ' + r.product + ': ' + r.stock + ' left, about ' + r.daysCover + ' days.\\n  Post: ' + link(r.postIds[0]) + (r.postIds.length > 1 ? ' and ' + (r.postIds.length - 1) + ' more' : ''));\nconst others = rows.length - hold.length;\nconst message = 'These posts promote products that may sell out:\\n\\n' + lines.join('\\n') + (others ? '\\n\\n' + others + ' more products are low, with no post set.' : '') + '\\n\\nNothing was changed. Move or edit the posts in sprkly if you need to.';\nreturn [{ json: { message } }];"
      }
    },
    {
      "id": "df414392-e220-4426-8946-32d4f7744776",
      "name": "Send the warning",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        1680,
        200
      ],
      "parameters": {
        "chatId": "={{ $('Settings').first().json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "2434cc7e-96ca-4601-9e44-b5a0411741d3",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -648,
        922
      ],
      "parameters": {}
    },
    {
      "id": "9f2d2280-686c-4d04-9382-f95166db45d9",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -428,
        922
      ],
      "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": "35d43822-afa0-4db1-87d0-1c4409215ede",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -208,
        922
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Every morning": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check now": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Read Shopify stock",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Shopify stock": {
      "main": [
        [
          {
            "node": "Read recent orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read recent orders": {
      "main": [
        [
          {
            "node": "Get scheduled posts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get scheduled posts": {
      "main": [
        [
          {
            "node": "Find promos at risk",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find promos at risk": {
      "main": [
        [
          {
            "node": "Log the stock check",
            "type": "main",
            "index": 0
          },
          {
            "node": "Write the warning",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the warning": {
      "main": [
        [
          {
            "node": "Send the warning",
            "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
          }
        ]
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "tags": []
}
