{
  "name": "XRechnung und ZUGFeRD aus dem Postfach auslesen",
  "nodes": [
    {
      "parameters": {
        "mailbox": "INBOX",
        "postProcessAction": "read",
        "downloadAttachments": true,
        "options": {}
      },
      "id": "5aaed988-6571-5b15-8cf6-e46062271717",
      "name": "Postfach rechnung@ prüfen",
      "type": "n8n-nodes-base.emailReadImap",
      "typeVersion": 2,
      "position": [
        -440,
        0
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1c57e97-415c-5872-86b2-6187c8a2d04c",
              "name": "absender",
              "value": "automation@ihre-firma.de",
              "type": "string"
            },
            {
              "id": "4a8258f6-1ed0-5821-a315-f1877f846ac8",
              "name": "buchhaltung_an",
              "value": "buchhaltung@ihre-firma.de",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {
          "includeBinary": true
        }
      },
      "id": "5c1e4475-249b-5302-b9ac-bdc4b89cd19c",
      "name": "Konfiguration",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -200,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Jeden Anhang als eigenes Item weitergeben (nur PDF und XML)\nconst out = [];\nfor (const item of $input.all()) {\n  for (const [key, bin] of Object.entries(item.binary ?? {})) {\n    const name = (bin.fileName || '').toLowerCase();\n    if (!/(\\.pdf|\\.xml)$/.test(name)) continue;\n    out.push({\n      json: { betreff: item.json.subject, von: item.json.from, datei: bin.fileName, typ: name.endsWith('.xml') ? 'xml' : 'pdf' },\n      binary: { data: bin },\n    });\n  }\n}\nreturn out;"
      },
      "id": "53382e6d-cdd1-5eb0-a5f6-3d179d0b4a84",
      "name": "Anhänge einzeln",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        40,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "332c22a6-4346-525d-9e3d-66b64f6472fd",
              "leftValue": "={{ $json.typ }}",
              "rightValue": "xml",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "bfc0dcf3-a493-5008-8d4b-cf82ffe38e3d",
      "name": "Ist XML?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        260,
        0
      ]
    },
    {
      "parameters": {
        "operation": "text",
        "binaryPropertyName": "data",
        "destinationKey": "xml",
        "options": {}
      },
      "id": "cf2cdacd-922d-5046-8c26-df7ccdbd4e85",
      "name": "XML als Text",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1,
      "position": [
        480,
        -80
      ]
    },
    {
      "parameters": {
        "mode": "xmlToJson",
        "dataPropertyName": "xml",
        "options": {
          "explicitArray": false,
          "ignoreAttrs": true
        }
      },
      "id": "820d6816-0f44-5378-9fdc-4527f2abc7a2",
      "name": "XML zu JSON",
      "type": "n8n-nodes-base.xml",
      "typeVersion": 1,
      "position": [
        700,
        -80
      ]
    },
    {
      "parameters": {
        "jsCode": "// Wichtigste Felder aus XRechnung (UBL oder CII) bzw. ZUGFeRD-XML lesen\nconst pick = (o, path) => path.split('.').reduce((a, k) => (a == null ? a : (Array.isArray(a) ? a[0] : a)[k]), o);\nconst val = (v) => (v == null ? null : typeof v === 'object' ? (v._ ?? v['#text'] ?? JSON.stringify(v)) : v);\nreturn $input.all().map((item) => {\n  const j = item.json;\n  const rootKey = Object.keys(j).find((k) => /CrossIndustryInvoice|Invoice|CreditNote/.test(k));\n  const r = j[rootKey] ?? {};\n  const key = (o, name) => o && Object.keys(o).find((k) => k.split(':').pop() === name);\n  const g = (o, ...names) => names.reduce((a, n) => { if (a == null) return a; const x = Array.isArray(a) ? a[0] : a; const k = key(x, n); return k ? x[k] : undefined; }, o);\n  let out;\n  if (/CrossIndustryInvoice/.test(rootKey)) {\n    const tx = g(r, 'SupplyChainTradeTransaction');\n    const agr = g(tx, 'ApplicableHeaderTradeAgreement');\n    const set = g(tx, 'ApplicableHeaderTradeSettlement');\n    const sum = g(set, 'SpecifiedTradeSettlementHeaderMonetarySummation');\n    out = {\n      format: 'CII (ZUGFeRD/XRechnung)',\n      rechnungsnummer: val(g(r, 'ExchangedDocument', 'ID')),\n      datum: val(g(r, 'ExchangedDocument', 'IssueDateTime', 'DateTimeString')),\n      lieferant: val(g(agr, 'SellerTradeParty', 'Name')),\n      leitweg_id: val(g(agr, 'BuyerReference')),\n      netto: val(g(sum, 'TaxBasisTotalAmount')),\n      brutto: val(g(sum, 'GrandTotalAmount')),\n      zahlbetrag: val(g(sum, 'DuePayableAmount')),\n      iban: val(g(set, 'SpecifiedTradeSettlementPaymentMeans', 'PayeePartyCreditorFinancialAccount', 'IBANID')),\n    };\n  } else {\n    const mon = g(r, 'LegalMonetaryTotal');\n    out = {\n      format: 'UBL (XRechnung)',\n      rechnungsnummer: val(g(r, 'ID')),\n      datum: val(g(r, 'IssueDate')),\n      lieferant: val(g(r, 'AccountingSupplierParty', 'Party', 'PartyName', 'Name')) ?? val(g(r, 'AccountingSupplierParty', 'Party', 'PartyLegalEntity', 'RegistrationName')),\n      leitweg_id: val(g(r, 'BuyerReference')),\n      netto: val(g(mon, 'TaxExclusiveAmount')),\n      brutto: val(g(mon, 'TaxInclusiveAmount')),\n      zahlbetrag: val(g(mon, 'PayableAmount')),\n      iban: val(g(r, 'PaymentMeans', 'PayeeFinancialAccount', 'ID')),\n    };\n  }\n  return { json: { ...out, datei: item.json.datei } };\n});"
      },
      "id": "13a94a7a-8355-5c48-89ad-96f8dad1d859",
      "name": "Rechnungsfelder lesen",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        -80
      ]
    },
    {
      "parameters": {
        "fromEmail": "={{ $('Konfiguration').first().json.absender }}",
        "toEmail": "={{ $('Konfiguration').first().json.buchhaltung_an }}",
        "subject": "=E-Rechnung: {{ $json.lieferant }} {{ $json.rechnungsnummer }}",
        "emailFormat": "text",
        "text": "=Neue E-Rechnung ({{ $json.format }})\n\nLieferant: {{ $json.lieferant }}\nRechnungsnr.: {{ $json.rechnungsnummer }} vom {{ $json.datum }}\nNetto: {{ $json.netto }} · Brutto: {{ $json.brutto }} · Zahlbetrag: {{ $json.zahlbetrag }}\nIBAN: {{ $json.iban }}\nKäuferreferenz: {{ $json.leitweg_id }}\nDatei: {{ $json.datei }}",
        "options": {}
      },
      "id": "c52300ee-faf7-522c-942c-e3180d24d8b8",
      "name": "An Buchhaltung",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1140,
        -80
      ]
    },
    {
      "parameters": {
        "content": "## E-Rechnungen (XML) automatisch auslesen\nVorlage von roiwerk.com\n\nLiest XRechnung (UBL und CII) und ZUGFeRD-XML ohne KI aus: Die Daten stehen strukturiert im XML.\n\n1. IMAP-Zugang hinterlegen\n2. Empfänger in **Konfiguration** anpassen\n3. Statt E-Mail können die Daten direkt an DATEV, lexoffice, sevdesk oder eine Tabelle gehen\n\nZum Ansehen einzelner Rechnungen: roiwerk.com/tools/xrechnung-viewer",
        "height": 340,
        "width": 420
      },
      "id": "2b92f5a1-81a5-5279-be40-3d66d2e5aca2",
      "name": "Hinweis",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -260,
        -420
      ]
    }
  ],
  "connections": {
    "Postfach rechnung@ prüfen": {
      "main": [
        [
          {
            "node": "Konfiguration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Konfiguration": {
      "main": [
        [
          {
            "node": "Anhänge einzeln",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Anhänge einzeln": {
      "main": [
        [
          {
            "node": "Ist XML?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ist XML?": {
      "main": [
        [
          {
            "node": "XML als Text",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "XML als Text": {
      "main": [
        [
          {
            "node": "XML zu JSON",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "XML zu JSON": {
      "main": [
        [
          {
            "node": "Rechnungsfelder lesen",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Rechnungsfelder lesen": {
      "main": [
        [
          {
            "node": "An Buchhaltung",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false,
    "source": "https://roiwerk.com/vorlagen/n8n-workflow-vorlagen"
  },
  "tags": []
}