{
  "name": "inventory-management-automation-workflow",
  "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": "a2f32acf-aadf-49fd-8c40-bf66203dc7d8",
      "name": "Send Order to Suplier",
      "webhookId": "180664d7-1b1b-4ad1-84a5-7f7372d4ec00",
      "credentials": {
        "gmailOAuth2": {
          "id": "YpJCpL7lQqKeGFdc",
          "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": "5cb1bf0b-3b75-456a-9f8d-517a855b4a0b",
      "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": "92fbcb27-8beb-48e7-8503-94a7a3c97855",
      "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": "c0a96cef-ec47-4236-ae81-50aab75eaef8",
      "name": "Order Handling"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1472,
        -176
      ],
      "id": "4a4f2074-b402-4ae2-b9d7-5ae9af6b4bc3",
      "name": "No Operation, do nothing"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        864,
        -16
      ],
      "id": "2fa6e019-80ea-4630-8bd2-cad2ec01b131",
      "name": "Loop Over Items"
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {}
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -128,
        -112
      ],
      "id": "f83c1165-077e-4e75-83bd-0b6d921c8777",
      "name": "Trigger Everyday"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw",
          "mode": "list",
          "cachedResultName": "Inventory Management",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Inventory_Stock",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw/edit#gid=0"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "Inventory Status",
              "lookupValue": "Low Stock"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        64,
        -112
      ],
      "id": "5a939b39-f5bb-4a3c-b680-40b146768e8d",
      "name": "Get Low Stock Product",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "WdaCQmtoNquNSoAA",
          "name": "Google Sheets"
        }
      }
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw",
          "mode": "list",
          "cachedResultName": "Inventory Management",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": 1455016343,
          "mode": "list",
          "cachedResultName": "Purchase Order",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw/edit#gid=1455016343"
        },
        "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": "f302f755-752c-41e4-a910-9e0092b82d90",
      "name": "Get Purchase Order",
      "alwaysOutputData": true,
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "WdaCQmtoNquNSoAA",
          "name": "Google Sheets"
        }
      }
    },
    {
      "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": "03a28f65-5eed-4ea2-8b44-491ccde04fd5",
      "name": "Check Record Exists Or Not"
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw",
          "mode": "list",
          "cachedResultName": "Inventory Management",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": 1455016343,
          "mode": "list",
          "cachedResultName": "Purchase Order",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw/edit#gid=1455016343"
        },
        "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": "528a140d-e6ca-42fe-81c2-b651a2a5ee67",
      "name": "Store a Purchase Order",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "WdaCQmtoNquNSoAA",
          "name": "Google Sheets"
        }
      }
    },
    {
      "parameters": {
        "content": "### Sample Sheet\nhttps://docs.google.com/spreadsheets/d/15bLKtbrz1Ic7vJQZ7iIDxkL4rV9mLBpMWdTCZwehGUw/edit#gid=0",
        "height": 96,
        "width": 432
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -128,
        -272
      ],
      "typeVersion": 1,
      "id": "18008d88-bc7d-4b61-aff0-6953c92b7301",
      "name": "Sticky Note"
    }
  ],
  "pinData": {},
  "connections": {
    "Send Order to Suplier": {
      "main": [
        []
      ]
    },
    "Switch Email & PO": {
      "main": [
        [
          {
            "node": "Send Order to Suplier",
            "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": "1e62fc12-f900-49dc-9bb7-e435891bcdd5",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "9272721148ea09184b6bbb7ce6219dab088562dd450e2df8280d57c2e34c7d84"
  },
  "id": "fVWo35RSsCtpI19a",
  "tags": []
}