{
  "name": "Prinzipspur #02 — Automatischer KI-Rechnungseingang (GoBD + XML/PDF Weiche)",
  "nodes": [
    {
      "parameters": {
        "mailbox": "INBOX",
        "postProcessAction": "read",
        "downloadAttachments": true,
        "options": {}
      },
      "id": "node-imap-trigger",
      "name": "1. Sammler: IMAP Rechnungs-Postfach",
      "type": "n8n-nodes-base.emailReadImap",
      "typeVersion": 2,
      "position": [220, 300]
    },
    {
      "parameters": {
        "jsCode": "const crypto = require('crypto');\nconst items = $input.all();\nconst out = [];\n\nfor (const item of items) {\n  const bin = item.binary || {};\n  const keys = Object.keys(bin);\n  if (keys.length === 0) {\n    out.push({ json: { ...item.json, routing: 'NO_ATTACHMENT', received_at: new Date().toISOString() } });\n    continue;\n  }\n  for (const k of keys) {\n    const att = bin[k];\n    const buf = Buffer.from(att.data, 'base64');\n    const sha256 = crypto.createHash('sha256').update(buf).digest('hex');\n    const fname = (att.fileName || 'beleg').toLowerCase();\n    const isXml = fname.endsWith('.xml') || buf.includes(Buffer.from('CrossIndustryInvoice')) || buf.includes(Buffer.from('zugferd'));\n    out.push({\n      json: {\n        mail_subject: item.json.subject || '',\n        mail_from: item.json.from || '',\n        original_filename: att.fileName,\n        mime_type: att.mimeType,\n        sha256_hash: sha256,\n        received_at: new Date().toISOString(),\n        routing: isXml ? 'STRUCTURED_EINVOICE' : 'PDF_OR_SCAN'\n      },\n      binary: { data: att }\n    });\n  }\n}\nreturn out;"
      },
      "id": "node-gobd-hash-router",
      "name": "2. Tresor & Weiche: SHA-256 Hash + XML/PDF Erkennung",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [480, 300]
    },
    {
      "parameters": {
        "operation": "write",
        "fileName": "=/archiv_rohbelege/{{ $now.format('yyyy-MM') }}/{{ $json.sha256_hash.slice(0,12) }}_{{ $json.original_filename }}",
        "dataPropertyName": "data"
      },
      "id": "node-gobd-archive",
      "name": "2b. GoBD Roh-Archiv (Unverändertes Original sichern)",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [740, 180]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": { "caseSensitive": true },
                "conditions": [{ "leftValue": "={{ $json.routing }}", "rightValue": "STRUCTURED_EINVOICE", "operator": { "type": "string", "operation": "equals" } }]
              },
              "renameOutput": true,
              "outputKey": "E-Rechnung (XML)"
            },
            {
              "conditions": {
                "options": { "caseSensitive": true },
                "conditions": [{ "leftValue": "={{ $json.routing }}", "rightValue": "PDF_OR_SCAN", "operator": { "type": "string", "operation": "equals" } }]
              },
              "renameOutput": true,
              "outputKey": "PDF / Beleg"
            },
            {
              "conditions": {
                "options": { "caseSensitive": true },
                "conditions": [{ "leftValue": "={{ $json.routing }}", "rightValue": "NO_ATTACHMENT", "operator": { "type": "string", "operation": "equals" } }]
              },
              "renameOutput": true,
              "outputKey": "Portal-Liste"
            }
          ]
        }
      },
      "id": "node-format-switch",
      "name": "3. Format-Weiche (0ct XML vs. KI vs. Portal)",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [740, 400]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://openrouter.ai/api/v1/chat/completions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"model\": \"openai/gpt-4o-mini\",\n  \"temperature\": 0,\n  \"response_format\": { \"type\": \"json_object\" },\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"Extrahiere Rechnungsdaten streng als JSON mit den Schlüsseln: ist_echte_rechnung (boolean; false bei Angebot, Proforma, Lieferschein, Mahnung), ist_bewirtung (boolean), lieferant (string), rechnungsdatum_iso (YYYY-MM-DD), rechnungsnummer (string), netto (number), steuersatz_prozent (number), steuerbetrag (number), brutto (number), waehrung (EUR/USD/CHF), iban (string|null). Erfinde niemals Werte; nutze null wenn unlesbar.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"Dokumenttext / Metadaten prüfen: \" + JSON.stringify($json)\n    }\n  ]\n}"
      },
      "id": "node-ai-extractor",
      "name": "4. KI-Prüfer (Strenges JSON-Schema)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1020, 400]
    },
    {
      "parameters": {
        "jsCode": "const raw = JSON.parse($json.choices[0].message.content);\nconst diff = Math.abs((Number(raw.netto || 0) + Number(raw.steuerbetrag || 0)) - Number(raw.brutto || 0));\nconst mathOk = diff <= 0.03 && Number(raw.brutto || 0) > 0;\nconst cleanVendor = String(raw.lieferant || 'Unbekannt').replace(/[^a-zA-Z0-9äöüÄÖÜß-]/g, '-').slice(0, 35);\nconst cleanNr = String(raw.rechnungsnummer || 'OHNE-NR').replace(/[^a-zA-Z0-9-]/g, '-');\nconst cleanAmt = Number(raw.brutto || 0).toFixed(2).replace('.', '-') + (raw.waehrung || 'EUR');\nconst targetFilename = `${raw.rechnungsdatum_iso || 'DATUM-PRUEFEN'}_${cleanVendor}_${cleanNr}_${cleanAmt}.pdf`;\n\nreturn [{\n  json: {\n    ...raw,\n    math_check_passed: mathOk,\n    math_diff_eur: Number(diff.toFixed(2)),\n    ziel_ordner: (!raw.ist_echte_rechnung || !mathOk) ? '02_MANUELLE_PRUEFUNG' : '01_BEREIT_FUER_STEUERBERATER',\n    ziel_dateiname: targetFilename,\n    hinweis_bewirtung: raw.ist_bewirtung ? 'ACHTUNG: Anlass + Teilnehmer auf Beleg ergänzen!' : null\n  }\n}];"
      },
      "id": "node-deterministic-math-guard",
      "name": "5. Deterministischer Mathe- & Dubletten-Wächter",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1280, 400]
    }
  ],
  "connections": {
    "1. Sammler: IMAP Rechnungs-Postfach": {
      "main": [[{ "node": "2. Tresor & Weiche: SHA-256 Hash + XML/PDF Erkennung", "type": "main", "index": 0 }]]
    },
    "2. Tresor & Weiche: SHA-256 Hash + XML/PDF Erkennung": {
      "main": [
        [
          { "node": "2b. GoBD Roh-Archiv (Unverändertes Original sichern)", "type": "main", "index": 0 },
          { "node": "3. Format-Weiche (0ct XML vs. KI vs. Portal)", "type": "main", "index": 0 }
        ]
      ]
    },
    "3. Format-Weiche (0ct XML vs. KI vs. Portal)": {
      "main": [
        [],
        [{ "node": "4. KI-Prüfer (Strenges JSON-Schema)", "type": "main", "index": 0 }],
        []
      ]
    },
    "4. KI-Prüfer (Strenges JSON-Schema)": {
      "main": [[{ "node": "5. Deterministischer Mathe- & Dubletten-Wächter", "type": "main", "index": 0 }]]
    }
  },
  "settings": { "executionOrder": "v1" }
}
