{
 "name": "وكيل واتساب المتجر — اسأل أبو خليفة",
 "nodes": [
  {
   "parameters": {
    "updates": [
     "messages"
    ],
    "options": {}
   },
   "id": "11704fc5-2751-46e1-82ac-a4c71740533c",
   "name": "رسالة واتساب",
   "type": "n8n-nodes-base.whatsAppTrigger",
   "typeVersion": 1,
   "position": [
    -440,
    0
   ],
   "credentials": {
    "whatsAppTriggerApi": {
     "id": "",
     "name": "WhatsApp OAuth (App ID + App Secret)"
    }
   }
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "75300e99-76eb-4017-8d90-c6e463756ad6",
       "leftValue": "={{ $json.messages?.[0]?.type === 'text' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "2aad493f-98ef-4d98-b7ce-b54517c50818",
   "name": "رسالة نصية؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    -220,
    0
   ]
  },
  {
   "parameters": {
    "assignments": {
     "assignments": [
      {
       "id": "973b4f66-a58e-4f80-8f23-bf993aff2ecd",
       "name": "shop_name",
       "type": "string",
       "value": "متجر الأناقة"
      },
      {
       "id": "6464f9b7-b6d2-496f-9e43-5d47db8d8933",
       "name": "inventory_csv_url",
       "type": "string",
       "value": "ضع هنا رابط CSV لجدول المخزون (Google Sheets > نشر على الويب > CSV)"
      }
     ]
    },
    "options": {}
   },
   "id": "c44272d7-d08e-49c4-a884-ae54b54e7d05",
   "name": "الإعدادات",
   "type": "n8n-nodes-base.set",
   "typeVersion": 3.4,
   "position": [
    0,
    -20
   ]
  },
  {
   "parameters": {
    "url": "={{ $json.inventory_csv_url }}",
    "options": {
     "response": {
      "response": {
       "responseFormat": "text"
      }
     }
    }
   },
   "id": "49c6860d-9b6f-4f97-9180-5e33a84889cb",
   "name": "جلب المخزون",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    200,
    -20
   ]
  },
  {
   "parameters": {
    "jsCode": "// يجهّز بيانات الرسالة + المخزون من ملف CSV (Google Sheets منشور كـ CSV)\nconst msg = $('رسالة واتساب').first().json;\nconst m = msg.messages[0];\nconst csv = $input.first().json.data || '';\nconst rows = csv.trim().split(/\\r?\\n/).map(l => l.split(',').map(c => c.trim()));\nconst head = rows.shift().map(h => h.toLowerCase());\nconst inventory = rows.filter(r => r.length >= head.length).map(r => Object.fromEntries(head.map((h, i) => [h, r[i]])));\nconst inventory_text = inventory.map(p => `- sku: ${p.sku} | ${p.name} | مقاس ${p.size} | ${p.price} ريال | الكمية ${p.stock}`).join('\\n');\nreturn [{ json: {\n  shop: $('الإعدادات').first().json.shop_name,\n  customer: m.from,\n  customer_name: (msg.contacts && msg.contacts[0] && msg.contacts[0].profile && msg.contacts[0].profile.name) || '',\n  text: m.text.body,\n  phone_number_id: msg.metadata.phone_number_id,\n  inventory, inventory_text,\n}}];"
   },
   "id": "e37f4e46-e0b4-4fb8-b7ad-f6c6be036b77",
   "name": "تجهيز البيانات",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    400,
    -20
   ]
  },
  {
   "parameters": {
    "promptType": "define",
    "text": "={{ $json.text }}",
    "hasOutputParser": true,
    "options": {
     "systemMessage": "=أنت موظف المبيعات في «{{ $('تجهيز البيانات').item.json.shop }}» على واتساب. ترد بلهجة سعودية بيضاء، مختصر وودود (سطرين أو ثلاثة).\n\nالمخزون الحالي (هذا هو المصدر الوحيد للأسعار والتوفر):\n{{ $('تجهيز البيانات').item.json.inventory_text }}\n\nالقواعد:\n1. لا تخترع منتجاً أو سعراً أو مقاساً غير موجود في المخزون. إذا ما لقيت المنتج قل إنه غير متوفر واقترح أقرب بديل من القائمة.\n2. إذا الكمية 0 فالمنتج غير متوفر.\n3. إذا الزبون ما حدد المقاس أو اللون اسأله قبل أي شيء.\n4. إذا الزبون أكّد أنه يبي يشتري منتجاً محدداً (sku معروف) وكمية، ضع wants_payment = true و sku و qty. لا تكتب رابط الدفع بنفسك، النظام يضيفه.\n5. الشكاوى أو الاسترجاع أو أي شيء خارج البيع: قل له إن موظفاً بشرياً بيتواصل معه، وضع needs_human = true.\n6. لا تطلب بيانات بطاقة أبداً. الدفع فقط عبر الرابط.\n\nأعد الرد فقط بالصيغة المطلوبة (JSON)."
    }
   },
   "id": "cb47deb2-c4d2-47ca-92aa-10d6051bbf8c",
   "name": "وكيل المبيعات",
   "type": "@n8n/n8n-nodes-langchain.agent",
   "typeVersion": 3.1,
   "position": [
    640,
    -20
   ]
  },
  {
   "parameters": {
    "model": {
     "__rl": true,
     "mode": "id",
     "value": "claude-haiku-5-5"
    },
    "options": {
     "maxTokensToSample": 2000
    }
   },
   "id": "2ae7c61d-86fa-4db9-8d10-6a16f17c4ce1",
   "name": "Claude Haiku",
   "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
   "typeVersion": 1.6,
   "position": [
    580,
    200
   ],
   "credentials": {
    "anthropicApi": {
     "id": "",
     "name": "Anthropic API"
    }
   }
  },
  {
   "parameters": {
    "sessionIdType": "customKey",
    "sessionKey": "={{ $('تجهيز البيانات').item.json.customer }}",
    "contextWindowLength": 10
   },
   "id": "e81f42a4-020d-49a0-8680-9a9c9b07723b",
   "name": "ذاكرة المحادثة",
   "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
   "typeVersion": 1.3,
   "position": [
    720,
    200
   ]
  },
  {
   "parameters": {
    "schemaType": "fromJson",
    "jsonSchemaExample": "{\"reply\": \"إيه متوفر ✅ مقاس XL بـ 149 ريال، تبي أرسل لك رابط الدفع؟\", \"wants_payment\": false, \"sku\": \"\", \"qty\": 0, \"needs_human\": false}"
   },
   "id": "fed49c4c-19fc-4139-9b4f-60bcc9a62e8d",
   "name": "صيغة الرد",
   "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
   "typeVersion": 1.3,
   "position": [
    860,
    200
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "678a1cdf-d364-4ad0-85bc-0dc09487eb34",
       "leftValue": "={{ $json.output.wants_payment === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "11187bf9-da09-431f-9fea-a743fff18e82",
   "name": "يبي يدفع؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    940,
    -20
   ]
  },
  {
   "parameters": {
    "jsCode": "// يحسب المبلغ من المخزون (ما نعتمد على الذكاء الاصطناعي في الأسعار)\nconst ai = $input.first().json.output;\nconst d = $('تجهيز البيانات').first().json;\nconst p = d.inventory.find(x => String(x.sku).toLowerCase() === String(ai.sku).toLowerCase());\nconst qty = Math.max(1, parseInt(ai.qty || 1, 10));\nif (!p) return [{ json: { ok: false, text: 'آسفين، ما لقيت هذا المنتج. تقدر تقول لي اسمه أو مقاسه؟' } }];\nif (Number(p.stock) < qty) return [{ json: { ok: false, text: `آسفين، المتوفر من ${p.name} مقاس ${p.size} هو ${p.stock} فقط.` } }];\nconst total = Number(p.price) * qty;\nreturn [{ json: { ok: true, amount: Math.round(total * 100), total, description: `${p.name} - مقاس ${p.size} × ${qty}`, sku: p.sku, qty, reply: ai.reply } }];"
   },
   "id": "0c2a1c4c-de75-431a-b54d-99c84aa704f8",
   "name": "حساب المبلغ من المخزون",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1160,
    -140
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "90bd562a-6785-4667-9e9d-ee67acbf03f7",
       "leftValue": "={{ $json.ok === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "ae81dbc7-e841-4687-9bb3-19e0d859e174",
   "name": "المنتج متوفر؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1380,
    -140
   ]
  },
  {
   "parameters": {
    "method": "POST",
    "url": "https://api.moyasar.com/v1/invoices",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify({ amount: $json.amount, currency: 'SAR', description: $json.description, metadata: { whatsapp: $('تجهيز البيانات').item.json.customer, sku: $json.sku, qty: String($json.qty) } }) }}",
    "options": {},
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth"
   },
   "id": "870bc598-5e04-4cc3-88ef-7d7bfc3566c4",
   "name": "رابط دفع ميسّر",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1600,
    -220
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Moyasar (Secret key + empty password)"
    }
   }
  },
  {
   "parameters": {
    "assignments": {
     "assignments": [
      {
       "id": "56a8c58e-db14-40d6-9749-b9aaf941323c",
       "name": "text",
       "type": "string",
       "value": "={{ $('حساب المبلغ من المخزون').item.json.reply }}\n\n🧾 {{ $('حساب المبلغ من المخزون').item.json.description }}\n💰 المجموع: {{ $('حساب المبلغ من المخزون').item.json.total }} ريال\n💳 رابط الدفع: {{ $json.url }}"
      }
     ]
    },
    "options": {}
   },
   "id": "874814dd-c3a8-4a78-a571-2de4e57d1229",
   "name": "رسالة الدفع",
   "type": "n8n-nodes-base.set",
   "typeVersion": 3.4,
   "position": [
    1820,
    -220
   ]
  },
  {
   "parameters": {
    "assignments": {
     "assignments": [
      {
       "id": "596749ef-a7a1-4a1e-80d2-15c0a047c3e0",
       "name": "text",
       "type": "string",
       "value": "={{ $('وكيل المبيعات').item.json.output.reply }}"
      }
     ]
    },
    "options": {}
   },
   "id": "32cf2245-642f-4976-b99e-ba1e3ff0c6fb",
   "name": "رد عادي",
   "type": "n8n-nodes-base.set",
   "typeVersion": 3.4,
   "position": [
    1160,
    120
   ]
  },
  {
   "parameters": {
    "resource": "message",
    "operation": "send",
    "phoneNumberId": "={{ $('تجهيز البيانات').item.json.phone_number_id }}",
    "recipientPhoneNumber": "={{ $('تجهيز البيانات').item.json.customer }}",
    "textBody": "={{ $json.text }}",
    "additionalFields": {}
   },
   "id": "d5ee3807-af53-4025-9a62-c2071ab05ddf",
   "name": "إرسال الرد على واتساب",
   "type": "n8n-nodes-base.whatsApp",
   "typeVersion": 1.1,
   "position": [
    2060,
    0
   ],
   "credentials": {
    "whatsAppApi": {
     "id": "",
     "name": "WhatsApp (Access token + Business Account ID)"
    }
   }
  }
 ],
 "connections": {
  "رسالة واتساب": {
   "main": [
    [
     {
      "node": "رسالة نصية؟",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "رسالة نصية؟": {
   "main": [
    [
     {
      "node": "الإعدادات",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "الإعدادات": {
   "main": [
    [
     {
      "node": "جلب المخزون",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "جلب المخزون": {
   "main": [
    [
     {
      "node": "تجهيز البيانات",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "تجهيز البيانات": {
   "main": [
    [
     {
      "node": "وكيل المبيعات",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Claude Haiku": {
   "ai_languageModel": [
    [
     {
      "node": "وكيل المبيعات",
      "type": "ai_languageModel",
      "index": 0
     }
    ]
   ]
  },
  "ذاكرة المحادثة": {
   "ai_memory": [
    [
     {
      "node": "وكيل المبيعات",
      "type": "ai_memory",
      "index": 0
     }
    ]
   ]
  },
  "صيغة الرد": {
   "ai_outputParser": [
    [
     {
      "node": "وكيل المبيعات",
      "type": "ai_outputParser",
      "index": 0
     }
    ]
   ]
  },
  "وكيل المبيعات": {
   "main": [
    [
     {
      "node": "يبي يدفع؟",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "يبي يدفع؟": {
   "main": [
    [
     {
      "node": "حساب المبلغ من المخزون",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "رد عادي",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "حساب المبلغ من المخزون": {
   "main": [
    [
     {
      "node": "المنتج متوفر؟",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "المنتج متوفر؟": {
   "main": [
    [
     {
      "node": "رابط دفع ميسّر",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "إرسال الرد على واتساب",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "رابط دفع ميسّر": {
   "main": [
    [
     {
      "node": "رسالة الدفع",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "رسالة الدفع": {
   "main": [
    [
     {
      "node": "إرسال الرد على واتساب",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "رد عادي": {
   "main": [
    [
     {
      "node": "إرسال الرد على واتساب",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "settings": {
  "executionOrder": "v1"
 },
 "pinData": {}
}