{
  "name": "Inventory Reorder Prediction",
  "nodes": [
    {
      "id": "sticky-overview", "name": "Overview", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [-240, -500],
      "parameters": { "content": "## Inventory Reorder Prediction\nVersion 1.0.0 — E-Commerce\n\nRuns daily, pulls all Shopify product variants with inventory levels, fetches orders from the last 7 days to compute sales velocity, then uses GPT-4o to predict stockout dates and determine whether to reorder. Reorder emails are sent to the supplier and all reorder decisions are logged to Google Sheets.\n\nFlow: Schedule => Fetch Products (Shopify) => Fetch Orders (Shopify) => Compute Sales Velocity (Code) => Predict Stockout Risk (AI Agent) => Should Reorder? (IF) => Send Reorder Email + Log to Sheets", "height": 260, "width": 680, "color": 7 }
    },
    {
      "id": "sticky-prereqs", "name": "Prerequisites", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [-240, -220],
      "parameters": { "content": "## Prerequisites\n- Shopify store with Admin API access (Custom App)\n- OpenAI API key (GPT-4o)\n- Gmail account for reorder notifications\n- Google Sheets for reorder log\n\nShopify setup: Admin => Apps and sales channels => Develop apps => Create an app => Enable read_products and read_orders API scopes => Install app => Copy Admin API access token.", "height": 180, "width": 420, "color": 5 }
    },
    {
      "id": "sticky-setup", "name": "Setup Required", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [220, -220],
      "parameters": { "content": "## Setup Required\n1. Fetch Products + Fetch Orders — connect 'Shopify Access Token API' credential\n2. OpenAI sub-node — connect OpenAI credential\n3. Send Reorder Email — connect Gmail OAuth2 credential, update supplier@example.com to real address\n4. Log to Google Sheets — connect Google Sheets credential, replace YOUR_REORDER_LOG_SHEET_ID\n5. Adjust reorder threshold in the Should Reorder? IF node (default: should_reorder = true from AI)", "height": 180, "width": 420, "color": 3 }
    },
    {
      "id": "sticky-howitworks", "name": "How It Works", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [-240, 0],
      "parameters": { "content": "## How It Works\n1. Runs daily at 06:00 UTC via cron schedule\n2. Fetches all Shopify products and their variant inventory levels\n3. Fetches all orders from the past 7 days and sums units sold per variant\n4. Code node joins the two datasets to compute sales velocity (units/day) and estimated days until stockout\n5. AI Agent evaluates each variant's risk level and recommended reorder quantity\n6. IF should_reorder is true: sends email to supplier and logs to Google Sheets\n7. IF should_reorder is false: logs to Google Sheets with low risk status", "height": 200, "width": 420, "color": 4 }
    },

    {
      "id": "schedule-trigger", "name": "Daily Inventory Check", "type": "n8n-nodes-base.scheduleTrigger", "typeVersion": 1.2, "position": [0, 100],
      "parameters": { "rule": { "interval": [{ "field": "cronExpression", "expression": "0 6 * * *" }] } }
    },

    {
      "id": "sni-fetch-products", "name": "Fetch Products note", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [265, -35],
      "parameters": { "content": "Pulls all product variants with current inventory_quantity from Shopify", "height": 60, "width": 270 }
    },
    {
      "id": "fetch-products", "name": "Fetch All Products", "type": "n8n-nodes-base.shopify", "typeVersion": 1, "position": [260, 100],
      "credentials": { "shopifyApi": { "id": "shopify-cred", "name": "Shopify Access Token API" } },
      "parameters": { "resource": "product", "operation": "getAll", "returnAll": true, "options": {} },
      "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 2000, "onError": "continueErrorOutput"
    },

    {
      "id": "sni-fetch-orders", "name": "Fetch Orders note", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [525, -35],
      "parameters": { "content": "Fetches all orders from the last 7 days to calculate sales velocity", "height": 60, "width": 260 }
    },
    {
      "id": "fetch-orders", "name": "Fetch Recent Orders", "type": "n8n-nodes-base.shopify", "typeVersion": 1, "position": [520, 100],
      "credentials": { "shopifyApi": { "id": "shopify-cred", "name": "Shopify Access Token API" } },
      "parameters": {
        "resource": "order", "operation": "getAll", "returnAll": true,
        "options": { "created_at_min": "={{ DateTime.now().minus({ days: 7 }).toISO() }}", "status": "any" }
      },
      "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 2000, "onError": "continueErrorOutput"
    },

    {
      "id": "sni-velocity", "name": "Velocity note", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [785, -35],
      "parameters": { "content": "Joins products + orders, computes velocity (units/day) and days until stockout per variant", "height": 60, "width": 270 }
    },
    {
      "id": "compute-velocity", "name": "Compute Sales Velocity", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [780, 100],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const orders = $('Fetch Recent Orders').all();\nconst salesMap = {};\nfor (const order of orders) {\n  for (const item of (order.json.line_items || [])) {\n    const vid = String(item.variant_id);\n    salesMap[vid] = (salesMap[vid] || 0) + (item.quantity || 0);\n  }\n}\nconst products = $('Fetch All Products').all();\nconst result = [];\nfor (const product of products) {\n  for (const variant of (product.json.variants || [])) {\n    const vid = String(variant.id);\n    const stock = variant.inventory_quantity || 0;\n    const sold7d = salesMap[vid] || 0;\n    const velocity = sold7d / 7;\n    const days_until_stockout = velocity > 0 ? Math.floor(stock / velocity) : 999;\n    result.push({ json: {\n      product_title:    product.json.title,\n      variant_id:       vid,\n      variant_title:    variant.title,\n      sku:              variant.sku || '',\n      stock,\n      sold_7d:          sold7d,\n      velocity_per_day: Math.round(velocity * 100) / 100,\n      days_until_stockout\n    }});\n  }\n}\nreturn result;"
      }
    },

    {
      "id": "sni-predict", "name": "Predict note", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [1045, -35],
      "parameters": { "content": "AI Agent assesses stockout risk and recommends reorder quantity with 30-day + 20% safety buffer", "height": 60, "width": 270 }
    },
    {
      "id": "predict-agent", "name": "Predict Stockout Risk", "type": "@n8n/n8n-nodes-langchain.agent", "typeVersion": 1.8, "position": [1040, 100],
      "parameters": {
        "agentType": "toolsAgent",
        "promptType": "define",
        "text": "=Analyse this Shopify product variant and determine reorder urgency.\n\nProduct: {{ $json.product_title }} — {{ $json.variant_title }}\nSKU: {{ $json.sku }}\nCurrent Stock: {{ $json.stock }} units\nSold in Last 7 Days: {{ $json.sold_7d }} units\nSales Velocity: {{ $json.velocity_per_day }} units/day\nEstimated Days Until Stockout: {{ $json.days_until_stockout }}\n\nAssess risk level, recommend a reorder quantity that covers 30 days of demand plus 20% safety stock, and decide whether an immediate reorder is needed.",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You are an inventory analyst for an e-commerce business. Assess stockout risk based on sales velocity and current stock. critical = stockout within 3 days, high = within 7 days, medium = 7-14 days, low = 14+ days. Recommend reorder quantities based on 30-day demand plus 20% safety buffer. If stock is 0 and velocity is 0, classify as low risk.",
          "returnIntermediateSteps": false
        }
      }
    },
    {
      "id": "predict-openai", "name": "OpenAI — Predict", "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi", "typeVersion": 1.2, "position": [1040, 300],
      "parameters": { "model": { "__rl": true, "value": "gpt-4o", "mode": "list" }, "options": { "temperature": 0 } },
      "credentials": { "openAiApi": { "id": "openai-cred", "name": "OpenAI API" } }
    },
    {
      "id": "predict-parser", "name": "Stockout Risk Schema", "type": "@n8n/n8n-nodes-langchain.outputParserStructured", "typeVersion": 1.2, "position": [1240, 300],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\"type\":\"object\",\"properties\":{\"risk_level\":{\"type\":\"string\",\"enum\":[\"critical\",\"high\",\"medium\",\"low\"]},\"recommended_reorder_qty\":{\"type\":\"integer\"},\"reasoning\":{\"type\":\"string\"},\"should_reorder\":{\"type\":\"boolean\"}},\"required\":[\"risk_level\",\"recommended_reorder_qty\",\"reasoning\",\"should_reorder\"]}"
      }
    },

    {
      "id": "sni-should-reorder", "name": "Should Reorder note", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [1305, -35],
      "parameters": { "content": "Routes to email supplier (true) or skip to log only (false)", "height": 60, "width": 255 }
    },
    {
      "id": "should-reorder", "name": "Should Reorder?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [1300, 100],
      "parameters": {
        "conditions": {
          "options": { "typeValidation": "loose" },
          "conditions": [{ "id": "cond-reorder", "leftValue": "={{ $json.output.should_reorder }}", "rightValue": true, "operator": { "type": "boolean", "operation": "equal" } }],
          "combinator": "and"
        }
      }
    },

    {
      "id": "sni-email", "name": "Email note", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [1565, -115],
      "parameters": { "content": "Sends reorder request to supplier with full variant details", "height": 60, "width": 255 }
    },
    {
      "id": "send-reorder-email", "name": "Send Reorder Email", "type": "n8n-nodes-base.gmail", "typeVersion": 2.1, "position": [1560, -80],
      "parameters": {
        "sendTo": "supplier@example.com",
        "subject": "=Reorder Request — {{ $('Compute Sales Velocity').item.json.product_title }} (SKU: {{ $('Compute Sales Velocity').item.json.sku }})",
        "emailType": "html",
        "message": "=<h2>Reorder Request</h2><table border='1' cellpadding='6' cellspacing='0' style='border-collapse:collapse'><tr><td><strong>Product</strong></td><td>{{ $('Compute Sales Velocity').item.json.product_title }} — {{ $('Compute Sales Velocity').item.json.variant_title }}</td></tr><tr><td><strong>SKU</strong></td><td>{{ $('Compute Sales Velocity').item.json.sku }}</td></tr><tr><td><strong>Current Stock</strong></td><td>{{ $('Compute Sales Velocity').item.json.stock }} units</td></tr><tr><td><strong>Sales Velocity</strong></td><td>{{ $('Compute Sales Velocity').item.json.velocity_per_day }} units/day</td></tr><tr><td><strong>Days Until Stockout</strong></td><td>{{ $('Compute Sales Velocity').item.json.days_until_stockout }}</td></tr><tr><td><strong>Risk Level</strong></td><td>{{ $json.output.risk_level.toUpperCase() }}</td></tr><tr><td><strong>Recommended Reorder Qty</strong></td><td>{{ $json.output.recommended_reorder_qty }} units</td></tr></table><p><em>{{ $json.output.reasoning }}</em></p><p>Please confirm receipt and expected delivery timeline.</p>",
        "options": {}
      },
      "credentials": { "gmailOAuth2": { "id": "gmail-cred", "name": "Gmail OAuth2" } },
      "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 2000, "onError": "continueErrorOutput"
    },

    {
      "id": "sni-log", "name": "Log note", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [1825, -35],
      "parameters": { "content": "Logs all reorder decisions (triggered or skipped) to Google Sheets for tracking", "height": 60, "width": 265 }
    },
    {
      "id": "log-to-sheets", "name": "Log to Google Sheets", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [1820, 100],
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": { "__rl": true, "value": "YOUR_REORDER_LOG_SHEET_ID", "mode": "id" },
        "sheetName": { "__rl": true, "value": "Reorder Log", "mode": "name" },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Timestamp":         "={{ DateTime.now().toISO() }}",
            "Product":           "={{ $('Compute Sales Velocity').item.json.product_title }}",
            "Variant":           "={{ $('Compute Sales Velocity').item.json.variant_title }}",
            "SKU":               "={{ $('Compute Sales Velocity').item.json.sku }}",
            "Stock":             "={{ $('Compute Sales Velocity').item.json.stock }}",
            "Sold 7d":           "={{ $('Compute Sales Velocity').item.json.sold_7d }}",
            "Velocity/day":      "={{ $('Compute Sales Velocity').item.json.velocity_per_day }}",
            "Days to Stockout":  "={{ $('Compute Sales Velocity').item.json.days_until_stockout }}",
            "Risk Level":        "={{ $('Predict Stockout Risk').item.json.output.risk_level }}",
            "Reorder Qty":       "={{ $('Predict Stockout Risk').item.json.output.recommended_reorder_qty }}",
            "Reorder Triggered": "={{ $('Predict Stockout Risk').item.json.output.should_reorder }}",
            "Reasoning":         "={{ $('Predict Stockout Risk').item.json.output.reasoning }}"
          }
        }
      },
      "credentials": { "googleSheetsOAuth2Api": { "id": "gsheets-cred", "name": "Google Sheets OAuth2" } },
      "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 2000, "onError": "continueErrorOutput"
    }
  ],
  "connections": {
    "Daily Inventory Check":  { "main": [[{ "node": "Fetch All Products",      "type": "main", "index": 0 }]] },
    "Fetch All Products":     { "main": [[{ "node": "Fetch Recent Orders",      "type": "main", "index": 0 }]] },
    "Fetch Recent Orders":    { "main": [[{ "node": "Compute Sales Velocity",   "type": "main", "index": 0 }]] },
    "Compute Sales Velocity": { "main": [[{ "node": "Predict Stockout Risk",    "type": "main", "index": 0 }]] },
    "OpenAI — Predict":       { "ai_languageModel": [[{ "node": "Predict Stockout Risk", "type": "ai_languageModel", "index": 0 }]] },
    "Stockout Risk Schema":   { "ai_outputParser":  [[{ "node": "Predict Stockout Risk", "type": "ai_outputParser",  "index": 0 }]] },
    "Predict Stockout Risk":  { "main": [[{ "node": "Should Reorder?",          "type": "main", "index": 0 }]] },
    "Should Reorder?": {
      "main": [
        [{ "node": "Send Reorder Email",   "type": "main", "index": 0 }],
        [{ "node": "Log to Google Sheets", "type": "main", "index": 0 }]
      ]
    },
    "Send Reorder Email": { "main": [[{ "node": "Log to Google Sheets", "type": "main", "index": 0 }]] }
  },
  "pinData": {},
  "settings": { "executionOrder": "v1", "saveManualExecutions": true, "callerPolicy": "workflowsFromSameOwner" },
  "staticData": null,
  "tags": ["E-Commerce", "Shopify", "Inventory", "AI", "Reorder"],
  "triggerCount": 1,
  "active": false
}
