{
 "id": "RhR4Order0000001",
 "name": "N7 สั่งซื้อ ตัดสต็อก แจ้งคลัง (หลังวางกระบวนงานใหม่)",
 "active": false,
 "nodes": [
  {
   "id": "r4n14",
   "name": "Webhook",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    300
   ],
   "parameters": {
    "httpMethod": "POST",
    "path": "r4-order",
    "responseMode": "responseNode",
    "options": {}
   },
   "webhookId": "4dcbae94-29a3-ba36-5242-f3c3928fe0fe"
  },
  {
   "id": "r4n15",
   "name": "Read stock",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    220,
    300
   ],
   "parameters": {
    "method": "POST",
    "url": "={{ $env.BUYER_API_BASE }}/sheets/read",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify({ sheet: 'สต็อก' }) }}",
    "options": {
     "timeout": 10000
    }
   },
   "onError": "continueErrorOutput",
   "retryOnFail": true,
   "maxTries": 3
  },
  {
   "id": "r4n16",
   "name": "Place order",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    440,
    300
   ],
   "parameters": {
    "jsCode": "// N7 วางกระบวนงานใหม่: ฟอร์มสั่งซื้อ → ตรวจสต็อก → ตัดสต็อก → แจ้งคลัง ในงานเดียว (เดิมคนคีย์ซ้ำ 3 ที่)\n// stock = {sku: คงเหลือ} · ตัดได้ทั้งออเดอร์หรือไม่ตัดเลย (ไม่ตัดครึ่งออเดอร์)\nfunction placeOrder(order, stock, minLeft) {\n  const need = {};\n  for (const l of order.lines || []) {\n    if (!(Number.isInteger(l.qty) && l.qty > 0)) return { ok: false, reason: \"จำนวนไม่ถูกต้อง: \" + l.sku };\n    if (!(l.sku in stock)) return { ok: false, reason: \"ไม่มีรหัสสินค้า: \" + l.sku };\n    need[l.sku] = (need[l.sku] || 0) + l.qty;\n  }\n  if (!Object.keys(need).length) return { ok: false, reason: \"ไม่มีรายการ\" };\n  const short = Object.keys(need).filter((k) => stock[k] < need[k]);\n  if (short.length) return { ok: false, reason: \"สต็อกไม่พอ: \" + short.join(\", \") };\n  const after = { ...stock };\n  for (const k in need) after[k] -= need[k];\n  const low = Object.keys(need).filter((k) => after[k] <= minLeft);\n  return { ok: true, stock: after, notify: { to: \"คลัง\", text: `ออเดอร์ ${order.id}: ` + Object.entries(need).map(([k, q]) => `${k}×${q}`).join(\", \") }, low };\n}\n\n\n\nconst o = $(\"Webhook\").first().json.body;\nconst r = placeOrder({ id: o.id, lines: o.lines }, $input.first().json.stock, Number($env.LOW_STOCK || 2));\nreturn [{ json: { ...r, code: r.ok ? 200 : 409, response: r.ok ? { ok: true, low: r.low } : { ok: false, reason: r.reason } } }];"
   }
  },
  {
   "id": "r4n17",
   "name": "OK?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2,
   "position": [
    660,
    300
   ],
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "c1",
       "leftValue": "={{ $json.ok }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   }
  },
  {
   "id": "r4n18",
   "name": "Write stock",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    880,
    200
   ],
   "parameters": {
    "method": "POST",
    "url": "={{ $env.BUYER_API_BASE }}/sheets/write",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify({ sheet: 'สต็อก', stock: $json.stock }) }}",
    "options": {
     "timeout": 10000
    }
   },
   "onError": "continueErrorOutput",
   "retryOnFail": true,
   "maxTries": 3
  },
  {
   "id": "r4n19",
   "name": "Notify warehouse",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1100,
    200
   ],
   "parameters": {
    "method": "POST",
    "url": "={{ $env.BUYER_API_BASE }}/notify",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($('Place order').first().json.notify) }}",
    "options": {
     "timeout": 10000
    }
   },
   "onError": "continueErrorOutput",
   "retryOnFail": true,
   "maxTries": 3
  },
  {
   "id": "r4n20",
   "name": "Respond",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    1320,
    300
   ],
   "parameters": {
    "respondWith": "json",
    "responseBody": "={{ JSON.stringify($json.response !== undefined ? $json.response : $(\"Place order\").first().json.response) }}",
    "options": {
     "responseCode": "={{ $json.code !== undefined ? $json.code : $(\"Place order\").first().json.code }}"
    }
   }
  }
 ],
 "connections": {
  "Webhook": {
   "main": [
    [
     {
      "node": "Read stock",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Read stock": {
   "main": [
    [
     {
      "node": "Place order",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Place order": {
   "main": [
    [
     {
      "node": "OK?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "OK?": {
   "main": [
    [
     {
      "node": "Write stock",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Respond",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Write stock": {
   "main": [
    [
     {
      "node": "Notify warehouse",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Notify warehouse": {
   "main": [
    [
     {
      "node": "Respond",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "settings": {
  "executionOrder": "v1",
  "saveDataErrorExecution": "all"
 },
 "pinData": {}
}