{
 "name": "وكيل الفواتير — اسأل أبو خليفة",
 "nodes": [
  {
   "parameters": {
    "updates": [
     "messages"
    ],
    "options": {}
   },
   "id": "ddb58715-3ea8-407e-9bbf-ad3485463ad2",
   "name": "رسالة واتساب",
   "type": "n8n-nodes-base.whatsAppTrigger",
   "typeVersion": 1,
   "position": [
    -880,
    0
   ],
   "credentials": {
    "whatsAppTriggerApi": {
     "id": "",
     "name": "WhatsApp OAuth (App ID + App Secret)"
    }
   },
   "webhookId": "d650bc38-876e-45d2-a00e-b81c04828ce7"
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "81494884-6ecc-4d76-8383-4688d621a089",
       "leftValue": "={{ $json.messages?.[0]?.type === 'image' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "53092a2d-9446-4279-9fc8-71bfa29d4cb6",
   "name": "صورة؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    -660,
    0
   ]
  },
  {
   "parameters": {
    "resource": "media",
    "operation": "mediaUrlGet",
    "mediaGetId": "={{ $json.messages[0].image.id }}"
   },
   "id": "cfb1ae19-a36e-49ee-aca2-4fda5768e88d",
   "name": "رابط الصورة",
   "type": "n8n-nodes-base.whatsApp",
   "typeVersion": 1.1,
   "position": [
    -440,
    -20
   ],
   "credentials": {
    "whatsAppApi": {
     "id": "",
     "name": "WhatsApp (Access token + Business Account ID)"
    }
   }
  },
  {
   "parameters": {
    "url": "={{ $json.url }}",
    "authentication": "predefinedCredentialType",
    "nodeCredentialType": "whatsAppApi",
    "options": {
     "response": {
      "response": {
       "responseFormat": "file"
      }
     }
    }
   },
   "id": "701b801d-3aec-4c0c-92b6-e816c4ae81cd",
   "name": "تنزيل الصورة",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    -220,
    -20
   ],
   "credentials": {
    "whatsAppApi": {
     "id": "",
     "name": "WhatsApp (Access token + Business Account ID)"
    }
   }
  },
  {
   "parameters": {
    "jsCode": "// يحوّل الصورة لنص base64 عشان نرسلها للذكاء الاصطناعي\nconst buf = await this.helpers.getBinaryDataBuffer(0, 'data');\nconst mime = $input.first().binary.data.mimeType || 'image/jpeg';\nreturn [{ json: { b64: buf.toString('base64'), mime } }];"
   },
   "id": "c4be19ec-07d0-4682-98d4-ff7a37be7d04",
   "name": "الصورة",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    0,
    -20
   ]
  },
  {
   "parameters": {
    "method": "POST",
    "url": "https://api.anthropic.com/v1/messages",
    "authentication": "genericCredentialType",
    "genericAuthType": "httpHeaderAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "anthropic-version",
       "value": "2023-06-01"
      }
     ]
    },
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify({ model: 'claude-haiku-5-5', max_tokens: 4000, messages: [{ role: 'user', content: [ { type: 'image', source: { type: 'base64', media_type: $json.mime, data: $json.b64 } }, { type: 'text', text: \"اقرأ صورة الفاتورة هذي واستخرج البيانات. رد بـ JSON فقط بهذا الشكل:\\n{\\\"vendor\\\": \\\"اسم المورد كما هو مكتوب\\\", \\\"date\\\": \\\"YYYY-MM-DD\\\", \\\"invoice_no\\\": \\\"رقم الفاتورة\\\", \\\"subtotal\\\": 0, \\\"vat\\\": 0, \\\"total\\\": 0, \\\"unsure\\\": []}\\nالقواعد:\\n- التاريخ في الفواتير السعودية غالباً مكتوب يوم/شهر/سنة. حوّله لصيغة YYYY-MM-DD.\\n- الأرقام تكتبها بالأرقام الإنجليزية بدون فواصل وبدون عملة (مثال 1250.50).\\n- subtotal = الإجمالي قبل الضريبة، vat = ضريبة القيمة المضافة، total = الإجمالي شامل الضريبة، كما هي مطبوعة.\\n- إذا أي خانة مو واضحة أو مقصوصة أو عليها بقعة: لا تخمّن. حط قيمتها null وأضف اسمها في unsure.\\n- إذا الصورة مو فاتورة أصلاً: رد {\\\"not_invoice\\\": true}.\" } ] }] }) }}",
    "options": {
     "timeout": 120000
    }
   },
   "id": "f1f9ca45-58ae-4db5-bf63-f290cf181a6c",
   "name": "قراءة الفاتورة (Claude)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    220,
    -20
   ],
   "credentials": {
    "httpHeaderAuth": {
     "id": "",
     "name": "Claude API (x-api-key)"
    }
   }
  },
  {
   "parameters": {
    "jsCode": "// يفحص الأرقام بالكود (ما نعتمد على الذكاء الاصطناعي في الحساب)\nconst raw = $input.first().json;\n// Claude يرجّع أكثر من جزء (تفكير + نص): ناخذ جزء النص\nlet txt = (raw.content || []).filter(c => c.type === 'text').map(c => c.text).join('\\n') || raw.message?.content || '';\nconst toEn = s => String(s).replace(/[٠-٩]/g, d => '٠١٢٣٤٥٦٧٨٩'.indexOf(d)).replace(/[٬,]/g, '').replace('٫', '.');\nlet ai = {};\ntry { ai = JSON.parse(txt.slice(txt.indexOf('{'), txt.lastIndexOf('}') + 1)); } catch (e) { ai = { unsure: ['كل الفاتورة'] }; }\nif (ai.not_invoice) return [{ json: { not_invoice: true, reply: 'هذي الصورة ما تبين إنها فاتورة. صوّر الفاتورة نفسها وأرسلها.' } }];\nconst num = v => (v === null || v === undefined || v === '' || isNaN(Number(toEn(v)))) ? null : Math.round(Number(toEn(v)) * 100) / 100;\nconst sub = num(ai.subtotal), vat = num(ai.vat), total = num(ai.total);\nconst why = [];\nconst names = { vendor: 'اسم المورد', date: 'التاريخ', invoice_no: 'رقم الفاتورة', subtotal: 'المبلغ قبل الضريبة', vat: 'الضريبة', total: 'الإجمالي' };\nfor (const k of (ai.unsure || [])) why.push(`${names[k] || k} مو واضح`);\nif (total === null && !why.some(w => w.startsWith('الإجمالي'))) why.push('الإجمالي مو واضح');\nif (!ai.vendor) why.push('اسم المورد ناقص');\nconst date = toEn(ai.date || '');\nif (!/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) why.push('التاريخ مو واضح');\nif (sub !== null && vat !== null && total !== null) {\n  if (Math.abs(sub + vat - total) > 0.05) why.push(`المبلغ + الضريبة (${(sub + vat).toFixed(2)}) ما يساوي الإجمالي (${total.toFixed(2)})`);\n  if (Math.abs(sub * 0.15 - vat) > 0.06) why.push('الضريبة مو 15% من المبلغ');\n}\nconst ok = why.length === 0;\nreturn [{ json: {\n  'التاريخ': date, 'المورد': ai.vendor || '', 'رقم الفاتورة': toEn(ai.invoice_no || ''),\n  'قبل الضريبة': sub, 'الضريبة': vat, 'الإجمالي': total,\n  'الحالة': ok ? '✅' : '⚠️ راجعها', 'ملاحظة': why.join('، '),\n  'أضيفت في': $now.setZone('Asia/Riyadh').toFormat('yyyy-MM-dd HH:mm'),\n  reply: ok ? `✅ سجّلت فاتورة ${ai.vendor}: ${total} ريال (الضريبة ${vat}).`\n            : `⚠️ سجّلت فاتورة ${ai.vendor || 'بدون اسم'} بس عليها علامة صفرا: ${why.join('، ')}. افتح الجدول وصحّح الخانة، أو صوّرها مرة ثانية أوضح.`,\n}}];"
   },
   "id": "9493fedc-f6d5-45bd-8b15-5be4e2a6a738",
   "name": "فحص الأرقام",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    440,
    0
   ]
  },
  {
   "parameters": {
    "operation": "append",
    "documentId": {
     "__rl": true,
     "mode": "url",
     "value": "حط هنا رابط جدول Google Sheets"
    },
    "sheetName": {
     "__rl": true,
     "mode": "list",
     "value": "gid=0",
     "cachedResultName": "Sheet1"
    },
    "columns": {
     "mappingMode": "defineBelow",
     "value": {
      "التاريخ": "={{ $json['التاريخ'] }}",
      "المورد": "={{ $json['المورد'] }}",
      "رقم الفاتورة": "={{ $json['رقم الفاتورة'] }}",
      "قبل الضريبة": "={{ $json['قبل الضريبة'] }}",
      "الضريبة": "={{ $json['الضريبة'] }}",
      "الإجمالي": "={{ $json['الإجمالي'] }}",
      "الحالة": "={{ $json['الحالة'] }}",
      "ملاحظة": "={{ $json['ملاحظة'] }}",
      "أضيفت في": "={{ $json['أضيفت في'] }}"
     },
     "matchingColumns": [],
     "schema": [
      {
       "id": "التاريخ",
       "displayName": "التاريخ",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "المورد",
       "displayName": "المورد",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "رقم الفاتورة",
       "displayName": "رقم الفاتورة",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "قبل الضريبة",
       "displayName": "قبل الضريبة",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "الضريبة",
       "displayName": "الضريبة",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "الإجمالي",
       "displayName": "الإجمالي",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "الحالة",
       "displayName": "الحالة",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "ملاحظة",
       "displayName": "ملاحظة",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      },
      {
       "id": "أضيفت في",
       "displayName": "أضيفت في",
       "required": false,
       "defaultMatch": false,
       "display": true,
       "type": "string",
       "canBeUsedToMatch": true
      }
     ]
    },
    "options": {}
   },
   "id": "4295a569-a15a-431f-bd3f-884e4908f2d6",
   "name": "إضافة صف في الجدول",
   "type": "n8n-nodes-base.googleSheets",
   "typeVersion": 4.7,
   "position": [
    880,
    -120
   ],
   "credentials": {
    "googleSheetsOAuth2Api": {
     "id": "",
     "name": "Google Sheets"
    }
   }
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "a696ad03-bd61-4716-a489-3a2aa19cc772",
       "leftValue": "={{ $json.not_invoice !== true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "fc73377b-9b01-4dd8-a5e5-be56bcff77ba",
   "name": "فاتورة؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    660,
    -20
   ]
  },
  {
   "parameters": {
    "resource": "message",
    "operation": "send",
    "phoneNumberId": "={{ $('رسالة واتساب').item.json.metadata.phone_number_id }}",
    "recipientPhoneNumber": "={{ $('رسالة واتساب').item.json.messages[0].from }}",
    "textBody": "={{ $('فحص الأرقام').item.json.reply }}",
    "additionalFields": {}
   },
   "id": "a524668c-5da0-4434-a78b-6c58c3b9e905",
   "name": "الرد على واتساب",
   "type": "n8n-nodes-base.whatsApp",
   "typeVersion": 1.1,
   "position": [
    1100,
    -20
   ],
   "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": "قراءة الفاتورة (Claude)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "قراءة الفاتورة (Claude)": {
   "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
     }
    ]
   ]
  }
 },
 "settings": {
  "executionOrder": "v1"
 },
 "pinData": {}
}