{
  "name": "Low-Stock Purchase Order Automation",
  "nodes": [
    {
      "parameters": {
        "sendTo": "={{ $json.supplier_email }}",
        "subject": "={{ $json.subject }}",
        "emailType": "text",
        "message": "={{ $json.body }}",
        "options": {
          "appendAttribution": false
        }
      },
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        864,
        -208
      ],
      "id": "1f53a2f8-772b-46d7-ba9c-a8527fd5f9cc",
      "name": "Send Order to Supplier",
      "webhookId": "50f2a1c5-f379-401b-9c5a-4dad98fc604b",
      "credentials": {
        "gmailOAuth2": {
          "id": "emmuhpJGs7nAZSDK",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.type }}",
                    "rightValue": "email",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "6167fcaf-6603-44b3-971f-0d4157015fae"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Email"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "97d1cb23-55d5-45de-afcb-89c71ba38ec1",
                    "leftValue": "={{ $json.type }}",
                    "rightValue": "po",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Purchase Order"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        640,
        -112
      ],
      "id": "ba4dacf8-f55e-4e49-9b73-af4b1acb5916",
      "name": "Switch Email & PO"
    },
    {
      "parameters": {
        "jsCode": "const supplierOrders = {};\nconst orderDate = new Date().toISOString().split(\"T\")[0];\nconst poNumber = `PO-${Date.now()}`;\n\n// Group by supplier\nfor (const item of items) {\n  const { sku, name, supplier, supplier_email, reorder_needed, order_qty, available, threshold } = item.json;\n\n  if (reorder_needed) {\n    if (!supplierOrders[supplier_email]) {\n      supplierOrders[supplier_email] = {\n        supplier,\n        supplierEmail: supplier_email,\n        items: []\n      };\n    }\n\n    supplierOrders[supplier_email].items.push({\n      sku,\n      name,\n      orderQty: order_qty,\n      available,\n      threshold\n    });\n  }\n}\n\nconst results = [];\n\nfor (const supplierEmail in supplierOrders) {\n  const order = supplierOrders[supplierEmail];\n  const itemList = order.items.map(i =>\n    `- ${i.name} (SKU: ${i.sku})\\n   Order Qty: ${i.orderQty}`\n  ).join(\"\\n\");\n\n  // Email\n  const emailSubject = `Purchase Order ${poNumber} - ${order.supplier}`;\n  const emailBody = `Dear ${order.supplier},\\n\\n` +\n    `We would like to place the following order:\\n\\n${itemList}\\n\\n` +\n    `PO Number: ${poNumber}\\nOrder Date: ${orderDate}\\n\\n` +\n    `Please confirm availability and expected delivery.\\n\\n` +\n    `Best regards,\\nProcurement Team`;\n\n  results.push({\n    json: {\n      type: \"email\",\n      supplier: order.supplier,\n      supplier_email: order.supplierEmail,\n      subject: emailSubject,\n      body: emailBody\n    }\n  });\n\n  // PO Rows (for Sheet)\n  for (const i of order.items) {\n    results.push({\n      json: {\n        type: \"po\",\n        po_number: poNumber,\n        supplier: order.supplier,\n        supplier_email: order.supplierEmail,\n        sku: i.sku,\n        item_name: i.name,\n        available: i.available,\n        threshold: i.threshold,\n        order_qty: i.orderQty,\n        order_date: orderDate\n      }\n    });\n  }\n}\n\nreturn results;\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        448,
        -112
      ],
      "id": "18edcac9-9e1b-4687-9836-b095b3b44cfe",
      "name": "Generate Email & PO"
    },
    {
      "parameters": {
        "jsCode": "const results = [];\n\nfor (const item of items) {\n  const sku = item.json.sku;\n  const name = item.json.Name;\n  const supplier = item.json.supplier;\n  const supplierEmail = item.json.supplier_email;\n\n  const available = Number(item.json[\"Available Qty\"]) || 0;\n  const threshold = Number(item.json[\"Min. Threshold\"]) || 0;\n  const minOrder = Number(item.json[\"Min Order\"]) || 0;\n  const maxOrder = Number(item.json[\"Max Order\"]) || 0;\n\n  let reorderNeeded = false;\n  let orderQty = 0;\n\n  // Check if reorder needed\n  if (available < threshold) {\n    reorderNeeded = true;\n\n    // Basic calculation: how much short\n    orderQty = threshold - available;\n\n    // Ensure reorderQty >= Min Order\n    if (orderQty < minOrder) {\n      orderQty = minOrder;\n    }\n\n    // Ensure reorderQty <= Max Order\n    if (orderQty > maxOrder) {\n      orderQty = maxOrder;\n    }\n  }\n\n  results.push({\n    json: {\n      sku,\n      name,\n      supplier,\n      supplier_email: supplierEmail,\n      available,\n      threshold,\n      minOrder,\n      maxOrder,\n      reorder_needed: reorderNeeded,\n      order_qty: orderQty\n    }\n  });\n}\n\nreturn results;\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        256,
        -112
      ],
      "id": "9f6f8830-84ec-43cb-9e60-5ba7339a3119",
      "name": "Order Handling"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1472,
        -176
      ],
      "id": "8e48e3a7-a86e-41b6-9ce1-f196c4ac7d45",
      "name": "No Operation, do nothing"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        864,
        -16
      ],
      "id": "9bb96945-6088-4ebc-bfb4-40adf95a16f5",
      "name": "Loop Over Items"
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {}
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -128,
        -112
      ],
      "id": "3fd4fa38-2e52-4afd-9c03-d21aa76ce3f6",
      "name": "Trigger Everyday"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw",
          "mode": "list",
          "cachedResultName": "Inventory Management"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Inventory_Stock"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "Inventory Status",
              "lookupValue": "Low Stock"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        64,
        -112
      ],
      "id": "f32d2283-14f9-45a9-9ca9-7618ba221721",
      "name": "Get Low Stock Product",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "GojUvCMDXbhY8HrB",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw",
          "mode": "list",
          "cachedResultName": "Inventory Management"
        },
        "sheetName": {
          "__rl": true,
          "value": 1455016343,
          "mode": "list",
          "cachedResultName": "Purchase Order"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "SKU",
              "lookupValue": "={{ $json.sku }}"
            },
            {
              "lookupColumn": "Order Status",
              "lookupValue": "In Progress"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1072,
        -160
      ],
      "id": "c37a9260-291f-48d0-8a1b-9d0d9d7c63af",
      "name": "Get Purchase Order",
      "alwaysOutputData": true,
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "GojUvCMDXbhY8HrB",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "f68f512d-48ad-44f6-bbcf-36646c290250",
              "leftValue": "={{ $json['Order Status'] }}",
              "rightValue": 1,
              "operator": {
                "type": "string",
                "operation": "exists",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1264,
        -160
      ],
      "id": "f9b453cf-6975-4360-b33e-5cfa13042a24",
      "name": "Check Record Exists Or Not"
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw",
          "mode": "list",
          "cachedResultName": "Inventory Management"
        },
        "sheetName": {
          "__rl": true,
          "value": 1455016343,
          "mode": "list",
          "cachedResultName": "Purchase Order"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "PO Number": "={{ $('Generate Email & PO').item.json.po_number }}",
            "Supplier": "={{ $('Generate Email & PO').item.json.supplier }}",
            "Supplier Email": "={{ $('Generate Email & PO').item.json.supplier_email }}",
            "SKU": "={{ $('Generate Email & PO').item.json.sku }}",
            "Item Name": "={{ $('Generate Email & PO').item.json.item_name }}",
            "Available": "={{ $('Generate Email & PO').item.json.available }}",
            "Order Date": "={{ $('Generate Email & PO').item.json.order_date }}",
            "Order Status": "In Progress",
            "Order Qty": "={{ $('Switch Email & PO').item.json.order_qty }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "PO Number",
              "displayName": "PO Number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Supplier",
              "displayName": "Supplier",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Supplier Email",
              "displayName": "Supplier Email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "SKU",
              "displayName": "SKU",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Item Name",
              "displayName": "Item Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Available",
              "displayName": "Available",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Order Qty",
              "displayName": "Order Qty",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Order Date",
              "displayName": "Order Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Order Status",
              "displayName": "Order Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1504,
        16
      ],
      "id": "93d79dc2-967d-4d38-8b1d-c1eb47cd474b",
      "name": "Store a Purchase Order",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "GojUvCMDXbhY8HrB",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "content": "### Data Setup\nCreate your own spreadsheet with these tabs/columns, then select it in the Google Sheets nodes:\n- **Inventory Management → Inventory_Stock**: `Inventory Status`\n- **Inventory Management → Purchase Order**: `SKU`, `Order Status`, `PO Number`, `Supplier`, `Supplier Email`, `Item Name`, `Available`, `Order Qty`, `Order Date`",
        "height": 96,
        "width": 432
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -128,
        -272
      ],
      "typeVersion": 1,
      "id": "a0fd33cc-5054-4162-aacc-3da72bf85be0",
      "name": "Sticky Note"
    }
  ],
  "pinData": {},
  "connections": {
    "Send Order to Supplier": {
      "main": [
        []
      ]
    },
    "Switch Email & PO": {
      "main": [
        [
          {
            "node": "Send Order to Supplier",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Email & PO": {
      "main": [
        [
          {
            "node": "Switch Email & PO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Order Handling": {
      "main": [
        [
          {
            "node": "Generate Email & PO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "No Operation, do nothing": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [],
        [
          {
            "node": "Get Purchase Order",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trigger Everyday": {
      "main": [
        [
          {
            "node": "Get Low Stock Product",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Low Stock Product": {
      "main": [
        [
          {
            "node": "Order Handling",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Purchase Order": {
      "main": [
        [
          {
            "node": "Check Record Exists Or Not",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Record Exists Or Not": {
      "main": [
        [
          {
            "node": "No Operation, do nothing",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Store a Purchase Order",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store a Purchase Order": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "ec02c4ae-c783-44b0-bddc-2782950776a1",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "f1c26778ec36097a9722a22c47c5e9c01f00b8862dadd0121ec118026a370fa6"
  },
  "id": "jTygrSTxC99dCUNJ",
  "tags": []
}