{
 "name": "وكيل واتساب المتجر + تقرير المبيعات — اسأل أبو خليفة",
 "nodes": [
  {
   "parameters": {
    "updates": [
     "messages"
    ],
    "options": {}
   },
   "id": "5fd31283-2ca5-4598-8c83-bf641680e1a2",
   "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": "94263b8b-4ee9-4243-9edc-2cd35f85f695",
       "leftValue": "={{ $json.messages?.[0]?.type === 'text' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "4f3a6dec-9848-4201-b45b-0df6c3ba837d",
   "name": "رسالة نصية؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    -220,
    0
   ]
  },
  {
   "parameters": {
    "assignments": {
     "assignments": [
      {
       "id": "f894ebbf-c2ce-4f1d-ac15-b17c54c72aee",
       "name": "shop_name",
       "type": "string",
       "value": "متجر الأناقة"
      },
      {
       "id": "c9f6746b-7116-4a58-b89a-3930da73db70",
       "name": "inventory_csv_url",
       "type": "string",
       "value": "ضع هنا رابط CSV لجدول المخزون (Google Sheets > نشر على الويب > CSV)"
      },
      {
       "id": "94a16ba8-bc11-4a6f-a31d-2f20d64e6ae2",
       "name": "owner_whatsapp",
       "type": "string",
       "value": "ضع رقم جوالك بصيغة دولية بدون + (مثال 9665XXXXXXXX)"
      }
     ]
    },
    "options": {}
   },
   "id": "1bab6347-8517-48ca-98be-32ef71af4362",
   "name": "الإعدادات",
   "type": "n8n-nodes-base.set",
   "typeVersion": 3.4,
   "position": [
    0,
    -20
   ]
  },
  {
   "parameters": {
    "url": "={{ $json.inventory_csv_url }}",
    "options": {
     "response": {
      "response": {
       "responseFormat": "text"
      }
     }
    }
   },
   "id": "75f698eb-351f-403b-be62-340638528c3c",
   "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": "b591b159-2d40-44b4-add5-41d19fda540d",
   "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": "806d2838-c278-4b48-92fe-1ee3ebef5351",
   "name": "وكيل المبيعات",
   "type": "@n8n/n8n-nodes-langchain.agent",
   "typeVersion": 3.1,
   "position": [
    640,
    -20
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "51c69f3f-5d7f-4efa-8de6-cac8c71b55ed",
       "leftValue": "={{ $json.customer === String($('الإعدادات').first().json.owner_whatsapp).replace(/\\D/g, '') && $json.text.includes('تقرير') }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "23db55a4-1d3a-48ef-b32c-b6f18de87221",
   "name": "صاحب المتجر يطلب تقرير؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    780,
    -260
   ]
  },
  {
   "parameters": {
    "url": "https://api.moyasar.com/v1/invoices",
    "sendQuery": true,
    "queryParameters": {
     "parameters": [
      {
       "name": "status",
       "value": "paid"
      },
      {
       "name": "created[gt]",
       "value": "={{ $now.setZone('Asia/Riyadh').startOf('day').toISODate() }}"
      }
     ]
    },
    "options": {
     "pagination": {
      "pagination": {
       "paginationMode": "updateAParameterInEachRequest",
       "parameters": {
        "parameters": [
         {
          "type": "qs",
          "name": "page",
          "value": "={{ $pageCount + 1 }}"
         }
        ]
       },
       "paginationCompleteWhen": "other",
       "completeExpression": "={{ !$response.body.meta || !$response.body.meta.next_page }}",
       "limitPagesFetched": true,
       "maxRequests": 30
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth"
   },
   "id": "10fe31b0-aabf-40a2-909f-286267221e07",
   "name": "فواتير اليوم المدفوعة",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1000,
    -360
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Moyasar (Secret key + empty password)"
    }
   }
  },
  {
   "parameters": {
    "jsCode": "// تقرير اليوم: الفواتير المدفوعة من ميسّر + المنتجات اللي قربت تخلص\nconst d = $('تجهيز البيانات').first().json;\nconst tz = 'Asia/Riyadh';\nconst start = $now.setZone(tz).startOf('day');\nconst all = $input.all().flatMap(i => (i.json.invoices || []));\nconst today = all.filter(v => v.status === 'paid' && DateTime.fromISO(v.paid_at || v.created_at).setZone(tz) >= start);\nconst total = today.reduce((s, v) => s + Number(v.amount || 0), 0) / 100;\nconst count = {};\nfor (const v of today) {\n  const key = (v.metadata && v.metadata.sku) || v.description || 'منتج';\n  count[key] = (count[key] || 0) + Number((v.metadata && v.metadata.qty) || 1);\n}\nconst nameOf = sku => { const p = d.inventory.find(x => x.sku === sku); return p ? `${p.name} ${p.size !== '-' ? p.size : ''}`.trim() : sku; };\nconst top = Object.entries(count).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([k, q]) => `${nameOf(k)} (${q})`);\nconst low = d.inventory.filter(p => Number(p.stock) <= 2).map(p => `${p.name} ${p.size !== '-' ? p.size : ''}`.trim() + (Number(p.stock) === 0 ? ' (خلص)' : ` (باقي ${p.stock})`));\nconst last = today.map(v => DateTime.fromISO(v.paid_at || v.created_at).setZone(tz)).sort((a, b) => b - a)[0];\nconst fmt = n => n.toLocaleString('en-US', { maximumFractionDigits: 2 });\nconst lines = [\n  `📊 تقرير اليوم — ${start.setLocale('ar').toFormat('cccc d LLLL')}`,\n  `🛒 الطلبات المدفوعة: ${today.length}`,\n  `💰 المبيعات: ${fmt(total)} ريال`,\n  top.length ? `🏆 الأكثر مبيعاً: ${top.join('، ')}` : '🏆 ما فيه مبيعات اليوم للحين',\n  low.length ? `⚠️ قرب يخلص: ${low.join('، ')}` : '✅ المخزون تمام',\n];\nif (last) lines.push(`⏱️ آخر طلب مدفوع: ${last.toFormat('HH:mm')}`);\nreturn [{ json: { text: lines.join('\\n'), orders: today.length, total } }];"
   },
   "id": "7b4cb33d-2750-46c7-abc5-ac4abad17f40",
   "name": "حساب التقرير",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1220,
    -360
   ]
  },
  {
   "parameters": {
    "model": {
     "__rl": true,
     "mode": "id",
     "value": "claude-haiku-5-5"
    },
    "options": {
     "maxTokensToSample": 2000
    }
   },
   "id": "7dd7a742-2272-48f1-8e84-9f962bd22909",
   "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": "39a2e0c7-9c6d-4908-a3b6-ddc57616e6a0",
   "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": "78de2be4-4f8c-4668-a6f7-39bcf1bd93fa",
   "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": "4f3232ab-5568-4dfa-83d2-6ee1cd162c2d",
       "leftValue": "={{ $json.output.wants_payment === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "9b3111e7-c03b-421b-aadc-94621fc233db",
   "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": "b62a4a32-8678-4b96-80c3-70131f97f121",
   "name": "حساب المبلغ من المخزون",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1160,
    -140
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "70d01f95-bb85-4e6f-9998-9df4a0653a6b",
       "leftValue": "={{ $json.ok === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "54a177bb-d97e-4740-b132-c06c717f765f",
   "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": "88a42209-f204-44d0-9e32-f60adf8c819d",
   "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": "7cbbabde-61b7-48a0-bb3a-8f480abc8f3c",
       "name": "text",
       "type": "string",
       "value": "={{ $('حساب المبلغ من المخزون').item.json.reply }}\n\n🧾 {{ $('حساب المبلغ من المخزون').item.json.description }}\n💰 المجموع: {{ $('حساب المبلغ من المخزون').item.json.total }} ريال\n💳 رابط الدفع: {{ $json.url }}"
      }
     ]
    },
    "options": {}
   },
   "id": "63a01b60-789d-4cde-ba74-1cde0c7696b9",
   "name": "رسالة الدفع",
   "type": "n8n-nodes-base.set",
   "typeVersion": 3.4,
   "position": [
    1820,
    -220
   ]
  },
  {
   "parameters": {
    "assignments": {
     "assignments": [
      {
       "id": "8c3eb68c-c301-4777-86b3-c0e2f05d69b7",
       "name": "text",
       "type": "string",
       "value": "={{ $('وكيل المبيعات').item.json.output.reply }}"
      }
     ]
    },
    "options": {}
   },
   "id": "e3a79df0-6ee7-416f-bad9-7d470d2741dd",
   "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": "1b2895e3-78c0-4aa0-a8fd-996ff1b16d36",
   "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
     }
    ]
   ]
  },
  "صاحب المتجر يطلب تقرير؟": {
   "main": [
    [
     {
      "node": "فواتير اليوم المدفوعة",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "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
     }
    ]
   ]
  },
  "حساب التقرير": {
   "main": [
    [
     {
      "node": "إرسال الرد على واتساب",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "settings": {
  "executionOrder": "v1"
 },
 "pinData": {}
}