{
 "id": "gfpayledger00001",
 "name": "Payment to ledger",
 "nodes": [
  {
   "name": "Payment event (webhook)",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    300
   ],
   "webhookId": "8f4c1d1e-2b7a-4c8e-9a10-3d5e6f7a8b01",
   "parameters": {
    "httpMethod": "POST",
    "path": "payment",
    "responseMode": "responseNode",
    "options": {}
   }
  },
  {
   "name": "Expected signature",
   "type": "n8n-nodes-base.crypto",
   "typeVersion": 1,
   "position": [
    220,
    300
   ],
   "parameters": {
    "action": "hmac",
    "type": "SHA256",
    "encoding": "hex",
    "dataPropertyName": "expected",
    "secret": "demo-secret-not-a-real-key",
    "value": "={{ $json.body.event_id }}.{{ $json.body.amount_cents }}.{{ $json.body.currency }}"
   }
  },
  {
   "name": "Check event",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    440,
    300
   ],
   "parameters": {
    "jsCode": "// Check the event before anything is written. A bad event is answered, never silently dropped.\nreturn $input.all().map(item => {\n  const b = item.json.body || {};\n  const problems = [];\n  const id = String(b.event_id ?? '').trim();\n  if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) problems.push('event_id missing or malformed');\n  if (b.type !== 'payment.succeeded') problems.push('unsupported event type');\n  if (!Number.isInteger(b.amount_cents) || b.amount_cents <= 0) problems.push('amount_cents must be a positive whole number');\n  if (!/^[A-Z]{3}$/.test(String(b.currency ?? ''))) problems.push('currency must be three capital letters');\n  if (!String(b.invoice ?? '').trim()) problems.push('invoice missing');\n  const given = String((item.json.headers || {})['x-demo-signature'] ?? '');\n  const signed = problems.length === 0 && given.length === 64 && given === item.json.expected;\n  if (problems.length === 0 && !signed) problems.push('signature does not match');\n  return { json: { event_id: id, invoice: b.invoice, customer: b.customer, amount_cents: b.amount_cents, currency: b.currency,\n    problems, status: problems.length === 0 ? 200 : (problems[0] === 'signature does not match' ? 401 : 400) } };\n});"
   }
  },
  {
   "name": "Event OK?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2,
   "position": [
    660,
    300
   ],
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "combinator": "and",
     "conditions": [
      {
       "id": "c1",
       "leftValue": "={{ $json.problems.length }}",
       "rightValue": 0,
       "operator": {
        "type": "number",
        "operation": "equals"
       }
      }
     ]
    },
    "options": {}
   }
  },
  {
   "name": "Reject event",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    880,
    500
   ],
   "parameters": {
    "respondWith": "json",
    "responseBody": "={{ JSON.stringify({ok:false, problems:$json.problems}) }}",
    "options": {
     "responseCode": "={{ $json.status }}"
    }
   }
  },
  {
   "name": "Book payment in ledger",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    880,
    200
   ],
   "retryOnFail": true,
   "maxTries": 3,
   "waitBetweenTries": 1000,
   "parameters": {
    "method": "POST",
    "url": "http://127.0.0.1:8771/ledger/payments",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Idempotency-Key",
       "value": "={{ $json.event_id }}"
      }
     ]
    },
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify({invoice:$json.invoice, customer:$json.customer, amount_cents:$json.amount_cents, currency:$json.currency}) }}",
    "options": {}
   }
  },
  {
   "name": "Write receipt draft",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1100,
    200
   ],
   "parameters": {
    "jsCode": "const p = $('Check event').item.json;\nconst amount = (p.amount_cents / 100).toFixed(2);\nreturn [{ json: { event_id: p.event_id, body:\n  `Receipt for ${p.invoice}\\n${p.customer}\\nPaid: ${amount} ${p.currency}\\n\\nThank you. (Fictional demo receipt. Saved as a draft, not sent.)` } }];"
   }
  },
  {
   "name": "Save receipt draft",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1320,
    200
   ],
   "parameters": {
    "method": "POST",
    "url": "http://127.0.0.1:8771/receipts/draft",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($json) }}",
    "options": {}
   }
  },
  {
   "name": "Acknowledge",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    1540,
    200
   ],
   "parameters": {
    "respondWith": "json",
    "responseBody": "={{ JSON.stringify({ok:true, event_id:$('Check event').item.json.event_id, booked:$('Book payment in ledger').item.json.booked, deliveries:$('Book payment in ledger').item.json.deliveries}) }}",
    "options": {}
   }
  }
 ],
 "connections": {
  "Payment event (webhook)": {
   "main": [
    [
     {
      "node": "Expected signature",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Expected signature": {
   "main": [
    [
     {
      "node": "Check event",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Check event": {
   "main": [
    [
     {
      "node": "Event OK?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Event OK?": {
   "main": [
    [
     {
      "node": "Book payment in ledger",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Reject event",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Book payment in ledger": {
   "main": [
    [
     {
      "node": "Write receipt draft",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Write receipt draft": {
   "main": [
    [
     {
      "node": "Save receipt draft",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Save receipt draft": {
   "main": [
    [
     {
      "node": "Acknowledge",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "settings": {
  "executionOrder": "v1",
  "saveDataSuccessExecution": "all",
  "saveDataErrorExecution": "all",
  "saveManualExecutions": true,
  "errorWorkflow": "gffailalert00001"
 },
 "active": false,
 "pinData": {}
}
