{
 "id": "karnema04Events",
 "name": "کارنما ۴ — دریافت رویدادهای کارنما (وب‌هوک)",
 "nodes": [
  {
   "parameters": {
    "httpMethod": "POST",
    "path": "karnema-events",
    "responseMode": "responseNode",
    "options": {
     "rawBody": true
    }
   },
   "name": "رویداد کارنما",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    0
   ],
   "webhookId": "a1f5c0d2-0000-4000-8000-000000000004"
  },
  {
   "parameters": {
    "jsCode": "// امضای کارنما: HMAC-SHA256 بدنهٔ خام با کلید امضای وب‌هوک، hex در سرآیند X-Webhook-Signature.\n// نیاز: NODE_FUNCTION_ALLOW_BUILTIN=crypto و متغیر KARNEMA_WEBHOOK_SECRET.\nconst crypto = require('crypto');\nconst results = [];\nfor (let i = 0; i < $input.all().length; i++) {\n  const item = $input.all()[i];\n  const raw = await this.helpers.getBinaryDataBuffer(i, 'data');\n  const expected = crypto.createHmac('sha256', $env.KARNEMA_WEBHOOK_SECRET).update(raw).digest('hex');\n  const given = String(item.json.headers['x-webhook-signature'] ?? '');\n  const valid = given.length === expected.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));\n  const event = JSON.parse(raw.toString('utf8'));\n  results.push({ json: { valid, eventType: event.eventType, eventId: event.eventId, occurredAtUtc: event.occurredAtUtc, data: event.data } });\n}\nreturn results;"
   },
   "name": "بررسی امضا",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    240,
    0
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "typeValidation": "strict",
      "version": 2
     },
     "conditions": [
      {
       "id": "sig",
       "leftValue": "={{ $json.valid }}",
       "rightValue": true,
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "امضا درست است؟",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    480,
    0
   ]
  },
  {
   "parameters": {
    "respondWith": "json",
    "responseBody": "={\"ok\": false}",
    "options": {
     "responseCode": 401
    }
   },
   "name": "رد (401)",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    720,
    200
   ]
  },
  {
   "parameters": {
    "respondWith": "json",
    "responseBody": "={{ JSON.stringify({ ok: true, received: $json.eventId }) }}",
    "options": {}
   },
   "name": "رسید (200)",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    720,
    -100
   ]
  },
  {
   "parameters": {
    "rules": {
     "values": [
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "typeValidation": "strict",
         "version": 2
        },
        "conditions": [
         {
          "leftValue": "={{ $json.eventType }}",
          "rightValue": "ProcessRequest",
          "operator": {
           "type": "string",
           "operation": "startsWith"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "درخواست"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "typeValidation": "strict",
         "version": 2
        },
        "conditions": [
         {
          "leftValue": "={{ $json.eventType }}",
          "rightValue": "DossierRecordSaved",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "سند پرونده"
      }
     ]
    },
    "options": {
     "fallbackOutput": "extra",
     "renameFallbackOutput": "سایر"
    }
   },
   "name": "نوع رویداد",
   "type": "n8n-nodes-base.switch",
   "typeVersion": 3.2,
   "position": [
    960,
    -100
   ]
  },
  {
   "parameters": {
    "method": "GET",
    "url": "={{ $env.KARNEMA_BASE_URL }}/requests/{{ $json.data.InstanceId }}",
    "authentication": "genericCredentialType",
    "genericAuthType": "httpHeaderAuth",
    "options": {
     "response": {
      "response": {
       "fullResponse": false,
       "neverError": false
      }
     }
    }
   },
   "name": "کارنما: جزئیات درخواست",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1200,
    -200
   ],
   "credentials": {
    "httpHeaderAuth": {
     "id": "karnemaApiKey",
     "name": "Karnema API Key"
    }
   }
  },
  {
   "parameters": {
    "mode": "manual",
    "assignments": {
     "assignments": [
      {
       "id": "خلاصهٔ درخواست-0",
       "name": "event",
       "value": "={{ $('نوع رویداد').item.json.eventType }}",
       "type": "string"
      },
      {
       "id": "خلاصهٔ درخواست-1",
       "name": "trackingNumber",
       "value": "={{ $json.request.trackingNumber }}",
       "type": "number"
      },
      {
       "id": "خلاصهٔ درخواست-2",
       "name": "title",
       "value": "={{ $json.request.title }}",
       "type": "string"
      },
      {
       "id": "خلاصهٔ درخواست-3",
       "name": "status",
       "value": "={{ $json.request.status }}",
       "type": "string"
      },
      {
       "id": "خلاصهٔ درخواست-4",
       "name": "answers",
       "value": "={{ $json.answers.map(a => a.label + ': ' + a.value).join(' | ') }}",
       "type": "string"
      }
     ]
    },
    "options": {}
   },
   "name": "خلاصهٔ درخواست",
   "type": "n8n-nodes-base.set",
   "typeVersion": 3.4,
   "position": [
    1440,
    -200
   ]
  },
  {
   "parameters": {},
   "name": "ثبت سند در ERP (جای اتصال شما)",
   "type": "n8n-nodes-base.noOp",
   "typeVersion": 1,
   "position": [
    1200,
    0
   ]
  },
  {
   "parameters": {},
   "name": "سایر رویدادها",
   "type": "n8n-nodes-base.noOp",
   "typeVersion": 1,
   "position": [
    1200,
    150
   ]
  },
  {
   "parameters": {
    "content": "## دریافت رویدادهای کارنما\nنشانی این گره را در «مدیریت ← وب‌هوک‌ها»ی کارنما ثبت کنید (برای ProcessRequest*، DossierRecordSaved…).\nامضای HMAC بررسی می‌شود؛ رویداد نادرست 401 می‌گیرد. برای رویدادهای درخواست، جزئیات کامل (پاسخ‌های فرم و وضعیت) از کارنما خوانده می‌شود.\nمتغیر: KARNEMA_WEBHOOK_SECRET (کلید امضایی که کارنما هنگام ساخت وب‌هوک یک بار نشان می‌دهد)",
    "height": 260,
    "width": 420
   },
   "name": "راهنما",
   "type": "n8n-nodes-base.stickyNote",
   "typeVersion": 1,
   "position": [
    -420,
    -260
   ]
  }
 ],
 "connections": {
  "رویداد کارنما": {
   "main": [
    [
     {
      "node": "بررسی امضا",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "بررسی امضا": {
   "main": [
    [
     {
      "node": "امضا درست است؟",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "امضا درست است؟": {
   "main": [
    [
     {
      "node": "رسید (200)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "رد (401)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "رسید (200)": {
   "main": [
    [
     {
      "node": "نوع رویداد",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "نوع رویداد": {
   "main": [
    [
     {
      "node": "کارنما: جزئیات درخواست",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "ثبت سند در ERP (جای اتصال شما)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "سایر رویدادها",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "کارنما: جزئیات درخواست": {
   "main": [
    [
     {
      "node": "خلاصهٔ درخواست",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "active": false,
 "settings": {
  "executionOrder": "v1"
 },
 "pinData": {},
 "tags": []
}